text stringlengths 20 1.01M | url stringlengths 14 1.25k | dump stringlengths 9 15 ⌀ | lang stringclasses 4
values | source stringclasses 4
values |
|---|---|---|---|---|
CodePlexProject Hosting for Open Source Software
If I have a migration file with multiple methods that are to be executed then all the migrations are run, but the version number in Orchard_Framework_DataMigrationRecord is not correct.
For example, if I have the following methods in my Migration file, when I update both columns will be added, but the version number in the Orchard_Framework_DataMigrationRecord table will be 5 rather than 6.
public int UpdateFrom4() {
SchemaBuilder.AlterTable("RecentBlogPostsPartRecord",
table => table
.AddColumn("Test2", DbType.DateTime)
);
return 5;
}
public int UpdateFrom5()
{
SchemaBuilder.AlterTable("RecentBlogPostsPartRecord",
table => table
.AddColumn("Test3", DbType.DateTime)
);
return 6;
}
I have debugged the code in the DataMigrationManager class and the dataMigrationRecord.Version property seems to be set to the correct value, but when the SQL update statement is executed it has the wrong version number. I'm finding it difficult
to see what is going wrong because it just seems to be in the NHibenate code.
This looks to me to be a bug. Anyone else seeing this?
I suspect this is something to do with the NHibernate versioning. I added an additional property to the DataMigrationRecord class and associated table and that property seems to work fine.
I think you are right. A column named "Version" has a pre-defined meaning for NHibernate wrt to versioning. I would open a bug about this (nice find!)
public class DataMigrationRecord {
public virtual int Id { get; set; }
public virtual string DataMigrationClass { get; set; }
public virtual int Version { get; set; }
}
Okay, thanks. Bug opened here
Are you sure you want to delete this post? You will not be able to recover it later.
Are you sure you want to delete this thread? You will not be able to recover it later. | http://orchard.codeplex.com/discussions/271740 | CC-MAIN-2017-51 | en | refinedweb |
Decorators are very useful functionality in Python. Here am going in a straight forward way to get a quick basic idea about what a decorator means. You can find what is a decorator and more details from here.
Excerpt from python wiki about decorator: A decorator is the name used for a software design pattern. Decorators dynamically alter the functionality of a function, method, or class without having to directly use subclasses or change the source code of the function being decorated.
Lets go through an example.
@login_required def account_settings(request): #some code
Here login_required is a decorator. Decorator is nothing but another function. But it’s functionality is different. While running this code, when the python interpreter see some decorator ( here it is login_required) it calls the decorator with the below function as argument (that means ‘account_settings’ as argument). Then we can do some preprocessing with the function inside decorator. Such as, using the details from function arguments we can check whether user is logined or not, if not logined redirect to login page etc.
In short using a decorator we can do some action before a particular function is called.( can do more than this!).
So how a decorator look like. Am giving a simple outline of a decorator:
def login_required(func_name): def decorator(request, *args, **kwargs): #if not logined: # redirect to log in page #else: #allow to access settings return decorator
Some points:
1) The inner function name ‘decorator’ is optional. You can choose a different name also. But you should return that name in the end. That means if you use the name ‘myfunc’ as function name, then you should return ‘myfunc’.
2) If you are sure about the number of parameter and its type you can use it directly as inner function (here ‘decorator’) parameter. If you know there should be two parameters(say ‘a’ and ‘b’ ) for account_settings function, then you can define inner function as ‘decorator(a,b)’ .
if you want to know more about decorators, this is a good tutorial.
Doh! I was domain searching at namecheap.com and went to type
in the domain name:.
com/2012/05/01/a-simple-decorator-in-python/ and guess who already
purchased it? You did! lol j/k. I was about to purchase
this domain name but noticed it had been taken so I figured I’d come check it out. Nice blog! | https://jineshpaloor.wordpress.com/2012/05/01/a-simple-decorator-in-python/ | CC-MAIN-2017-51 | en | refinedweb |
From Content to Knowledge: a Perspective on CMS**
- Isabel Cook
- 2 years ago
- Views:
Transcription
1 AUTOMATYKA 2007 Tom 11 Zeszyt 1 2 Grzegorz J. Nalepa*, Antoni Ligêza*, Igor Wojnicki* From Content to Knowledge: a Perspective on CMS** 1. Introduction The Internet has become a single most important resource for instant information sharing. From the point of view of ordinary users it can be considered to constitute a very flexible and powerful version of the concept of the so-called blackboard architecture. The rapid growth of the Internet prompted a rapid development of specific software. This software addresses different aspects of information organization and interchange related issues, such as storing, retrieval, searching, indexing, aggregating, sharing, updating, etc. Taking into account the size and flexibility of the system as a whole, these problems constitute a real challenge. Content Management Systems (CMS for short) emerged as a technology providing a unified interface for large databases or data warehouses. In a broad sense a CMS consists of: a RDBMS (Relational Data Base System) which stores the data, and a complex webbased application or interface providing the access to the data. The web interface is built around using common web technologies. This software requires a proper and efficient runtime environment, including a web server. An important aspect of a CMS system is the possibility of user personalization, tracking, and interactive use. Today web technologies constitute an advanced and universal programming framework. This framework has a very heterogeneous structure including: data encoding and structuring languages (such as HTML and XML), meta-data languages (such as RDF), data transformation languages (such as XSL/T/FO), data presentation languages (such as CSS), server-side programming languages (such as PHP, JSP), and client-side programming languages (such as Javascript). Rapid development of CMSs has been stimulated by the so-called opensource LAMP platform, which provides a vary portable and accessible deployment environment for a CMS. LAMP originally stood for GNU/Linux Apache SQL PHP. PHP is an advanced * Institute of Automatics, AGH University of Science and Technology ** The paper is supported from the AGH UST grant No
2 218 Grzegorz J. Nalepa, Antoni Ligêza, Igor Wojnicki and very common server-side programming platform for developing web applications. First versions of PHP were best suited for Apache, the most important (and most popular) web server on the Internet. SQL has been the first open source RDBMS which provided a relatively high efficiency along with good integration with PHP, today it may be often replaced by some technologically superior solutions such as PostgreSQL. All of these software tools were originally tailored for the GNU/Linux operating system environment, which provided an accessible, efficient, and low-cost deployment platform. Today there is a very large group of FLOSS (Free/Libre, Open Source Software) CMS systems. Multiple CMS categories can be identified erg., web portals, group ware suites, forum sites, and e-learning toolkits. In each of these cases the content they manage differs. From knowledge management perspective this content may be seen as a particular kind of knowledge. In order to design and implement a CMS, knowledge representation methods should be taken into account. While all of the CMS systems provide some kind on knowledge acquisition facilities, few of them focus on using proper knowledge representation method, that would simplify the acquisition and design process. This paper presents results an critical overview of architecture and main classes of CMS. The overview has been conducted in order to identify main issues related to knowledge representation in CMS. In the paper some practical guidelines for improving existing CMS, and turning them into knowledge-oriented systems have been given. 2. CMS Architecture Content Management Systems (CMS for short) emerged as a technology providing a unified interface for large databases or data warehouses. In a broad sense a CMS consists of: the server side: a RDBMS (Relational Data Base System) which stores the content, and a complex web-based application or interface providing the access to the content; the client side: a web browser that renders the content in the visual manner. The clients are connected to the server via the computer network. It is the Internet in the general case, but it can also be an Internet network, an Internet. On the server side several several software elements can be identified: a RDBMS server which stores the content, and provides a query facility, in case of FLOSS; the main CMS application, implemented in some high level language, such as PHP, JSP, or ASP; this application accesses the content RDBMS system using SQL (or in some cases technologies such as ODBC), and encodes the results of the query using XML or HTML;
3 From Content to Knowledge: a Perspective on CMS 219 the application runtime, such as PHP interpreter, Java Virtual Machine, or ASP runtime; the web server, which is integrated with the application runtime, and serves the XMLencoded content via the HTTP protocol; the operating system environment (erg. GNU/Linux, BSD, Unix), which provides a proper and efficient run-time for all of the above components, including an efficient TCP/IP network stack. The main element on the client side is the web browser. In a simplest case its job is to simply render the XML-encoded content. It often has some basic programming capabilities, mainly Java Script. In some cases it is integrated with the JVM (Java Virtual Machine) which allows for full-scale application programming Considering the architecture, the core software, called the CMS runtime here, can be identified. The runtime includes: an RDBMS, a server side programming language, a web server, content encoding and description languages, web browser, and client-side programming language. For all of this components some well established technologies are provided. 3. CMS Classes CMS are not a heterogeneous software collection. Several classes or groups can be identified. The main differentiating factor is the type of web system they are oriented for. Basing on research, supported by [1, 2] in the following subsections main CMS classes are identified and described Portals This is the main class of CMS, grouping the largest number of software solutions. Portal CMS are designed to build a so-called web portal, a web site presenting multiple categories of content, with advanced user profiling capabilities. Portals are extensively used by news or domain-specific content providers. They are often combined with advertisement and e-commerce facilities. They provide user accounts in order to profile the content for the specific user, and track user activity. Portals are usually heavily linked with other web sites concerning the content. There is a large number of this class of CMS implementations. Some most mature and well established are: Dru pal (), Mambo (), Plone (), PHP Nuke (phpnuke.org), PostNuke (postnuke.com). An example application of such a system may be found in [6] and is shown in Figure 1. It shows the SOPD systems, which supports students thesis presentation, and assignment in Institute of Automatics AGH.
4 220 Grzegorz J. Nalepa, Antoni Ligêza, Igor Wojnicki Fig. 1. SOPD system page example Source: own research and [6] 3.2. Group ware Group ware CMS provide an on-line environment supporting the problem of group work coordination. This includes tasks like: contact management, and instant messaging support, distributed editor environment, possibly with version control, calendars and schedule controllers, as wheel as message boards, etc. There are numerous applications of such systems, including the support for a large local company, as well as distributed worldwide enterprise; these task can allow for communication with customers, by including a CRM part (Customer Relationship Management). Some popular implementations of such systems include: PhpGroupWare (), WebCollab (webcollab.sf.net), NetOffice (netoffice.sf.net) Forums Forums provide a complete solution for asynchronous discussion of large number of people. They allow for exchanging ideas between experts. They have also become one of
5 From Content to Knowledge: a Perspective on CMS 221 the preferred solution for on-line technical customer support for number of software and hardware companies. Some best examples of forum CMS are: Forum (), PhpBB () E-Commerce A special group of CMS systems is oriented towards e-commerce solutions. These are usually dedicated portals, with some additional features built-in. These features include a secure user data management, advanced user profiles and tracking, on-line shopping carts, and complex presentation modules for product catalogs, etc. Several system exist in this class: oscommerce (), PhpShop (), ZenCart () E-Learning CMS are one of key components in on-line e-learning solutions. They support the process of entering the content for e-learning suites as well as the learning process itself. They gain an increasing popularity by adopting some established standards such as SCORM. One of the best examples of such systems is Noodle (), others include: Atutor (), Dukeos () Miscellaneous Besides all of the above systems there are number of other solutions. They support some common on-line activities, such as: logging, wiki creation, personal image galleries, and so one. Some popular systems are: Bologna (), PhpWiki (), Gallery (gallery.sf.net). 4. Wiki Systems The wiki concept emerged in 90 s. The main idea behind was to create a tool for communication and knowledge sharing to be simultaneously simple and powerful. Thus, the main features follow this idea. A wiki system is mainly a collaboration tool. It allows multiple users access, read, edit, upload and download documents. Documents are text based enriched with so-called wiki markup. It is a simplistic, tag based, text only language which allows to annotate text with information regarding the way how it should be presented. Such an enriched text is called Cronkite. The tags allow to make sections, subsection, tables, items and other typographic operational Cronkite remains human readable, tags are intuitive and easy to learn. Each document is identified by a keyword uniquely, which makes a wiki concept similar to the encyclopedia concept. Furthermore a document, in addition to typographic tags mentioned earlier, can contain hyper links to other documents. A hyper link is a document name enclosed by a link tag. Furthermore a wiki allows to upload images, and other files as well. Wikis are mostly web based. A web interface allows to access a wiki, render pages,
6 222 Grzegorz J. Nalepa, Antoni Ligêza, Igor Wojnicki and edit them. Depending on particular solutions there might be access control and authorization mechanisms guarding access implemented as well. One of the most important features of a Wiki is an integrated version control. Each page modification is recorded. At any time a user can access a page and its previous versions. A wiki system is usually based on some server side processing technologies providing the web application, and optionally a database backed. As a fronted a web browser is used. It is worth pointing out that wiki Systems currently blend with CMS. Some CMS provide wiki functionality while some Wilkins evolve into CMS. Similarly Wilkins are more and more often merged with e-learning systems to support collaborative knowledge gathering and sharing. One of the most interesting wiki systems for developers is DokuWiki (http:// wiki.splitbrain.org/wiki:dokuwiki). It is designed to be both easy to use and easy to set up. DokuWiki is based on PHP and does not require a database backend. Pages are stored as versioned text files which enables easy backup-restore operations. It allows image embedding and file upload/download. Pages can be arranged into so-called name spaces which act as a tree-like hierarchy similar to directory structure. It also provide syntax highlighting for in-page embedded code for programming languages such as: C/C++, Java, Lisp, ADA, PHP, SQL and others, using GeSHi (). Furthermore it supports extensive user authentication and authorization mechanisms including Access Control Lists (ACL). Its modularized architecture allows to extend DokuWiki with plugins which provide additional syntax and functionality. The most popular plug ins provide: user and ACL management, log, gallery of pictures, discussion board, calendar, and LaTeX math and symbols. The DokuWiki system has been successfully used in AGH Institute of Automatics as the following applications: Research Project Team Collaboration, Student Projects, Student Collaboration (). Thanks to the DokuWiki extensive user authentication and ACL mechanisms user collaboration becomes seamless and information access can be controlled with a great precision. Regarding the Project Team Collaboration the Wiki pages were used to collect and publish domain specific information and data. Project Work Breakdown Structure and progress were stored and updated in the Wiki together with domain specific knowledge. Certain namespaces were chosen to publish information publicly and others to make it visible to the team members only. Since all information stored in the Wiki is subject to the version control feature gradual improvements to the gathered domain knowledge were possible. DokuWiki was also used as an information platform to hold student project subjects and descriptions. The subjects and descriptions were collaboratively developed by faculty members. Students were not allowed to modify the pages, since the projects were supervised by faculty members. Only faculty were allowed to add or modify information about project assignments and its progress. The third application regarded collaborative knowledge gathering regarding availability of certain technologies. Students were allowed to create, edit, delete and update pages belonging to a given namespace. Since the Wiki syntax is simple and easy to learn the was completed quickly.
7 From Content to Knowledge: a Perspective on CMS 223 DokuWiki proved to be a great tool aiding teaching and research processes. It can act as an easy to use and set up collaborative work environment. An example of the AGH IA wiki is shown in Figure 2. Fig. 2. AGH IA system page example Source: own research and [6] 5. Critical Perspective A review of the selected CMS revealed some common limitations. Even though the number of classes and implementations is quite large, few of the solutions are innovative. Most of them share some architectural patterns, and compete merely on technical level (e.g. Customizability, performance, etc.). Several types of limitations can be identified, namely: technical limitations, content management and portability problems, and most importantly, knowledge representation simplicity. A common technical limitation is the dependence on selected run-time technology, namely RDBS. Most of PHP-based solutions use an simplified PHP API for selected
8 224 Grzegorz J. Nalepa, Antoni Ligêza, Igor Wojnicki RDBMS. For performance reasons MySQL has been a popular solution for FLOSS CMS. However, until recently, it lacked some important RDBMS functions, such as transactions, which have always been present in PostgreSQL or Oracle. An obvious solution is to use some kind of database abstraction, such as ADOdb (adodb.sf.net) which supports number of RDBMS: MySQL, PostgreSQL, Interbase, Firebird, Informix, Oracle, MS SQL, Foxpro, Access, ADO, Sybase, FrontBase, DB2, SAP DB, SQLite, Netezza, LDAP, and generic ODBC, ODBTP, or some advanced modules available in PHP. Another technical limitation is poor support for W3C standards and technologies. Number of solutions are still HTML-dependent, whereas they should be based on XML. XML along with CSS not only allows for advanced content encoding, structuralization and presentation, it is also foundation for other important standards. XML-based meta-data languages such as RDF provide a unified framework for meta-level content description, including semantic information. When it comes the the actual management of the content the main problem is, that CMS systems provide limited content portability. As long as content is simply data, such as HTML, PDF documents, pictures and so-on CMS acts as a repository. When it comes to sharing information about the content, meta-data, or meta-knowledge, CMS systems do not provide appropriate facilities. This is mainly related to the lack of some common knowledge representation standards, while focusing on low-level encoding, and visual presentation of content. From knowledge management point-of-view, the crucial problem with CMS systems is, that they escape the knowledge representation and management pitfalls by assuming some predefined CMS structure, e.g. a portal. In this sense these CMS are only a kind o modifiable portal templates. It is difficult to choose knowledge representation for current CMS solutions, because the knowledge they store can be considered implicit, or even hidden. This criticism implicitly assumes that what CMS where designed to manage, and make available is somehow knowledge. That would put the process of deploying a CMS in the context knowledge engineering. In this field concepts such as knowledge representation, management, or validation are used. They refer to some common tasks in this field. However, considering how most of CMS are built, they cannot be considered Knowledge Management Systems. Turning current CMS into knowledge-oriented CMS should involve number of features. 6. Guidelines for Knowledge-based CMS There seems to be seven generic functionalities/areas that should be supported by any knowledge server ; these are [5]: knowledge representation and organization support; the system should provide appropriate structures and languages; knowledge processing and inference; the system should be capable of multi-paradigm reasoning and automated operations on knowledge; inference and operation control, user support, and operational decision making;
9 From Content to Knowledge: a Perspective on CMS 225 knowledge acquisition support and extraction of knowledge from different sources; user interface both for operational use and administration/design; truth-maintenance, verification and validation support; learning and optimization. These top-level general features are often translated into numerous detailed features. A critical area is an advanced explicit knowledge representation. In the field of knowledge engineering a number of representations, such as frames, trees, tables, concept networks, mind maps are available. Some new solutions, such as XTT, include even knowledge processing and logical analysis features [7]. Due to more and more complex nature of the encoded knowledge, as well as to the rapidly increasing size of knowledge bases, efficient techniques for supporting visual design and knowledge acquisition are becoming more popular. It is believed that more than 80% of information accepted by human comes through our eyes. Simultaneously, graphical knowledge representation is more intuitive and can be performed at different levels of abstraction. The XTT approach [5, 7] allows for hierarchical visualization of both knowledge (encoded in the form of tabular trees) and inference control (encoded in links of the tree/graph). Since modern systems can accept knowledge coming from heterogeneous sources and specified in different formats, it is more and more important to assure appropriate capabilities for knowledge evaluation, verification and validation. Some formal techniques are developed for knowledge encoded in logical and algebraic (tabular, tree-like) form [5, 7]. The knowledge encoding should not be limited to structure encoding (XML), but also meta-data, and semantics, for example using RDF. There are number of valuable developments in the field of languages for formal ontologies (OWL) which could improve CMS. In case of knowledge specified with rules, the RuleML [11] language offers some limited capabilities for knowledge specification, mostly with respect to structural specification useful for exchange and analysis. Unfortunately, semantic operations are not supported. Moreover, complex inference mechanism are neither designed not implemented. Knowledge Management [9] is a relatively new domain located at the intersection of knowledge engineering [5, 8], management in general, informations systems including expert systems [8], and intelligent web applications. An example of a system integrating various knowledge management techniques for enterprise applications is the PYTON system [12]. There are numerous efforts to meet the emerging requirements, however, in case of lack of consistent and uniform theoretical foundations efforts oriented towards building a knowledge server replacing, subsuming and covering database services, web applications and decision processes are far from being satisfactory. An example of an ongoing effort to build a so-called knowledge server (it could be considered knowledge-based CMS) is the CyC Project (cyc.com). The Cyc knowledge base. The Cyc KB is divided into
10 226 Grzegorz J. Nalepa, Antoni Ligêza, Igor Wojnicki many [4]. 7. Concluding Remarks The paper discusses certain issues concerning the so-called Content Management Systems (CMS) which can be regarded as a partial solution with respect to knowledge storing, retrieval and presentation. A critical perspective and state-of-the art of such systems is outlined. Contemporary tools and techniques applied in CMS are presented in brief and future problems to be solve are identified. Limitations of such systems are an inspiration to build knowledge management CMS in the form of a Knowledge Server. Some most important functionalities of potential Knowledge Sever are identified. A short discussion of possible application of existing and experimental tools to form components of the system is provided. It is pointed out that new technologies, such as XML related ones are not sufficient to satisfy the requirements. References [1] The Opensource CMS Website, Miro International Pty Ltd, 2005 [2] The CMS Matrix Website, Plain Black Corporation, 2005 [3] Ernst S., Pacewicz D., Klimek R.: Nowoczesne systemy zarz¹dzania treœci¹ w bazach danych i witrynach internetowych, 2005 [4] What is Cyc?, Cycorp, Inc, 2005 [5] Ligêza A.: Logical Foundations for Rule-Based Systems. Kraków, UST-AGH Press 2005 [6] az K., Szpakiewicz R.: Projekt i implementacja systemu obs³ugi prac dyplomowych baza danych z dostêpem internetowym. Kraków, AGH 2004 (praca dyplomowa, promotor: A. Ligêza) [7] Nalepa G.J., Ligêza A.: A graphical tabular model for rule-based logic programming and verification. Systems Science, vol. 31 no. 2, 2005 [8] Aitech Katowice. Sphinx Vide: System documentation [9] Liebowitz J.: The Handbook of Applied Expert Systems. CRC Press, Boca Raton, 1998 [10] Liebowitz J.: Knowledge Management. Learning from Knowledge Engineering. CRC Press, 2001 [11] Boley H., Tabet S., Wagner G.: Design Rationale of RuleML: A Markup Language for Semantic Web Rules. In SWWS 01, Stanford, 2001 [12] PY,
ASSOCIATE IN ARTS DEGREE-60 UNITS
+ A Course of Study for a Major in Computer Science A.A. Degree & Certificate Programs The field of computer science leads to a variety of careers that all require core computer science skills. These skills
Document management and exchange system supporting education process
Document management and exchange system supporting education process Emil Egredzija, Bozidar Kovacic Information system development department, Information Technology Institute City of Rijeka Korzo
Computer Science A.A. Degree, Certificate of Achievement & Department Certificate Programs
A Course of Study for Computer Science A.A. Degree, Certificate of Achievement & Department Certificate Programs The field of computer science leads to a variety of careers that all require core computer
Communiqué 4. Standardized Global Content Management. Designed for World s Leading Enterprises. Industry Leading Products & Platform
Communiqué 4 Standardized Communiqué 4 - fully implementing the JCR (JSR 170) Content Repository Standard, managing digital business information, applications and processes through the web. Communiqué
Category: Business Process and Integration Solution for Small Business and the Enterprise
Home About us Contact us Careers Online Resources Site Map Products Demo Center Support Customers Resources News Download Article in PDF Version Download Diagrams in PDF Version Microsoft Partner Conference
Sisense. Product Highlights.
Sisense Product Highlights Introduction Sisense is a business intelligence solution that simplifies analytics for complex data by offering an end-to-end platform that lets users easily prepare and analyze
Business Application Development Platform
Business Application Development Platform Author Copyright Last update Version Document type Sclable Business Solutions GmbH Attribution-NonCommercial-NoDerivatives 4.0 International 01/28/2014 1.0 Technical
LABVANTAGE Architecture 2012 LABVANTAGE Solutions, Inc. All Rights Reserved. DOCUMENT PURPOSE AND SCOPE This document provides an overview of the LABVANTAGE hardware and software architecture. It is written
Secure Semantic Web Service Using SAML
Secure Semantic Web Service Using SAML JOO-YOUNG LEE and KI-YOUNG MOON Information Security Department Electronics and Telecommunications Research Institute 161 Gajeong-dong, Yuseong-gu, Daejeon KOREA
tibbr Now, the Information Finds You.
tibbr Now, the Information Finds You. - tibbr Integration 1 tibbr Integration: Get More from Your Existing Enterprise Systems and Improve Business Process tibbr empowers IT to integrate
Short notes on webpage programming languages
Short notes on webpage programming languages What is HTML? HTML is a language for describing web pages. HTML stands for Hyper Text Markup Language HTML is a markup language A markup language is a set of
Web Development News, Tips and Tutorials
Web Development News, Tips and Tutorials In this section I will try to explain what we could and how we maybe helpful for your company and online business. The purpose of this site is to show what we had
MMGD0204 Web Application Technology. Chapter 9 SERVER-SIDE SCRIPTING LANGUAGE
MMGD0204 Web Application Technology Chapter 9 SERVER-SIDE SCRIPTING LANGUAGE Server-Side Scripting Language A web server technology in which a user's request is fulfilled by running a script directly on
Getting Started Guide
Getting Started Guide Operations Center 5.0 March 3, 2014 Legal Notices THIS DOCUMENT AND THE SOFTWARE DESCRIBED IN THIS DOCUMENT ARE FURNISHED UNDER AND ARE SUBJECT TO THE TERMS OF A LICENSE AGREEMENT
COMPUTER SCIENCE (AS) Associate Degree, Certificate of Achievement & Department Certificate Programs
A Course of Study for COMPUTER SCIENCE (AS) Associate Degree, Certificate of Achievement & Department Certificate Programs The field of computer science leads to a variety of careers that all require core
SOA REFERENCE ARCHITECTURE: WEB TIER
SOA REFERENCE ARCHITECTURE: WEB TIER SOA Blueprint A structured blog by Yogish Pai Web Application Tier The primary requirement for this tier is that all the business systems and solutions be accessible
Technical. Overview. ~ a ~ irods version 4.x
Technical Overview ~ a ~ irods version 4.x The integrated Ru e-oriented DATA System irods is open-source, data management software that lets users: access, manage, and share data across any type or number
To use MySQL effectively, you need to learn the syntax of a new language and grow
SESSION 1 Why MySQL? Session Checklist SQL servers in the development process MySQL versus the competition To use MySQL effectively, you need to learn the syntax of a new language and grow comfortable.
II. PREVIOUS RELATED WORK
An extended rule framework for web forms: adding to metadata with custom rules to control appearance Atia M. Albhbah and Mick J. Ridley Abstract This paper proposes the use of rules that involve code to
Integration Platforms Problems and Possibilities *
BULGARIAN ACADEMY OF SCIENCES CYBERNETICS AND INFORMATION TECHNOLOGIES Volume 8, No 2 Sofia 2008 Integration Platforms Problems and Possibilities * Hristina Daskalova, Tatiana Atanassova Institute of Information
DYNAMIC TECHNOLOGIES ON THE WEB: EDUCATION ADMINISTRATION APPLICATIONS. Doug Martin, Ph.D. University of Cincinnati
119 DYNAMIC TECHNOLOGIES ON THE WEB: EDUCATION ADMINISTRATION APPLICATIONS Doug Martin, Ph.D. University of Cincinnati While it is somewhat trite sounding at this point, it is, nonetheless, appropriate
Oct 15, 2004 3. Internet : the vast collection of interconnected networks that all use the TCP/IP protocols
E-Commerce Infrastructure II: the World Wide Web The Internet and the World Wide Web are two separate but related things Oct 15, 2004 1 Outline The Internet and
LAMP [Linux. Apache. MySQL. PHP] Industrial Implementations Module Description
LAMP [Linux. Apache. MySQL. PHP] Industrial Implementations Module Description Mastering LINUX Vikas Debnath Linux Administrator, Red Hat Professional Instructor : Vikas Debnath Contact
Sanjay Dongare. Abstract
Powerful Utilization of Open Source Software in Digital Preservation, Maintenance and Utilization: An Example of the Creation of Union Catalogue of Serials for Astronomy Libraries in India Abstract Sanjay,
Index Data's MasterKey Connect Product Description
Index Data's MasterKey Connect Product Description MasterKey Connect is an innovative technology that makes it easy to automate access to services on the web. It allows nonprogrammers to create 'connectors'
Mobile Devices: Server and Management Lesson 03 Application Servers Part 2
Mobile Devices: Server and Management Lesson 03 Application Servers Part 2 Oxford University Press 2007. All rights reserved. 1 Sun Java System Web Server 6 For large business applications Compatible with
Mercury Users Guide Version 1.3 February 14, 2006
Mercury Users Guide Version 1.3 February 14, 2006 1 Introduction Introducing Mercury Your corporate shipping has just become easier! The satisfaction of your customers depends on the accuracy of your shipments,
Introductory Concepts
Introductory Concepts 5DV119 Introduction to Database Management Umeå University Department of Computing Science Stephen J. Hegner hegner@cs.umu.se Introductory Concepts 20150117
Oracle Identity Analytics Architecture. An Oracle White Paper July 2010
Oracle Identity Analytics Architecture An Oracle White Paper July 2010 Disclaimer The following is intended to outline our general product direction. It is intended for information purposes only, and may
ENTERPRISE EDITION ORACLE DATA SHEET KEY FEATURES AND BENEFITS ORACLE DATA INTEGRATOR
ORACLE DATA INTEGRATOR ENTERPRISE EDITION KEY FEATURES AND BENEFITS ORACLE DATA INTEGRATOR ENTERPRISE EDITION OFFERS LEADING PERFORMANCE, IMPROVED PRODUCTIVITY, FLEXIBILITY AND LOWEST TOTAL COST OF OWNERSHIP
Web Hosting. Comprehensive, scalable solutions for hosting dynamic websites, secure web services, and enterprise applications.
Web Hosting Comprehensive, scalable solutions for hosting dynamic websites, secure web services, and enterprise applications. Features High-performance Apache web server Apache 1.3 and 2.0 1 with HTTP
Design and Analysis of Content Management System Based on Factory Pattern
Proceedings of the 7th International Conference on Innovation & Management 1527 Design and Analysis of Content Management System Based on Factory Pattern Yan Shu School of Computer Science and Technology,
How to make a good Software Requirement Specification(SRS)
Information Management Software Information Management Software How to make a good Software Requirement Specification(SRS) Click to add text TGMC 2011 Phases Registration SRS Submission Project Submission
IT3504: Web Development Techniques (Optional)
INTRODUCTION : Web Development Techniques (Optional) This is one of the three optional courses designed for Semester 3 of the Bachelor of Information Technology Degree program. This course on web development
What is Enterprise Architect? Enterprise Architect is a visual platform for designing and constructing software systems, for business process
1 2 3 What is Enterprise Architect? Enterprise Architect is a visual platform for designing and constructing software systems, for business process modeling, and for more generalized modeling
Virtual Credit Card Processing System
The ITB Journal Volume 3 Issue 2 Article 2 2002 Virtual Credit Card Processing System Geraldine Gray Karen Church Tony Ayres Follow this and additional works at: Part of the E-Commerce
COMPUTER SCIENCE (AS) Associate Degree, Certificate of Achievement & Department Certificate Programs
A Course of Study f COMPUTER SCIENCE (AS) Associate Degree, Certificate of Achievement & Department Certificate Programs The field of computer science leads to a variety of careers that all require ce
CMS and Internet Marketing
CMS and Internet Marketing By Don Parsons DAP@DParsons.com Wish List Setup Website w/ Minimal HTML & Scripting Development Focus on Writing Content Make Adding Content As Easy As Possible Simplify Internet
Last Updated: July 2011. STATISTICA Enterprise Server Security
Last Updated: July 2011 STATISTICA Enterprise Server Security STATISTICA Enterprise Server Security Page 2 of 10 Table of Contents Executive Summary... 3 Introduction to STATISTICA Enterprise Server...
ORACLE APPLICATION EXPRESS 5.0
ORACLE APPLICATION EXPRESS 5.0 Key Features Fully supported nocost feature of the Oracle Database Simple 2-Tier Architecture Develop desktop and mobile applications 100% Browserbased Development and Runtime-1 : Introduction 1 CHAPTER - 1. Introduction
Chapter-1 : Introduction 1 CHAPTER - 1 Introduction This thesis presents design of a new Model of the Meta-Search Engine for getting optimized search results. The focus is on new dimension of internet
Heterogeneous Tools for Heterogeneous Network Management with WBEM
Heterogeneous Tools for Heterogeneous Network Management with WBEM Kenneth Carey & Fergus O Reilly Adaptive Wireless Systems Group Department of Electronic Engineering Cork Institute of Technology, Cork,
In This Presentation: What are DAMS?
In This Presentation: What are DAMS? Terms Why use DAMS? DAMS vs. CMS How do DAMS work? Key functions of DAMS DAMS and records management DAMS and DIRKS Examples of DAMS Questions Resources What are DAMS?
Fogbeam Vision Series - The Modern Intranet
Fogbeam Labs Cut Through The Information Fog Fogbeam Vision Series - The Modern Intranet Where It All Started Intranets began to appear as a venue for collaboration and knowledge
Business Information System Courses Description
Business Information System Courses Description 1903101 Fundamentals of Information Technology: (Prerequisite none) Information Technology components, computer hardware: memory, CPU, machine cycle. numbering
DIABLO VALLEY COLLEGE CATALOG 2014-2015
COMPUTER SCIENCE COMSC The computer science department offers courses in three general areas, each targeted to serve students with specific needs: 1. General education students seeking a computer literacy.
OVERVIEW HIGHLIGHTS. Exsys Corvid Datasheet 1
Easy to build and implement knowledge automation systems bring interactive decision-making expertise to Web sites. Here s proven technology that provides customized, specific recommendations to prospects,,
Jitterbit Technical Overview : Microsoft Dynamics CRM
Jitterbit allows you to easily integrate Microsoft Dynamics CRM with any cloud, mobile or on premise application. Jitterbit s intuitive Studio delivers the easiest way of designing and running modern integrations
Business Application Services Testing
Business Application Services Testing Curriculum Structure Course name Duration(days) Express 2 Testing Concept and methodologies 3 Introduction to Performance Testing 3 Web Testing 2 QTP 5 SQL 5 Load
E-commerce. Web Servers Hardware and Software
E-commerce Web Servers Hardware and Software Basic technical requirements of a Web site that can support E-commerce operations and match business needs. Oct 22, 2004
Towards a Semantic Wiki Wiki Web
Towards a Semantic Wiki Wiki Web Roberto Tazzoli, Paolo Castagna, and Stefano Emilio Campanini Abstract. This article describes PlatypusWiki, an enhanced Wiki Wiki Web using technologies from the Semantic
Actuate Business Intelligence and Reporting Tools (BIRT)
Product Datasheet Actuate Business Intelligence and Reporting Tools (BIRT) Eclipse s BIRT project is a flexible, open source, and 100% pure Java reporting tool for building and publishing reports against
Client/server is a network architecture that divides functions into client and server
Page 1 A. Title Client/Server Technology B. Introduction Client/server is a network architecture that divides functions into client and server subsystems, with standard communication methods to facilitate
ebusiness Web Hosting Alternatives Considerations Self hosting Internet Service Provider (ISP) hosting
ebusiness Web Hosting and E-Business Software Web Hosting Alternatives Self hosting Internet Service Provider (ISP) hosting Commerce Service Provider (CSP) hosting Shared hosting Dedicated hosting Considerations
Oracle Warehouse Builder 10g
Oracle Warehouse Builder 10g Architectural White paper February 2004 Table of contents INTRODUCTION... 3 OVERVIEW... 4 THE DESIGN COMPONENT... 4 THE RUNTIME COMPONENT... 5 THE DESIGN ARCHITECTURE... 6
XML for Manufacturing Systems Integration
Information Technology for Engineering & Manufacturing XML for Manufacturing Systems Integration Tom Rhodes Information Technology Laboratory Overview of presentation Introductory material on XML NIST
CST171 DB Management Approaches Page 1
CST171 DB Management Approaches Page 1 1 2 3 4 5 6 7 Database Management Approaches CST171 Distributed DBMS (DDBMS) (Page 1) Computers at various sites can be connected with communications network or network
VISION BPM. Business Process Management.
VISION BPM Business Process Management 2 Streamline your business processes with is an integrated business processes modeling, optimization and management solution enabling companies to increase their
1 Copyright 2011, Oracle and/or its affiliates. All rights ORACLE PRODUCT LOGO Session ID: 17202 Oracle Fusion Applications - Technology Essentials Overview Nadia Bendjedou Senior Director Product Strategy,
Firewall Builder Architecture Overview
Firewall Builder Architecture Overview Vadim Zaliva Vadim Kurland Abstract This document gives brief, high level overview of existing Firewall Builder architecture. | http://docplayer.net/1487352-From-content-to-knowledge-a-perspective-on-cms.html | CC-MAIN-2017-51 | en | refinedweb |
The Android framework provides a set of two-dimensional drawing APIs that allow you to render your own custom graphics onto a canvas or to modify existing views to customize their look and feel. You typically draw 2-D graphics in one canvas to the appropriate class'
onDraw(Canvas)method. You can also use the drawing methods in
Canvas. This option also puts you in control of any animation.
Drawing to a view is a good choice when you want to draw simple graphics that don't need to change dynamically and. However, there's more than one way to do this:
- In your app's main thread, wherein you create a custom view component in your layout, call
invalidate()and then handle the
onDraw(Canvas)callback.
- In a worker thread that manages a
SurfaceView, use drawing methods of the canvas. You don't need to call
invalidate().
Draw with a canvas
You can meet the requirements of an app that needs specialized drawing and/or
control of the graphics animation by drawing to a canvas, which is
represented by the
Canvas class. A canvas serves as a
pretense, or interface, to the actual surface upon which your graphics are
drawn—you can perform your draw operations to the canvas. Via the
canvas, your app draws to the underlying
Bitmap object,
which is placed into the window.
If you're drawing within the
onDraw(Canvas)
callback, the canvas is already provided and you only need to place your drawing
calls upon it. If you're using a
SurfaceView object, you
can acquire a canvas from
lockCanvas(). Both
of these scenarios are discussed in the following sections.
If you need to create a new
Canvas object, then you
must define the underlying
Bitmap object that is
required to place the drawing into a window. The following code example shows
how to set up a new canvas from a bitmap:
Bitmap b = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888); Canvas c = new Canvas(b);
It's possible to use the bitmap in a different canvas by using one of the
drawBitmap() methods. However, we
recommend that you use a canvas provided by the
onDraw(Canvas) callback or the
lockCanvas() method. For more information, see Drawing on a View and Drawing on a
SurfaceView.
The
Canvas class has its own set of drawing methods,
including
drawBitmap(),
drawRect(),
drawText(), and many more. Other classes that
you might use also have
draw() methods. For example, you probably
have some
Drawable objects that you want to
put on the canvas. The
Drawable class has its own
draw(Canvas) method that takes your canvas
as an argument.
Drawing on a view
If your app doesn't require a significant amount of processing or a high
frame rate (for example a chess game, a snake game, or another slowly animated
app), then you should consider creating a custom view and drawing
with a canvas in the
View.onDraw(Canvas) callback. The most convenient aspect of this is that
the Android framework provides a predefined canvas that can perform your
drawing operations.
To start, create a subclass of
View and implement the
onDraw(Canvas) callback, which the Android framework
calls to draw the view. Then perform the draw operations through the
Canvas object, which is provided by the framework.
The Android framework only calls
onDraw(Canvas) when
necessary. When it's time to redraw your app, you must invalidate the view by
calling
invalidate(). Calling
invalidate() indicates that you'd like your view to be drawn.
Android then calls your view's
onDraw(Canvas) method, though the
call isn't guaranteed to be instantaneous.
Inside your view's
onDraw(Canvas) method, call drawing
methods on the canvas or on other classes' methods that can take your canvas as
an argument. Once your
onDraw() finishes, the Android framework
uses your canvas to draw a bitmap that is handled by the system.
Note: To invalidate a view from a thread other
than the app's main thread, you must call
postInvalidate() instead of
invalidate().
For information about extending the
View class, read
Creating a view class.
Drawing on a SurfaceView
SurfaceView is a special subclass of
View that offers a dedicated drawing surface within the view
hierarchy. The goal is to offer this drawing surface to an app's worker thread.
This way, the app isn't required to wait until the system's view hierarchy is
ready to draw. Instead, a worker thread that has a reference to a
SurfaceView object can draw to its own canvas at its own pace.
To begin, you need to create a new class that extends
SurfaceView. This class should also implement the
SurfaceHolder.Callback interface, which provides events that
happen in the underlying
Surface object, such as when it's
created, changed, or destroyed. These events let you know when you can start
drawing, whether you need to make adjustments based on new surface properties,
and when to stop drawing and potentially terminate some tasks. The class that
extends
SurfaceView is also a good place to define your worker
thread, which calls all the drawing procedures in your canvas.
Instead of handling the
Surface object directly, you
should handle it via a
SurfaceHolder. After your
SurfaceView object is initialized, you can get a
SurfaceHolder object by calling
getHolder(). You should register your
SurfaceView object to receive notifications from the
SurfaceHolder by calling
addCallback().
Then implement each
SurfaceHolder.Callback abstract method
in your
SurfaceView class.
You can draw to the surface canvas from a worker thread that has access to a
SurfaceHolder object. Perform the following steps from
inside the worker thread every time your app needs to redraw the surface:
- Use
lockCanvas()to retrieve the canvas.
- Perform drawing operations on the canvas.
- Unlock the canvas by calling
unlockCanvasAndPost(Canvas)passing the
Canvasobject that you used for your drawing operations.
The surface draws the canvas considering all the drawing operations you performed on it.
Note: Every time you retrieve the canvas from
the
SurfaceHolder, the previous state of the canvas is
retained. In order to properly animate your graphics, you must repaint the
entire surface. For example, you can clear the previous state of the canvas by
filling in a color using the
drawColor() method or setting a background image using the
drawBitmap()
method. Otherwise, your canvas could show traces of previous drawings.
Drawables
The Android framework offers a custom 2-D graphics library for drawing shapes
and images. The
android.graphics.drawable package contains common
classes used for drawing in two dimensions.
This section discusses the basics of using drawable objects to draw graphics
and how to use a couple of subclasses of the
Drawable class. For information on how to use
drawables for frame-by-frame animation, see Drawable
Animation.
A
Drawable is a general abstraction for
something that can be drawn. The Android framework offers a set of direct
and indirect
subclasses of
Drawable that you can use in a variety of scenarios.
You can also extend these classes to define your own custom drawable objects
that behave in unique ways.
There are two ways to define and instantiate a
Drawable besides using the standard class
constructors:
- Using an resource image saved in your project.
- Using an XML resource that defines the drawable properties.
Creating, as shown in the following
example:
Resources res = mContext.getResources(); Drawable myImage = res.getDrawable(R.drawable.my_image);.
Creating:
Resources res = mContext.getResources(); TransitionDrawable transition = (TransitionDrawable) res.getDrawable(R.drawable.expand_collapse);:
public class CustomDrawableView extends View { private ShapeDrawable mDrawable; public CustomDrawableView(Context context) { super(context); int x = 10; int y = 10; int width = 300; int height = 50; mDrawable = new ShapeDrawable(new OvalShape()); // If the color isn't set, the shape uses black as the default. mDraw:
CustomDrawableView mCustomDrawableView; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mCustomDrawableView = new CustomDrawableView(this); setContentView(mCustom_0<<_1<<
Figure 2: Buttons rendered using an XML resource and a NinePatch graphic
Vector drawables
A vector drawable is a vector graphic defined in an XML file as a set of
points, lines, and curves along with its associated color information. The
Android framework provides the
VectorDrawable and
AnimatedVectorDrawable classes, which support
vector graphics as drawable resources.
Apps that target Android versions lower than 5.0 (API level 21) can use the Support Library version 23.2 or higher to get support for vector drawables and animated vector drawables. For more information about using the vector drawable classes, see Vector Drawable. | https://developer.android.com/guide/topics/graphics/2d-graphics.html | CC-MAIN-2017-51 | en | refinedweb |
How would I make lines etc in console mode (I'm using Microsoft VC++)
How would I make lines etc in console mode (I'm using Microsoft VC++)
This should work for horizontal lines. Where \xCD is the hex value for = in the ascii table. You would need to watch for overflow though.
#include <iostream.h>
int main()
{
int line;
for(line = 1; line <= 10; line++)
cout << "\xCD";
return 0;
}
hey thanks!
NP :) I've been working on that very thing myself. I've got a crude method of drawing lines as well, but it needs work in 32 bit compilers like VC 6. It causes the blue screen of death... likely cause is the regs or data type for the pointer, but I'm working on it. It *works* ok in 16 bit compilers though.
#include <iostream.h>
int main()
{
int line;
char *xrow, *ycol;
xrow = 0;
ycol = 0;
for(line = 1; line <=20; line++)
{
_asm
{
xor bh,bh
mov dh,BYTE PTR xrow
mov dl,BYTE PTR ycol
mov ah,2
int 10h
mov dl,'.' // or \xXX hex code for ascii
mov ah,02
int 21h
}
xrow = xrow + 1; // adjust increment of row
ycol = ycol + 1; // adjust increment of col
}
return 0;
} | https://cboard.cprogramming.com/cplusplus-programming/3877-line-printable-thread.html | CC-MAIN-2017-51 | en | refinedweb |
1 /* 2 * Copyright (c) 2001,.net.; 27 28 import java.io.*; 29 import java.net.*; 30 31 /** 32 * Instances of this class are returned to applications for the purpose of 33 * sending user data for a HTTP request (excluding TRACE). This class is used 34 * when the content-length will be specified in the header of the request. 35 * The semantics of ByteArrayOutputStream are extended so that 36 * when close() is called, it is no longer possible to write 37 * additional data to the stream. From this point the content length of 38 * the request is fixed and cannot change. 39 * 40 * @author Michael McMahon 41 */ 42 43 public class PosterOutputStream extends ByteArrayOutputStream { 44 45 private boolean closed; 46 47 /** 48 * Creates a new output stream for POST user data 49 */ 50 public PosterOutputStream () { 51 super (256); 52 } 53 54 /** 55 * Writes the specified byte to this output stream. 56 * 57 * @param b the byte to be written. 58 */ 59 public synchronized void write(int b) { 60 if (closed) { 61 return; 62 } 63 super.write (b); 64 } 65 66 /** 67 * Writes <code>len</code> bytes from the specified byte array 68 * starting at offset <code>off</code> to this output stream. 69 * 70 * @param b the data. 71 * @param off the start offset in the data. 72 * @param len the number of bytes to write. 73 */ 74 public synchronized void write(byte b[], int off, int len) { 75 if (closed) { 76 return; 77 } 78 super.write (b, off, len); 79 } 80 81 /** 82 * Resets the <code>count</code> field of this output 83 * stream to zero, so that all currently accumulated output in the 84 * output stream is discarded. The output stream can be used again, 85 * reusing the already allocated buffer space. If the output stream 86 * has been closed, then this method has no effect. 87 * 88 * @see java.io.ByteArrayInputStream#count 89 */ 90 public synchronized void reset() { 91 if (closed) { 92 return; 93 } 94 super.reset (); 95 } 96 97 /** 98 * After close() has been called, it is no longer possible to write 99 * to this stream. Further calls to write will have no effect. 100 */ 101 public synchronized void close() throws IOException { 102 closed = true; 103 super.close (); 104 } 105 } | http://checkstyle.sourceforge.net/reports/javadoc/openjdk8/xref/openjdk/jdk/src/share/classes/sun/net/www/http/PosterOutputStream.html | CC-MAIN-2017-51 | en | refinedweb |
sff4s: simple future facade for Scala.
what is future?
You've probably come across the notion before but let's go over it quickly. A future value (also known as promise) represents an incomplete calculation.
- a future value represents incomplete calculation.
That's the explanation often given, but not very useful. What's implied here, is that the calculation is going on in the background. It could be on your computer in another thread, it could be on some server, or maybe it's been queued and hasn't started yet. But the idea is that the calculation is taking place somewhere outside of your current flow of control.
- the calculation happens elsewhere.
Another aspect of a future value, is that you are able to eventually get hold of the calculated result. In Scala, this requires an explicit step of calling something like
def apply(). In case the calculation is not complete, it will block. In other words, you will wait till the result comes back (or time out).
- the calculation result can be obtained from a future value.
So initially, when the future value is declared the calculation result may or may not exist yet, and at some point in time hopefully, a result arrives and changes the internal structure of the object, which is called "resolving" the future value. This is a bit creepy because not too many things in programming construct changes its state on its own.
- there's a backdoor to resolve the calculation result.
So far we've described the simplest form of future value. In reality there are other features added to make it more useful, but it's still good enough. Let's see some usage:
val factory = sff4s.impl.ActorsFuture val f = factory future { Thread.sleep(1000) 1 } f() // => This blocks for 1 second and returns 1
Don't worry about the details, but see the behavior of the last line. The act of retrieving the calculation result is sometimes called "forcing." So the minimal API would look like this.
Future v0.1
abstract class Future[+A] { /** blocks indefinitely to force the calculation result */ def apply(): A }
There are several implementations of future values available in Scala, but they are all written from the ground up. If there were a common trait like the above, I can write stack independent code.
is it here yet?
Future v0.1 is too inconvenient because the only thing it can would block till the calculation result comes back. Might as well not use future if we have to wait for it. So another thing that all future value provides is a non-blocking way to check if the result is ready for retrieval. This is called
isDone,
isSet,
isDefined,
isCompleted depending on the implementation, but they all mean the same thing. For now I like
def isDefined: Boolean because then I can think of Future conceptually as an
Option variable.
- non-blocking way to check if the calculation result is ready.
Future v0.2
abstract class Future[+A] { def apply(): A /** checks if the result ready */ def isDefined: Boolean }
timeout
Another common feature is the ability to block for finite duration of time. This could be
def apply(timeoutInMsec: Long). If the calculation does not come back in the designated amount of time
TimeoutException would be thrown.
- block for finite duration of time to force the result.
Future v0.3
abstract class Future[+A] { def apply(): A def apply(timeoutInMsec: Long): A def isDefined: Boolean }
This feels minimal, but it's at least usable at this state.
event callback
So the problem with the timeout approach is that these operations could take a long time to complete and you'd rather not manage a bunch of loops polling for the results to come back. A simpler solution is to pass in a callback closure, so the future can call you when the calculation result is ready. Now we are talking asynchronously. I'm using
def onSuccess(f: A => Unit): Future[A] from twitter's future. Let's look at the usage code:
f onSuccess { value => println(value) // => prints "1" }
Thanks to call-by-name, Scala does not execute the block of code right way.
Also note that it just adds an event handler to the future value, but it does not change the calculated value itself.
error handling
I guess it's obvious we are going to talk about failures since the last event callback was named
onSuccess. Before that recall a point from earlier section: the calculation happens elsewhere. So let's say it's happening in a background thread, and some exception gets thrown. What then? Should it throw the exception in the middle of your current flow of control? Probably not. It's like the proverbial tree falling. What happens is that all exceptions are captured into an internal state, and is replayed when the value is forced by
apply().
The idiomatic way of expressing this notion is
Either in Scala. Since the parameterized type
Future[A] doesn't say what kind of errors it could potentially throw, I picked
Either[Throwable, A].
- any error during the calculation is captured into a state.
This opens up a way for error handling callback
def onFailure(rescueException: Throwable => Unit): Future[A]. In terms of implementation, both
onSuccess and
onFailure is a specific variation of general callback called
def respond(k: Either[Throwable, A] => Unit): Future[A].
- event callback can notify when the result is ready (success or fail).
Since the error state is captured as
Either, the forcing is implemented as
def get: Either[Throwable, A], and
apply() just called it as follows:
def apply(): A = get.fold(throw _, x => x)
Future v0.4:
abstract class Future[+A] { def apply(): A = get.fold(throw _, x => x) def apply(timeoutInMsec: Long): A = get(timeoutInMsec).fold(throw _, x => x) def isDefined: Boolean /** forces calculation result */ def get: Either[Throwable, A] def get(timeoutInMsec: Long): Either[Throwable, A] def value : Option[Either[Throwable, A]] = if (isDefined) Some(get) else None /** invoke callback when the calculation is ready */ def respond(k: Either[Throwable, A] => Unit): Future[A] def onSuccess(f: A => Unit): Future[A] = respond { case Right(value) => f(value) case _ => } def onFailure(rescueException: Throwable => Unit): Future[A] = respond { case Left(e) => rescueException(e) case _ => } }
It's looking better. In fact these features are already beyond the basics provided by
java.util.concurrent.Future, I had to supply my own implementation.
monadic chaining
We can (finally) talk about doing something with actual future. So far we've discussed getting the calculation result out, but that's still present value. A cooler thing would be to actually use the future value before it's available and calculate another future value. Using the value from one thing to compute another thing... it must be a monad. Usage code!
val g = f map { _ + 1 }
We kind of know what
f() is going to resolve to because we typed it in, but pretend you don't for now. So here we have an unknown
Future[Int]. Whatever the value is, add 1 to it. This becomes another unknown future value. If
f for some reason failed, now the whole thing would fail too, just like mapping
Option.
We can also put these into for expression:
val xFuture = factory future {1} val yFuture = factory future {2} for { x <- xFuture y <- yFuture } { println(x + y) // => prints "3" }
Let me just write out the signature of these
def foreach(f: A => Unit) def flatMap[B](f: A => Future[B]): Future[B] def map[B](f: A => B): Future[B] def filter(p: A => Boolean): Future[A]
select and join
I've also added two more interesting methods taken from twitter's Future, called
select(other) and
join(other).
select (also known as
or) takes another
Future as a parameter, and returns the first one to succeed.
Similarly,
join takes another
Future as a parameter, and combines it into one
Future.
Future v0.5:
abstract class Future[+A] { def apply(): A = get.fold(throw _, x => x) def apply(timeoutInMsec: Long): A = get(timeoutInMsec).fold(throw _, x => x) def isDefined: Boolean def get: Either[Throwable, A] def get(timeoutInMsec: Long): Either[Throwable, A] def value : Option[Either[Throwable, A]] = if (isDefined) Some(get) else None def respond(k: Either[Throwable, A] => Unit): Future[A] def onSuccess(f: A => Unit): Future[A] = respond { case Right(value) => f(value) case _ => } def onFailure(rescueException: Throwable => Unit): Future[A] = respond { case Left(e) => rescueException(e) case _ => } def foreach(f: A => Unit) def flatMap[B](f: A => Future[B]): Future[B] def map[B](f: A => B): Future[B] def filter(p: A => Boolean): Future[A] def select[U >: A](other: Future[U]): Future[U] def or[U >: A](other: Future[U]): Future[U] = select(other) def join[B](other: Future[B]): Future[(A, B)] }
Now we have a decent abstraction of a future value.
consumer and producer
Before we get into how to create a future value, I'd like to set things up by discussing the background.
Future values represent incomplete calculations. The calculation is first requested by a consumer, and is later resolved by a producer. In other words, future value is mostly a read-only value from the consumer's perspective, but it needs to be a writable data structure for the producer.
Future we've defined so far is a former one.
This has something to do with difference in different systems' usage. For the most part,
java.util.concurrency.Future,
actors.Future, and
akka.dispatch.Future are there for offloading user-driven calculations to another CPU core or machine. For these systems, resolution step is opaque to the API. It just happens internally.
On the other hand,
com.twitter.util.Future does not provide concurrency mechanism, and you are responsible for playing both consumer and the producer. In other words, you have the control over what goes on in the producer side.
dispatcher
sff4s provides dispatcher objects for the four future implementations mentioned above. They define
future method which dispatches calculation to the underlying system. Recall the first usage code:
val factory = sff4s.impl.ActorsFuture val f = factory future { Thread.sleep(1000) 1 }
This internally calls
scala.acotors.Futures'
future method to dispatch the block.
Note
sff4s.impl.TwitterUtilFuture's
future method would result to unimpressive result if you're expecting asynchronous behavior like that of
ActorsFuture.
implicit conversion
The dispatchers also implement implicit converters to turn a native future value into a wrapped one.
import factory._ val native = scala.actors.Futures future {5} val w: sff4s.Future[Int] = native w() // => This blocks for the futures result (and eventually returns 5)
feedbacks?
I just wrote sff4s in the last several days, so there may be some bug fixes and changes down the line.
Let me know what you think. | http://eed3si9n.com/node/39 | CC-MAIN-2017-51 | en | refinedweb |
H5 and App native interaction, usually the front page of the JavaScript and App using the native development language interaction. The technical proposal shall meet the following requirements:
- When the JS interacts with the native to ensure that the normal forward call logic return, the reverse can deal with asynchronous callback, because for JS, most of the logic is callback and listen.
- To ensure that H5 and Native App communication efficiency, security, and can effectively prevent the H5 page through App injection, intermediate attack or fishing.
- Convenient test phase, H5 embedded into the App among them, developers to facilitate debugging and Debug. The current mainstream technology scheme: 1 before iOS7, to achieve some good agreement with proxy method to intercept protocol Url in UIWebView, get to obtain the parameters from the Url transfer, mapped into local native methods, are as follows: – (BOOL) webView: (UIWebView * webView) shouldStartLoadWithRequest: (NSURLRequest * request navigationType: (UIWebViewNavigationType) NSString *urlString = request.URL.absoluteString navigationType{); if ([urlString rangeOfString:@ js-call://].location! = NSNotFound) {NSString host = [self * sliceHost:urlString] * params = [self; NSDictionary sliceParams:urlString]; if ([host “openOrderDetail” isEqualToString:@ “) {[self openOrderDetail:params]}}; return NO; return YES;} the only solution to the j S call native methods, as the result of the call for some pages and to call after the callback, in this process there is no way to intercept, but there are some crappy compensation measures are as follows: – (void) webViewDidFinishLoad: (UIWebView * webView) {self.orderDetailCallBackFuncName = [webView stringByEvaluatingJavaScriptFromString:@ (orderCallbackfuncName)] “name;} callback method set in the page loaded to get active on the page, and then in the original method processed again callback logic. – (void) OpenOrderDetail: (NSDictionary *) params{//do someting [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@ “(self.orderDetailCallBackFuncName),”% @ “;} 2.iOS7, all use JavaScriptCore the official WebKit JavaScript engine, OC and JavaScript language shuttle. – (void) configJsCallBack{WeakSelf; self.jsContext [self.webView valueForKeyPath:@ = “documentView.webView.mainFrame.javaScriptContext”]; self.jsContext.exceptionHandler = ^ (JSContext * con, JSValue * exception) {NSLog (@ JS Error:%@ “, exception);}; Coordinator coordinator = [[Coordinator * alloc]init]; self.jsContext[@” mobileCoordinator “] = coordinator; self.jsContext[@ = coordinator” console “] don’t know;} JavaScriptCore students can refer to the official document or learning materials. Here we use some skills, all App open to the JS method by a Coordinator scheduler to schedule, and the scheduler implements the JSExport protocol: #import < Foundation/Foundation.h> #import; < JavaScriptCore/JavaScriptCore.h> @protocol CoordinatorExport < JSExport> – (void) log: (NSString *) – BOOL (MSG; (callNativeModule:) NSString * URL); / * JS shareOpinion JSON calls the native shared object {“type”: “share”, “title”: “share title”, “content”: “share content”, “imgUrl”, “”, “clickUrl”: “type”} which types are the following share: (only a circle of friends and friends, doubleShare (WeChat), allShare contains all the shared channel) (share all channels) / JSExportAs (showShareMenu – (BOOL) showShareMenu: (NSStrin G URL opinion: (NSString) * *) opinion @end @interface); Coordinator: NSObject< CoordinatorExport > @property (nonatomic, copy) BOOL (^openShareCallBack) (NSDictionary * opinion); @end approach is that we will inject an object called mobileCoordinator to the JavaScript operating environment under the right conditions, the the object will be injected into the JavaScript window object in the environment, global availability. Why should the package to an object, because JS has no namespace concept and to find the variables increase, will cause naming conflicts, so we put the methods exposed are an object encapsulation. Another advantage is that JavaScript developers and app developers can write code like write their own language code, without grammar loss, JS synchronous call native methods, when native implementation of JS with the return value, the caller can obtain the return value, if it is an asynchronous callback, to provide a callback to the Senate when the foreign exposure method, in an asynchronous callback after completion.
3 other programs, such as JavaScriptBridge, are similar to the second schemes. Scheme comparison: the process of scheme 1 is as follows:
interactive way for the one-way
H5 call Native:H5 page – > Url Redirect (launched carrying parameters with action semantic Url) -> Native App-> Url Redirect-> interception; analytic Action Semantic parameter – > call Native code calls the H5 Native page: Native App – > get on the page; reserved parameters and analytical parameters of -> action semantics; call JavaScript code for such a simple method that calls become very fragmented, and the double end maintenance cost is very high, not easy to debug. The process is as follows:
2
scheme for two-way interactive page: H5 (Native App <); -> call Native code (call JavaScript code) < -> Native App call Native code execution is returned to the calling results (H5 pages called JavaScript code and return the result of the call) scheme 2 obvious advantages, general use second. There are some things need to pay attention to the implementation details:
1.oc method with parameter label, and no JS method, note the use of the JSExportAs macro to convert OC native language for the JS grammar style code.
2 note to obtain jscontext context and injection method and object time, depending on the H5 page of the JS reference time, if the H5 page require to use sequential references, there won’t be a problem, and if the primary interactive JS code is loaded with native injection into the order of chaos, not to call the method the primary exposure may cause abnormal JS execution. The proposed combination of the way to intercept the URL to determine when to inject H5, or front-end engineers to sort out the specification, the H5 reference JS when doing sequence control. Prevent injection and fishing in fact, this is not a technical solution, but you can mention. Sometimes the mobile phone in dangerous network environment for example links in unsafe routers, DNS malicious to phishing sites, if the original page call known exposed method, synchronous data or call the key business, there will be a risk of injection attacks. The general need to do is call app when H5 in the primary key business, need to call native methods in primary afferent notes, through the server authentication center authentication ticket, can through the processing of the page request, in sync with the state, for example the user login app in sync to H5 page in general, app synchronous cookie, but the high cost of maintenance. For synchronization status and data, app should be used to pass the business notes to H5, H5 through the center of the bill to replace the real user status or critical business data. The higher level of the program and H5 and App temporary handshake. H5 in WebView Debug this is a disgusting thing, but we can replace the JS window object console object log function will be transferred to the primary output, and by some other way, JavaScriptCore provides exceptionHandlercontext.exceptionHandler (JSContext ^ *context, JSValue = *exception) {NSLog (JS @ Error: “% @ exception);}; the next article will introduce websocket protocol, app WebView in the output debugging information to the brain for the specified IP, facilitate the development of debugging, so it can reduce the communication debugging and cooperation, improve the development efficiency. | http://w3cgeek.com/h5-and-app-native-interaction-scheme.html | CC-MAIN-2017-51 | en | refinedweb |
Op 26-10-10 23:29, Roland Clobus schreef: >>>> +#if (GTK_MAJOR_VERSION <= 2 && GTK_MINOR_VERSION <= 18 && >>>> GTK_MICRO_VERSION < 2) >>>> GtkWidget *button; >>>> +#endif >>>> >>> That check seems broken, it will consider, say, 2.12.12 as fixed. ... >> Roland, I think it's best if I make any required changes for this Debian >> package, and we include them in the next release (which will not go into >> squeeze) separately. What do you think? > > The patch for gtkbugs.c was included because Debian Testing (at some > time Debian Stable) includes a version that is new enough that this code > doesn't need to be present. The #if part can be removed from the patch, > it should work anyway. Indeed, 2.20 is in testing now. However, users may only upgrade pioneers if they want to, and not libgtk+. According to the package, this is allowed; it requires 2.12.0. So if we don't do a run-time check, I need to manually demand 2.18.2 or larger. I can do this; the question remains if these changes are small enough to be allowed a freeze exception (which is why debian-release is still in the loop; sorry for the noise). > I still think 0.12.3.1 could be included in the new Debian Stable > release. The translations are better, and a bug that renders half the > themes unusable is fixed. Yes, I will push those things in anyway. The question is if I should do this as a Debian-specific patch to 0.12.3, or by packaging 0.12.3.1. I'd like an answer from the release team to that. > A few hours ago I announced a string freeze for 0.12.4, so the next > release of Debian can include that updated version, I hope the new > Debian Stable can include 0.12.3.1. Indeed. The translation and theme fixes should go into squeeze (currently testing); 0.12.4 will go into wheezy (testing after the release of squeeze). Thanks, Bas Wijnen
Attachment:
signature.asc
Description: OpenPGP digital signature | https://lists.debian.org/debian-release/2010/10/msg01459.html | CC-MAIN-2015-11 | en | refinedweb |
12 July 2011 18:39 [Source: ICIS news]
HOUSTON (ICIS)--Renewable Energy Group (REG) has acquired all assets of SoyMor Biodiesel in ?xml:namespace>
REG expects to quickly restart the plant, which has been idled since 2008.
“With nationwide demand for biodiesel growing steadily through implementation of the Renewable Fuels Standard (RFS2) and
REG may also upgrade the plant to process a variety of feedstocks, including lower-cost natural fats and oils such as used cooking oil, inedible corn oil from ethanol production, and high free fatty acid materials, it said.
REG said it acquired the assets from SoyMor in exchange for common stock and the assumption of certain liabilities. It did not disclose the value of the deal.
The acquisition will bring REG’s total | http://www.icis.com/Articles/2011/07/12/9476926/us-renewable-energy-group-acquires-30m-galyear-biodiesel.html | CC-MAIN-2015-11 | en | refinedweb |
We are going to discuss how to create new file in java. First of all we have create class "CreateFile".and after that we create main method than we use try and catch block. We have created File object in java File class representing the files and folder pathnames by location. With File class we create files and directories. Java File represents actual file location in a System. We have created a new file fl.createNewFile() method. This method returns a Boolean value true if file is already created and returns false and display a message if File is already created.
You can see below example
import java.io.File; import java.io.IOException; public class CreateFile { public static void main(String[] t) { File fl = new File("c:/Rose.txt"); try { if (fl.createNewFile()) { System.out.println("file is successfully created"); } else { System.out.println("File is already create"); } } catch (IOException ex) { ex.printStackTrace(); } } }
OutPut:-
file is successfully created
File is already created
If you enjoyed this post then why not add us on Google+? Add us to your Circles
Liked it! Share this Tutorial
Discuss: Create new file in java
Post your Comment | http://www.roseindia.net/java/beginners/create-new-file-in-java.shtml | CC-MAIN-2015-11 | en | refinedweb |
FilePickerSortFlag
Since: BlackBerry 10.0.0
#include <bb/cascades/pickers/FilePickerSortFlag>
To link against this class, add the following line to your .pro file: LIBS += -lbbcascadespickers
Defines the attributes that the files can be sorted on in FilePicker.
By default, the files will be sorted based on type of files being displayed. For example, picture files will be sorted by date and documents will be sorted by name.
Overview
Public Types Index
Public Types
Various Sortflags associated with FilePicker.
BlackBerry 10.0.0
- Default
FilePicker will choose the appropriate sort type based on the type of files being displayed.
- Name
Sort by Name.Since:
BlackBerry 10.0.0
- Date
Sort by modification date.Since:
BlackBerry 10.0.0
- Suffix
Sort by file suffix.Since:
BlackBerry 10.0.0
- Size
Sort by file size.Since:
BlackBerry 10.0.0
Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus | https://developer.blackberry.com/native/reference/cascades/bb__cascades__pickers__filepickersortflag.html | CC-MAIN-2015-11 | en | refinedweb |
On Wed, 2006-02-22 at 15:18 -0500, Jakub Jelinek wrote: > On Wed, Feb 22, 2006 at 11:40:20AM -0800, Nicholas Miell wrote: > > On Wed, 2006-02-22 at 07:09 -0500, Jakub Jelinek wrote: > > >. > > > > > > > Oh great, they're breaking the ABI again!? When will those idiots > > learn... > > > > How about Fedora stops including all new versions of libstdc++ until the > > maintainers manage to wrap their tiny little minds around the concept of > > a "stable ABI"? > > Please don't insult people who know about C++ ABI stuff far more than > you apparently do. Yeah, that was kind of harsh. This is one of my pet peeves. > There are several C++ ABI bugs both on the compiler > side (things you currently get with -fabi-version=0, PR22488 etc.) > and several things in the STL land are simply not doable without > ABI break, backwards compatibility in C++ world is a few orders of magnitude > harder in C++ than in C. G++ 3.4/4.0/4.1 have C++ ABI compatibility > and nobody said yet to my knowledge if 4.2 will or won't be compatible, > libstdc++so7 is simply a playground for things that aren't doable > without ABI break (similarly to -fabi-version=0). If/when it is decided > to do an ABI break, all the stuff in there can be used. > > >From my own experience when I was doing the long double switch also in > libstdc++, aiming for libstdc++.so.6 compatibility with both DFmode > and TFmode long double, maintaining C++ ABI compatibility is a nightmare, > you basically can't use symbol versioning and due to inheritance, inlining > and ODR things are really hard to do. > > We included this in Fedora, because SCIM IM modules are written in C++ > and as they need to be loaded into arbitrary Gtk (and KDE) applications, > there is a big problem if the application uses some older libstdc++.so. > This can be solved only with dlmopen (but then, SCIM IM modules us > like 40 or 50 shared library dependencies, so dlmopen isn't really a > good idea), or by namespace versioning, which is one of the things > libstdc++so7 has. Nice to see that somebody is finally trying to solve the problem, instead of just letting the users suffer. Maybe C++ will actually be a viable language for library development one day soon. (Also re: dlmopen & namespace versioning -- couldn't the same thing be accomplished using linker groups? -- assuming glibc supported them) -- Nicholas Miell <nmiell comcast net> | https://www.redhat.com/archives/fedora-devel-list/2006-February/msg01159.html | CC-MAIN-2015-11 | en | refinedweb |
beanalysis. However, please note that SonarQubebebebebes assemblies are unit test assemblies. To do so, set the
sonar.donet.visualstudio.testProjectPattern property.
Then, you just have to run a SonarQube analysis and you'll get data on unit tests and code coverage. Indeed, the paths to the compiled, you just need to provide SonarQube with the following reports: unit tests execution and code coverage.
Deactivating Unit Tests and Code Coverage
Add the following line to your project configuration file:
My unit tests and integration tests are defined within the same assemblies, how can I run my unit tests only?
Define the
sonar.gallio.filter property:
How can I exclude some specific assemblies and/or namespaces from code coverage computation?
Define the
sonar.gallio.coverage.excludes property:
SonarQube cannot retrieve the compiled unit test assemblies
If for some reasons, compiled unit test assemblies are moved after the build (no longer available in directories defined in "csproj" files), you can tell SonarQube where to find them thanks to the
sonar.dotnet.test.assemblies property.
How to define the Gallio runner type?
Set the
sonar.gallio.runner property. As describe in the Gallio documentation, possible values are IsolatedAppDomain (PartCover default runner type), IsolatedProcess and Local.
Does not apply to NCover.
NCover Classic Edition License
As it is not possible to run tests for multiple test assemblies with the NCover Classic Edition license, set the
sonar.gallio.safe.mode property to
true. Gallio will then be launched once for each test assembly and then merge the generated XML reports. project configuration file:
The first and unique step is to tell SonarQube which assemblies are integration test assemblies. To do so, set the
sonar.donet.visualstudio.itProjectPattern property.
Then, you just have to run a SonarQube analysis and you'll get data on integration tests and code coverage. Indeed, the paths to the compiled, you just need to provide SonarQube with the following reports: integration tests execution report and code coverage report.
Deactivating Integration Tests and Code Coverage
This is the default mode. | http://docs.codehaus.org/pages/viewpage.action?pageId=231082754 | CC-MAIN-2015-11 | en | refinedweb |
In the past developers have had to spend many hours creating trivial data access layers like that in the listing below so that applications can interact more fluently with their chosen data store.
//... public List<Book> GetBooks() { List<Book> bookList = new List<Book>(); using (SqlConnection sqlConn = new SqlConnection(_conn)) using (SqlCommand cmd = new SqlCommand("SelectBooks", sqlConn)) { cmd.CommandType = CommandType.StoredProcedure; sqlConn.Open(); SqlDataReader sqlRdr = cmd.ExecuteReader(); while (sqlRdr.Read()) { bookList.Add(new Book((int)sqlRdr.GetInt32(0), (string)sqlRdr.GetString(1), (int)sqlRdr.GetInt32(2), (string)sqlRdr.GetString(3))); } } return bookList; } // ...Typically these data access layers would use SQL queries and map their results to a collection of custom types. This was fun the first time we did it many years ago, but quite frankly we are now starting to question our own sanity – mention a data access layer (DAL) again, and we might just scream!
In this article we will discuss how LINQ for SQL can help us create more intuitive, flexible DAL’s with a lot less code. Unfortunately we cannot just dive in without first setting the scene.
By the time you have read this article you will be familiar with key concepts introduced in LINQ and LINQ to SQL. With this new-found knowledge, you will be able to construct more powerful DAL’s for your applications to interact with.
Advantages of using LINQ for SQLMany developers have been intimidated by complex Object Relation Mapping (ORM) software due to the complexities of replicating a conceptual model of their database schema. One of the major advantages of using LINQ to SQL is that the complexity is taken away from the developer; new types have been included in ADO.NET vNext (the next version of ADO.NET), which easily allow you to express relationships between entities. Developers will benefit from being able to step through queries while debugging, and get intellisense when constructing queries, resulting in a more comfortable and robust programming environment.
Furthermore, the public May CTP of LINQ includes a number of tools for us to use which automate the process of constructing our conceptual entity view of our database schema.
For more information on mapping to relational databases using objects refer to Patterns of Enterprise Application Architecture by Martin Fowler.
Understanding LINQBefore we apply LINQ queries to entities we must first familiarize ourselves with exactly what LINQ is. In this section we will look at code examples of LINQ in action as well as provide a core understanding of the new features in C# 3.0 which LINQ uses extensively.
Overview of LINQIn the overview diagram (Figure 1) we can see that there are several components to LINQ, the middle tier of technologies which include LINQ, LINQ for XML, and LINQ for SQL can be utilized by both C# and VB.NET and potentially other languages.
Figure 1: The structure of LINQ
Each middle tier component provides us with the required functionality to interact with that component’s data store.
Getting up and running with LINQ is simple – it requires a one-off download of the LINQ May CTP. The CTP includes:
- C# 3.0/VB.NET 9.0 compiler (includes LINQ, LINQ for SQL and LINQ for XML namespaces)
- Language reference update for Visual Studio 2005
- Project Templates for Visual Studio (includes Console Application, Win Forms, WPF, and Class Library)
- Two tools for automating the creation of entities (LINQ for Relational Data (DLINQ) recently renamed to LINQ for SQL), these include the DLINQ objects item (visual designer for Visual Studio 2005) and SqlMetal which is a command line utility.
- Sample applications
First LINQ ApplicationLet us dive in and take a look at LINQ in action by performing a query on an in-memory collection. The goal of this example is to get a core understanding of how a query is constructed and what types of collections you can query.
// ... string[] cities = { "London", "Paris", "Berlin", "Moscow", "Dublin", "Barcelona", "New York", "Endinburgh", "Geneva", "Amsterdam", "Madrid" }; IEnumerable<string> query = from c in cities where c.StartsWith("M") select c; foreach(string city in query) Console.WriteLine(city); // ...In this snippet we use several standard operators to construct a query which filters out all cities which start with the letter ‘M’, however, of more significant importance is the collection which we have queried. We can query any in-memory collection which implements IEnumerable, or IEnumerable<T>. The example previously shown calls the GetEnumerator() on the query when the foreach statement is executed, subsequently a while loop iterates over all items in the collection that satisfy the query until the MoveNext() method of the collection returns false.
If we run this example in debug mode, placing a breakpoint on the same line as the foreach statement, we can see that the compiler is doing some extra work for us under the covers (Figure 2).
Figure 2: Calling a lambda expression
An implementation detail of the query given above is that we are actually creating a lambda expression when the code is compiled, this expression is used as a parameter for Where() extension method of the cities collection.
Lambda expressions introduce a functional style of programming into both the C# and VB.NET languages. Constructing a lambda expression is simple using the new generic Func<A0 , ... , A4, T> type, which like all other examples which use LINQ-specific features so far, is a part of the System.Query namespace. We will now go ahead and replicate the previous query using lambda expressions:
Func<string, bool> filter = c => c.StartsWith("M"); var query = cities.Where(filter); foreach(string city in query) Console.WriteLine(city);Here we define a lambda expression which takes a single string parameter and returns a bool, a lambda expression typically takes the following structure: parameters => expression. Another thing to note is that we call an extension method called Where() on the cities collection which takes a predicate as an argument, extension methods exist for several common query operators including Select, OrderBy, SelectAll, etc. For a full reference see the official LINQ project site.
To learn more about functional programming I would strongly recommend you look at the Haskell language.
LINQ for SQLFormerly named LINQ for Relational Data (DLINQ), LINQ for SQL allows us to interact with a conceptual view of our database. Before we look at LINQ for SQL we must first talk a little about entities, and the tools that exist to automate the generation of our conceptual database model.
Defining EntitiesAn entity by definition is something that is distinct and exists as a separate existence, in LINQ for SQL, entities are defined using custom types and attributing those types’ up with a special new set of attributes included in the LINQ for SQL namespace (System.Data.DLinq). Using attributes we can associate an entity with a table in our database, we can also use attributes to define relationships and entity hierarchies amongst other things.
Figure 3: Simple books database schema (can be downloaded from gbarnett.org)
In the code snippet below we use attributes to associate a type of Author with the Authors table in our database (see Figure 3); we also define a property AuthorID and associate it with the corresponding column in the Authors table. Of particular significance is the use of DBType in the Column attribute – this has been introduced because not all data types in SQL Server map directly to a CLR type, for more information on supported database types see the official LINQ project site.
To associate an entity with a relation in our database, use
[Table(Name="Authors")] public partial class Author { // ... [Column(Storage="_AuthorID", DBType="Int NOT NULL IDENTITY", Id=true, AutoGen=true)] public int AuthorID { // ... } // ... }
Figure 4: DLINQ Objects designer
The demo database schema in Figure 4 describes a few relationships; we can define these exact relationships at our conceptual layer. In the System.Data.DLinq namespace there are two generic types which allow us to express relationships between entities, these are:
- EntityRef<TEntity> – In the Books table we have a 1:1 relationship with a record in the Publishers table; to define this at our conceptual layer we create an attribute of type EntityRef<Publishers>, the implication being that each Book entity has a single reference to a Publisher entity.
- EntitySet<TEntity> – In the sample schema, one book can have many authors (1..*). To define this at our conceptual layer we create an attribute of type EntitySet<Authors>. We imply that for every Book entity there is an associated set of Author entities.
// ... [Association(Name= "FK_Books_Publishers", Storage="_Publisher", ThisKey="PublisherID", IsParent=true)] public Publisher Publisher { // ... } // ...For more information on attributes used to define relationships between entities refer to the official LINQ project site.
ToolsAs we have seen, defining entities is simply a case of mapping an attributed type to a table. Although this process is very straightforward it can be time-consuming, especially when you have many tables in your database schema with many relationships. For this reason the LINQ May CTP includes two tools, one is a designer hosted in Visual Studio 2005 (DLINQ objects) and the other is a command line utility, SqlMetal. We will take a quick look at using the DLINQ objects item to create a conceptual view of our database schema.
First go into Visual Studio and create a new LINQ Console Application, when the solution has been created add a DLINQObjects item to the solution. At the moment you will see a blank canvas, drag the tables of your database from the server explorer window onto the canvas – you have just created the conceptual view of your database schema. The main advantage of using the designer is that you are presented with an entity diagram (Figure_4) describing your conceptual model, however you will find the designer becomes very slow (it’s a CTP remember!) when creating a conceptual view for a large database schema, for that reason I recommend you use the SqlMetal command line utility if that is the case.
Querying EntitiesJust like we can query in memory collections, we can also query entities in our conceptual database model. To interact with our conceptual database model we need to create a DataContext – this is a very important type in the System.Data.DLinq namespace. The DataContext object is in charge of converting rows to objects and vice versa when interacting with our conceptual model, a DataContext object takes a connection string, or any type that implements IDbConnection as an argument (e.g. SqlConnection). Here is the code for getting all book titles in the database:
// ... BooksDataContext db = new BooksDataContext(_conn); IEnumerable<Book> query = from b in db.Books select b; foreach(Book item in query) Console.WriteLine(item.Title); // ...This code can be associated with the SQL statement:
Select * From BooksBecause we only want to select the Title property of the Book entity we can explicitly define this by returning a new anonymous type in our query which comprises of just the Title property of the Book entity.
Because we do not know the type of an anonymous type we can use the new variant type in C# 3.0. The type of a variant is inferred by its value, this allows us to use anonymous types very easily. Below we create a query variable whose type is inferred by the anonymous type passed back as a result of the query.
Anonymous types are types which are created at run time; of what type we do not know, however, the type created has CLR type safe properties. This code will pass back an anonymous type with a single property Title which is of type string:
// ... var query = from b in db.Books select new {b.Title}; foreach(var item in query) Console.WriteLine(item.Title); // ...
Figure 5: More efficient code generated by the DataContext object
Figure 5 shows the more efficient SQL generated by the DataContext object for this code.
Querying related entitiesNext we will look at how we query related entities and look at the SQL generated by the DataContext to enable these queries.
Because we defined the relationships between our entities using EntityRef<TEntity>, and EntitySet<TEntity> we can access related entities by using dot notation just like we would do to access methods, or properties of a normal type. The following query gets the Title of a Book and that book’s associated PublisherName.
// ... var books = from b in db.Books select new {b.Title, b.Publisher.PublisherName}; foreach(var book in books) Console.WriteLine("Title: {0} Publisher: {1}", book.Title, item.PublisherName); // ...We can access the PublisherName property of the Publisher entity from the Book entity as we have defined the Book entity as being the parent in the relationship to the Publisher entity.
Figure 6: SQL generated
Figure 6 shows the SQL generated by the DataContext for the above query.
For our final query we will get all the authors associated with each Book. Because there is a set of Author types associated with a Book we will need to create an inner loop using a foreach statement to iterate through the authors associated with any particular Book. The queries required to achieve this are:
var books = from b in db.Books select new {b.Title, b.Publisher.PublisherName, b.BookID}; foreach(var book in books) { Console.WriteLine("Title: {0} Publisher: {1}", book.Title, book.PublisherName); var authors = from a in db.Authors where a.BookID == book.BookID select new {a.AuthorName}; foreach(var author in authors) Console.WriteLine( author.AuthorName); }
SummaryLINQ provides a simple set of standard operators to query in-memory collections as well as entities. LINQ for SQL allows us to create DAL’s quickly but more importantly they are more flexible and robust than the common approach we would take now as demonstrated in the first code snippet. Hopefully the code examples we have gone through in this article will provoke you into trying LINQ out for yourself!
Granville Barnett’s interest in programming has spanned many languages – currently he is more than happy developing in C# (and the .NET framework in general), and C++. Granville’s blog is at gbarnett.org. | http://www.developerfusion.com/article/84395/next-generation-data-access-with-linq/ | CC-MAIN-2015-11 | en | refinedweb |
17 May 2013 22:56 [Source: ICIS news]
HOUSTON (ICIS)--A majority of energy executives believe the question of whether the ?xml:namespace>
Some 62% of those surveyed by the KPMG Global Energy Institute believe the
Many company executives have begun to feel the effects of the ongoing shale oil and gas revolution to the point that the debate over it is getting “more fine-tuned” toward the long-term ramifications, said Regina Mayor, oil and gas sector leader for KPMG.
“People are still quite bullish on the future,” she said.
“Increased domestic production, particularly from shale assets, is having a profound impact on the global energy sector, introducing new sources to the energy matrix,” said John Kunasek, national sector leader for energy and natural resources for KPMG.
About 73% of those surveyed expect the price of natural gas to remain in the $3-4MMBtu level for the remainder of 2013, while 39% expect Brent crude oil to peak at $116-125/bbl in 2013.
“Greater assurance of supply appears to be stabilising commodity price environments and enabling large investments,” Mayor said. “At the same time, marginal production remains ‘shut in’, which could quickly be reinstated should the price picture become even more robust for gas.”
About 62% of energy executives said that the low-priced natural gas environment in the
Survey respondents cited regulatory and legislative pressures (47%), pricing pressures (26%), volatile commodity and input prices (19%) and energy prices (19%) as the most significant growth barriers facing their companies over the next year. Also, 64% said political and regulatory uncertainty was the biggest threat to their business | http://www.icis.com/Articles/2013/05/17/9670158/majority-of-energy-execs-see-us-energy-independence-by-2030-survey.html | CC-MAIN-2015-11 | en | refinedweb |
This article has been dead for over six months: Start a new discussion instead
0
Hello I am supposed to find a bunch of different statistics from a text file for a homework assignment. I have found everything except the shortest line that is not a blank line. Can someone help me solve this problem?
Thanks
def stats(): linecount = 0 blankline = 0 largeline = '' largelinelen = 0 linelength = 0 nonemptyline = 0 shortline = '' shortlinelen = largelinelen inFileName = input("Please enter the name of the file to copy: ") inFile = open(inFileName) for line in inFile: linecount = linecount + 1 linelength = linelength + len(line) if line.startswith('\n'): blankline = blankline + 1 if len(line) > largelinelen: largelinelen = len(line) largeline = line if len(line) < shortlinelen and len(line) > ('\n'): shortlinelen = len(line) shortline = line print("toal lines:", linecount) print("blank lines:", blankline) print("largest line is:", largeline) print("largest line length is:", len(largeline)) print("total length of lines:", linelength) print("average line length is:", "%1.3f" % (linelength/linecount)) print("average blank lines is:", "%1.3f" % (linecount/blankline)) print('average number of non empty lines are:', "%1.3f" % ((linecount - blankline) / linecount)) print("average non empty") print("shortest line is:", shortline) print("shortest line length is:", len(shortline)) inFile.close() | https://www.daniweb.com/software-development/python/threads/409120/finding-shortest-non-blank-line-in-text-file | CC-MAIN-2015-11 | en | refinedweb |
Let's Kill the Hard Disk Icon 613
Kellym writes "The desktop metaphor is under attack these days. Usability experts and computer scientists like Don Norman, David Gelernter and George Robertson have declared the metaphor "dead." The complexities blamed on the desktop metaphor are not the fault of the metaphor itself, but of its implementation in mainstream systems. The default hard disk icon is part of the desktop metaphor. And the icon is the cause of the complexity created by the desktop"
It really doesn't matter... (Score:5, Insightful)
However, in the end it doesn't really matter. Why? Because there are either people who understand why this is wrong and therefore it doesn't matter to them, or there are people whose understanding of a computer is one that it would require more then changing the hard drive icon to make them undestand.
That, and I'm willing to bet that neither of these sorts of people really care one way or the other.
Well, it's just my opinion I suppose, and you have the right to disagree. But I've always thought the recursiveness of the desktop didn't really matter.
Yah right... (Score:5, Insightful)
Call me old fashioned, but I for one am _not_ baffled by the vast regions of "vague space" that my file systems offer me. I don't want hundreds of stacked desktops for everything I do. This might be nice for Joe Random Luser, but if you intend to do _LOTS_ of things with your computer, and interconnect them, having the power of a file system at your disposal helps a lot.
It is possible to build labyrinths of internal directories that eventually become too deep to navigate via the mouse.
Yeah, that's the way it goes - the same "usability experts" who have brought us the "tree control for everything" metaphor that totally sucks in large directory trees now want to oversimplify even more. Perhaps, if the mouse is incapable of filling your needs, you should consider alternatives... such as the keyboard and a sensible autocompletion. Every time I see someone use a keyboard based navigation tool (Windows Commander comes to my mind, or bash completion), they're about ten times faster than click-move-click-move sequences.
Re:Yah right... (Score:5, Insightful)
Re:Yah right... (Score:3, Interesting)
Keyboard-based navigation tools -- e.g. a command-line interface -- are ten times faster if
Okay, totally valid point. It _is_ of course non-obvious how to use vi for text editing or bash for file manipulation. Still, most people who use computers for work use them for hours a day - and mostly using the same applications. So, being able to use them is IMO much preferrable to being "simple".
That, of course is an implementation problem - if you take a look at GNU software, there's the Readline library [cwru.edu] that controls how you enter text (and a few more things
:)) in almost any application. So you set your preferences once, and they work in your mail client, on the shell prompt and in your web browser, just the same (of course, with configurable exceptions and all the candy you'd expect from a solution for smart people).
Trouble with readline is only that it's GPL licensed, and therefore never found adaptation in any non-free (or non-GPL, for that matter) software...
Re:Readline is LGPL not GPL (Score:2)
Wrong. It's actual, real, hard GPL, and that's the reason it never got big... RMS even cites it in the famous anti-LGPL rant [gnu.org] of his.
man and info (Score:4, Interesting)
>the GNU people (it was the GNU, people
>right?)
Yes.
>that decided that 'man' wasn't good enough and
>they wanted to reinvent it;
It's not that they wanted to reinvent itthat's a probelem; that would have been survivable. It's that info is just plain an abomination. It seems to be an "emacs everywhere" notion. It's a pain to navigate, counter-intuitive, and the type of thing that could only have come out of the emacs or redmond mentalities.
hawk
Re:man and info (Score:3, Informative)
Indeed. I'm a heavy Emacs advocate, and I think that the FSF's info viewer sucks. A lot. Fortunately, there exists a program named pinfo [gliwice.pl] that browses info files in a very nice, lynxlike manner. I recommend it to anyone who needs to look at info files.
--Phil (And, for Debian users, just 'apt-get install pinfo')
Re:Yah right... (Score:2, Interesting)
LOVE your logic!
Re:Yah right... (Score:5, Insightful)
The average computer user wants to do his job, which often has very little to do with the computer. That 10 minutes you refer to is better spent doing something else. You and I may find that ridiculous, but we're in the minority.
These studies are based on how average users (not your average Slashdot reader) use their computer systems. We can rail all we want to about "dumbing down" the interface, but in the end we don't really count. We'll learn the new way far more readily than the average folks will learn our way.
Re:Yah right... (Score:3, Interesting)
Disclaimer, I'm a sports car geek, and I drive a 6-speed.
The one argument that can be said, and this applies to computers, is that people turn their brains off too often. Manual transmission gives you better performance because it gives you direct control over the engine- it's all up to you. Driving is an active activity, but most people in North America (well, every region of NA has its habits,) take driving as 'I'm sitting in this lane until my exit shows up, and I'll ignore everything around me.' North America has the worst trained drivers...
These people also like to install in-dash DVD-Video players, because they find the act of driving... boring or something. They'd rather watch a movie while they drive--turning their brains off.
To relate this to computers, a computer is not like using a TV or a toaster. It's a tool and needs to be used like a tool- with an active brain. I remember back in the day when computers were rare, and I'd do vector artwork on computers, people thought it was cheating. "But the computer does everything for you!" Maybe there were thinking of Print Shop, but that's the reputation computers have. It does stuff for you.
It takes learning to use computers, and most people are very afraid to learn outside of their 'domain' (there domain being their profession). And this is one of the biggest problems I've had with Microsoft guis. "Let's show the user everything, let's make everything one click away. We'll make enough toolbars that can fill up the screen. Is there a task to do? We'll try an do it for them!" That really kills a user's need to explore, and people won't become better computer users that way. Most people don't even know what Style Sheets in Word are, and they're arguably the only good reason to use Word (once you turn off all that automatic formatting crap).
Not that our way (um, Unix) is better in that people should learn it. Raw Unix just wasn't designed for users. This article was about mainstream guis... that points to Microsoft
:) Mac users are known for becoming experts with their computers, whereas Windows users are always asking me to fix their computers... free up hard drive space... "do I need more memory?"
My mother understands Adobe Illustrator much better than she understands Word, and Illustrator is a far more complicated program. She gets pretty clueless about some of the aspects in Word sometimes. She's often able to figure out Illustrator on her own.
Back to the article, the hard disk icon is bad. People don't want to manage files. They don't even want to think about filing. A more ideal solution would be a database like storage system where the user could always find what they wanted easily, and saving was transparent. Then you'd need 'undo' and 'drafts' to make up for that, which is something that people understand easily. This is trading efficiency for usefulness. What else are we going to do with our 1 GHz machines?
But this desktop idea is just stupid. How many people do you know have cluttered real desktops and digital desktops?
Re:Yah right... (Score:2)
Actually, I think the poster of the parent comment was talking about OFMs [softpanorama.org]. These actually don't have a steep learning curve because A) they're usually at least quasi-GUI, and B) they all use the same keystrokes, so once you've learned one OFM, the others are all pretty much the same (F5 for copy, F6 for move, F7 for mkdir, F8 for delete, yada yada) (this contradicts your second point)
That's where hybrid interfaces come to play (Score:4, Interesting)
Have some (well-written) GTK apps installed? (Some apps written by less-clued folks try to implement their own open boxes... ugh!). Open such an application and go to file/open (alt+f o). Now, type part of a filename and press . If possible, the filename will be completed for you; if several options are available, the windowed listing will be reduced to them. If the only option is a directory, you'll instantly see the contents of that directory (and if it has only one subdirectory, you'll be instantly inside that too). There are lots of other goodies it's capable of as well (some globbing capabilities, &c).
The point of this is that it's possible to write an interface which is intuitive for first-time users but also insanely powerful for power users. It also demonstrates how a good set of underlying libraries can provide applications with really nifty functionality without the programmer even having to be aware that it's available.
Yup (Score:5, Insightful)
Exactly. Everything you ever needed to know you did not learn in kindergarten, but for some reason some people don't beleive that. Sometimes, as is the case with general purpose computers, the interface will require some training because there are new concepts.
An apt analogy is language. There are too many words in English. We should simplify it. Perhaps we only need 500 words.
Teach people about disks, don't take the icon away.
Re:No!!! It's too much for me. (Score:3, Insightful)
Except that TV remotes have an increasing number of buttons, allowing one to do many functions well.
TVs that require a difficult-to-navigate menu for every function, instead of having buttons for them, piss people off.
The best TVs, of course, have buttons for many common functions, and menus for uncommon functions. Kind of like, say, a modern desktop, with a hard drive icon handy.
Re:Yah right... (Score:5, Funny)
Same thing here. The hard disk is the physical place where my files reside. Simple enough.
Then, when I click File-Open in Word, the little man inside my computer takes the bus on Data Road to go get my report.doc file. I get it, no problem with that.
But before buying tickets, he checks in its drawer, and if a small part of the file happens to be there, he hands it to me before getting on the bus and bringing me back the whole thing. Efficient and fast, I get that.
But, the files aren't always accessible by bus. Sometimes, the little man has to ask his daughter Ether to get on her bike and go fetch my report.doc from the neighborhood. But she's been warned : she can't take the road until there's no more car in sight. If she ever get slammed on her way back, she must drop everything, get back to the little man's house and try again. I know, it's weird, but that's the way it works.
Thanks to my company's 3 hours intensive training, I know the ins and outs of my computer. I don't need no stinkin' abstraction. Let's deal with the real things.
- There, Ether. Take that to Slashdot.
That's right (Score:3, Troll)
Since *I* don't have any problem with a complex machine, *EVERYBODY* else should find it easy as well. If they don't, they're just Lusers who need to get a life. Basically, they suck. I'm superior to them.
See, when I was in high school, I got teased and beat up a lot, and now that I'm in control of the machines that those lusers have to use everyday, I work *hard* to make them complex and unusable for their work (so I can make fun of how stupid they are and get back at them for those terrible years in high school), while I make it good for me and the things that I do.
This is classic nerd thinking. Alan Cooper wrote a whole book [amazon.com] about how letting computer nerds design computer programs is wrong and stupid. The parent comment lends a lot of weight to his argument.
Re:That's right (Score:4, Interesting)
That is until you realize that, like designing a house, if you don't know what you're doing the whole thing is going to fall apart the instant you look at it funny.
The really interesting thing is that computer programs are quite often designed by People Who Aren't Computer nerds. They're called "customers." Often, these "customers" come by to meddle with the design during its building phase. If this were done during the construction of a house, you would have spaghetti for plumbing, electrical wiring that wouldn't pass inspection, and it would probably float in the air by magic. And this is often exactly what happens to software when you go through a few "design changes" as you make attempts to show the customer what you're spending his hard-earned (or maybe not-so-hard-earned in the case of some companies) cash on during the coding phase of the software. And what they believe to be "minor interface adjustments" typically turn out to be major overhauls that require an almost total rewrite because of how it was originally programmed. The problem is that it needs to be finished in a week, because that was "the last of the changes." If you've ever wondered why programmers don't sleep in that last week of development, that's why.
Don't fool yourself. You wouldn't let a bridge be designed by Joe Average, now would you? Coding's at least as complex.
Re:That's right (Score:5, Interesting)
Don't compare programming to construction. They are so similar, yet implemented so differently it's a shame. There are long lists of rules and codes by which construction has to do things. Are some of these things the "best" way? Probably not, but it is the accepted way and is therefore ubiquitous. Due to this, advances in construction techniques happen slowly, and usually come about through improved tools rather than new rules or codes.
However, in the programming world, nothing is standardized. There are approximately 8 bajillion ways to encode the alphabet. There are a dozen different libraries to display a bitmap image. There are 18 different widget sets in X to accomplish the same thing, and two major toolkits for writing software for Unix.
Advances happen often and create whole new directions to take programming, but these advances happen in the basic rules and codes while the programmer use the same old vi,gcc,gdb from the 19th century.
Computer nerds are poor designers, because they have a skewed outlook of what a computer can and should do. A nerd looks at a computer and sees a box filled with limitations. A nerd sees a computer as a natural extension of his hands and head. A user is 180 out of phase: they see a computer as a magick box with an obtuse and difficult operating mechanism.
Don't fool yourself. You wouldn't let a bridge be designed by Joe Average, now would you? Coding's at least as complex
I wouldn't let a programmer build a bridge either: they'd invent a new method of smelting ore and an entirely new branch of mathematics to build it, it would cost 3 times as much as was estimated, and would be 10 years late in construction. And, after it was built, it would fall into the river and the programmers would blame Microsoft.
I know how complex programming is. I also know that "but it's so haaaard!" is a pretty lame excuse for not doing it right. Programmers, by and large, do not do it right when it comes to design. They are great implementers, but poor designers, because they end up solving the wrong problems.
Perhaps I'm unclear when I say "design"--I don't mean how the inner workings of a computer program passes bits around. That's not design. Designing comes long before fingers touch keyboards. It's where real designers decide what problem the program should solve and how the user will interact with the program. After this has been designed, then the programmers implement this set of specifications. I'm not talking about those designers who put a pretty picture on a CD-player program: I'm talking about real designers that work just as hard as programmers do to design, test, lather, repeat as neccessary to create a good, usable program.
OT: On building houses and software (Score:3, Interesting)
Consider the folliwing:
When we planned the addition on our house, we engaged the services of an architect. He took us through the design, starting with extracting our requirements/needs/wants (my list also had to go through the wife filter, but that's a separate story) and sketched out a couple of proposed designs on the spot. We spent a fair amount of time just suggesting random things/improvements/modifications to his design, and eventually he went away with a big pile of notes.
The architect came back with a proposed design, and took us through it, including explaining relevant building codes and material issues, as well as adding a certain amount of value just from his knowledge. After a couple of iterations of this, we approved the plan, and got quotes from contractors to build it.
At various points during the construction, issues came up and we worked with the contractor to resolve them (usually by writing a bigger check). And we got a nice addition which looked very much like the one we wanted!
So why does it work so well in the real world, and less well in the software world?
Communication. We had a clearly defined specification, produced by the architect and approved by us. At various times during construction, we were told about issues and given choices. We were given the cost of each.
Visibility. We were able to see the work progressing, so (when they brought the wrong window and tried to install it) we were able to say "Hang on, that's not what we agreed to.
Accountability (1). Waving the big stick (check for completion) gave us a lot of leverage with the contractor if he was going in the wrong direction.
Accountability (2). Conversely, we were told that the contractor could do anything we wanted, but it would cost time and money, especially money. Any work done over and above the original contract was documented and signed off on.
So can you do this in software? Yes, but you need a couple of (rare) things:
A Manager/Project Leader (of either gender) with Big Brass Balls who can stand up to various people and say "Here's the impact of doing that".
Agreed-on goals/requirements, with key people accountable for both ensuring that they are met and for communicating them to the key players.
Communication amongst the developers and between the developers and the other stakeholders.
Something of a sense that the end-customer isn't a "luser"
Of course, that's my opinion -- I could be wrong.
Re:That's right (Score:5, Insightful)
You know, nobody who actually develops software thinks like this. The problem is simply that people who develop software tend to be very comfortable with a lot of interface ideas, and therefore tend to pick whichever one works the best for a given piece of their application, without so much realizing that in the overall scheme of things they might be better off simplifying it a bit.
Believe me, we want to make it easy for the user. The easier the software is to use, the happier people will be with it, the better it will sell, the less you'll have to go back and rework interface elements.
Sometimes, if the target audience has a bit more experience or you're working on a technically specialized application, you tend to make things easier for your target users by using interface ideas that would make it harder for someone who just walked in off the street and decided to play with your software. That's generally as it should be... if I'm working on a handy little Unix utility, I generally shouldn't bother to slap a GUI around it and design a nice icon; what my users are going to want is a solid set of (long and short) commandline options, a useful configuration file, and the ability to pass in data on stdin.
At any rate, accusing your post's parent of elitism seems entirely uncalled-for... he's right: The concept of a big empty desktop behind your windows never confused anybody. The big expanding tree structure does suck hard when you apply it to a large directory structure. People who learn the keyboard shortcuts for their apps do generally have far better performance.
And someone else brought up an interesting point, which is that most people spend most of their time in a few applications... only so much time and effort should be spent trying to unify the interfaces of all applications, and it really shouldn't be done at the expense of optimizing for each application.
The flipside is that advanced users tend to recommend applications that have very powerful interfaces, which newer users tend to have trouble with because they're so highly optimized: vim, emacs, Excel, Photoshop, ksh... And they're right, if you learn to use those programs, you will discover that they're very powerful. If you can't be bothered to learn their interfaces, well, you'll just be relegated to using less powerful generically-interfaced software. This is not elitism, it's just a matter of optimization.
Re:Yah right... (Score:3, Interesting)
This is absurd. Perhaps if they are navigating a tree of folders they are intimately familiar with, but I can navigate a tree or set of folders much quicker with a mouse then a CL and autocomplete. Especially if the folder names are unknown to me.
glorified directory (Score:3, Interesting)
We would then have a different desktop for different parts of the system -- e.g. an operating system desktop which would expose internal controls, configuration files, utility programs and other settings, several program desktops, etc.
In pratice it sounds good but I don't think anyone will take to it very well or it will be that different. In fact, most desktops are just glorified directories anyway that are always open and at the lowest level. So what's the point of difference, because I fail to see one.
Where's some real work on this? (Score:5, Interesting)
Where's some real data on desktop usability? Surely if the desktop is considered so wretched, there'd be a score of empirical HCI studies that:
1) Proposed an alternative
2) Actually went out and prototyped the alternative
3) Showed that the alternative was more efficient than the desktop
But I'm not seeing anything coming out that would seem to indicate that the desktop was dead.
Re:Where's some real work on this? (Score:5, Funny)
I nearly murdered the lecturers who tried to teach me on the HCI part of my degree course. While it's true that programmers usually design bad GUIs, the same is true of HCI researchers, except the other way round:
While a programmer will implement a bad gui because he just makes it so it can access the functions he wants, and figures that because he knows how to operate it- that's good enough, the HCI researchers will draw little diagrams, write up "task lists" and waffle on about the importance of various colours and auditary cues, being careful to cite some vaguelly relevant psychology papers and spend far too long being politically correct and work out how e.g. dead people will be able to use the menu on the mobile phone.
Finally they will "play test" their proposed user-interface on a random group of people who will swear blind in exchange for money that they have either a) never used a computer before or b) it was a mac. The play test might even consist of a paper-based simulation- leading to hilarious role-playing games:
luser: So next I think I would click on this here
HCI scum: With the left or the right mouse button?
luser: the middle one
HCI scum: ohhhh. interesting. roll a d20. Oh, the orc takes you by surprise.
luser: WTF?
HCI: exactly
luser: I kick the orc!
HCI: with the left or the right leg?
luser: the middle one.
The "play tests" of the gui (ignoring, as you should the above surreality) never yield interesting data because the researchers pay far too much attention to how individual users expected things to behave, even when they had no computer experience. The point is that computers that allow you to do more than a few simple things will always be semi-complicated by nature unless you dumb them down to the level of mobile phone/pvr menus- and then, as we all know it becomes frustrating to use them when you want to do something quickly, and impossible to do something complex or not envisioned by the manufacturer.
I mean, take for example that whole generation of people who refused to learn/couldn't set their vcrs to record one simple program. True- vcrs didn't need to be that complex- we now have electronic on-screen guides to programmes that make recording a doddle, but at that time the complexity was needed to keep the costs of the machine down and also technology was not as advanced.
However, there will always be some piece of kit that requires that same level of expertise that setting a vcr did, perhaps more, especially given that computers tend to be able to be used in a non-linear manner when compared to the simplistic menus of consumer multimedia devices.
People who can't accept the idiosynchrasies of the computer interface and learn to phase it out (exactly such things as a hard drive icon) will never be any good. Such people tend to learn a set way of doing things on the computer, so if you fuck with their desktop and move the icons about for example they end up madly clicking on an empty piece of desktop and sobbing uncontrolably when they realize nothing is happening.
The point is that if the hard drive icon needs to be changed because it's a confusing representation of how things are, then the users for whom this would be a problem have already lost.
I *DO* agree that we could do with another layer of abstraction though. For example, a user might have some mp3s he downloaded in the My Documents folder where IE defaulted to saving them- other mp3s in My Downloads, where X random download manager put them- and yet more in another directory from when he ripped a cd with some other app. It would of course be nice to be able to easilf list all mp3s on the computer, no matter where they are, as in this case, and indeed many others it is not relevant to the user where the files are- only to the programs and the os. (If you would normally create a "bad rips" directory to put certain mp3s in you now instead tag them with the meta data that they are bad rips...) Now, I know you can just use a file search to find all mp3s on the hard drive, but say you want to find all the mp3s longer than 5 minutes, or ones of just hip hop- some meta-data is needed to help you fine-tune your search criteria.
While it is true that some programs now, like Windows Media Player can "catalog" your files for you it is nowhere near as good as having a meta-filesystem built into the os.
The same meta-tags would be in all the files on the whole internet (tm) too- would make finding stuff a lot easier. I think TBL was going on about having more meta-tags for web pages and some clever system for stopping the obvious abuse of the system by vendors of unscrupulous pr0n.
Sorry for rambling on like some insane karma slut, and for the spelling, which is well below my normally fantastic level, but I am sitting here really tired, waiting for FFX to be released...
graspee
Huh? (Score:4, Insightful)
Maybe I missed the point. I hope so, then the article would make sense.
In my opinion the whole desktop metaphore is flawed. The screen should just be a view of the hard disk, but each user should have their own namespace on the disk and not be able to even see others files, or there system files without running special tools.
The problem with windows is that sometimes "My Computer" is a subdirectory of the disk and sometimes the disk is a sub-item of My Computer. It confuses me and I'm supposed to know what I'm doing!
Re:Huh? (Score:2, Insightful)
No more My Computer, but:
Windows
Program Files
My Documents
Autoexec.bat
Config.sys
etc...
I think is would get very full very fast and kill any +s it would add.
Re:Huh? (Score:3, Interesting)
Consider the number of users who can't find files after they've downloaded them and you'll see how right they are. Consider what "My Documents" tries to do and you'll see that half-assed efforts have been made to address a fundamental usability issue.
If you've ever gotten really used to multiple desktops for organizing your open applications - if you are one of those people like me who has about 25 windows open at any given time - you'd see what a strong point they have beyond the filesystem notion; it makes more sense to put similar tasks and data in groups together, to have a fairly flat set of groups, and to be able to switch between these contexts.
Named desktops (Score:5, Funny)
Re:Named desktops (Score:2)
"Yes, yes...you could even store those named desktops in a tree-like structure. Brilliant."
This is got to be the best response this this article yet. Instead of starting a new thread I must say here that this guy is jumping ahead of the game.
The desktop isn't fixed yet! It's not close to done. It isn't smart enough. I think that eventually we will need/want/have desktops that are smarted and more interactive. But there needs to be work done between the users, the kernel writers [of all OS/platforms], the userland writers all of it.
As computers get 'better' and faster some of us will stray from the bland picture frame desktop. Maybe this guy's idea would work better as his 'desktops' as tiles on The Desktop?
I've already responded saying that this is a silly idea all together.But now I see it as a way to change the way I see my system and I don't like it.
I want to know where my files are, I may want to just look through them. Sorry if that bothers you.
/complexity/ ?? (Score:5, Funny)
Re:/complexity/ ?? (Score:5, Insightful)
...and despite all this time, effort and money, most people still find computers complex to use.
My SO can pick up a remote control, figure it our without the manual, and operate the TV, VCR, and Hi-Fi. So can my parents. They are happy to set the message on their answering machine, program numbers into their phones, do combo-cooking with the microwave and generally use your average household technology without instruction
... but not a computer.
First you have to know about the idea of clicking with the mouse. The whole left-click / right-click thing which we take for granted and do 20000 times a day is NOT easy to catch onto for a new user. Once they have the idea, they still do know what to do.
"Start button? But its already started, why do I want to start it again?". How about the little icons on the taskbar? Any idea what they mean if you haven't been told? There's a deskpad with a notebook and pencil on it [looks like a writing application, but its the desktop]. Then a big blue "e" [here is South Africa we have a TV channel called "e" with a very similar logo]. Then a clock inside a square [that would be outlook].
When there IS a window open, there's three funny looking icons at the top right. Ask a new user if they can guess what they mean.
With the exception of international standard symbols (like the power symbol), most people can't guess the meaning of icons. Your average Word user goes on a 3 day course to learn the basics of clicking on the correct toolbar icon, when they could select a perfectly meaningful English word from the menu system.
The whole idea that GUIs are easy to use is a myth, as is the idea that icons are somehow more meaningful to users. These ideas have been forced down our throats by marketing droids and the odd technical writer who things (s)he knows his/her stuff.
Re:/complexity/ ?? (Score:5, Informative)
20 years later, where the "interface" for VCRs really hasn't changed, my parents to just fine, and can pretty much use any VCR.
The problem with computer GUI's is they haven't settled for 20 years - and people like these guys who come along and keep wanting to "create a new paradigm" (mark that off on your buzz-word bingo) are screwing things up - if it doesn't stay consistent for any length of time, no one will get accustomed to it.
I agree about the pictures on the buttons, though. We had an application from some developers that had a horrible interface. When we were asked for suggestions, I suggested they improve the interface, and suggested they looked at that particular OS's interface guide. Not only did they not look at the guide, but we ended up with a real pretty GUI where the pictures had virtually nothing to do with the functions - unless you were the programmer. We might have lived with it if they had tool-tips, but if you need to rely on tool-tips, maybe the icon isn't so good - why don't you just label the button with the tool tip?
Re:/complexity/ ?? (Score:3, Insightful)
Perfect.
You hit the nail right on the head. Why are computers so damned hard for a new user to use? Because a Windows PC works differently then a Macintosh PC which works differently than a Linux PC which works differently than... (ad naseum)
The GUIs of all those systems try to mimic the tools on an actual desk but each with enough subtle differences as to make the novice unable to move from one to another. And each new version changes everything COMPLETELY (although Apple had the same GUI from 1984 until 2000 with no "major" changes).
Calculators all look totally different. But anyone can look at one and know that it is a calculator. And when you know how to use one, you can use almost any other calculator. When it comes to icons on the GUI desktop, that isn't so easy. The icon for Microsoft Word is a green W. What is this W? Does this wash my comptuer for me? The Excel icon is an X. What is this X? Is this a computer xylophone?
GUIs and software publishers are very self-promoting. They use their own meaningless logos and marketing-drone generated names to identify their programs. And then they go nuts if you try an copy their "look and feel". That's all fine and dandy if you know how to use a computer and/or what you want to do with the computer. But for someone who never used a computer or that particular computer , they haven't got a clue.
All those fancy GUIs are supposed to make using computers easier. But they don't.
Here's how to design a computer that will truly be easy to use: Take someone who never has used a computer before. Sit them down in front of the computer. Don't tell them how to use the computer. Give them some tasks to do with the computer (ie, write a letter). If they can complete those tasks without needing help, you've designed an easy to use computer.
Ever teach somebody how to drive a stickshift? (Score:5, Insightful)
So people have to learn how to use computers in the same way they have to learn how to drive a car.
Have you ever thought about how intuitive an automobile is?
So you see, we can't demand an "intuitive" interface for everything. There are some things in life that people should just be expected to learn how to do, like operate cars and computers (regardless of the computer's OS). That also requires learning traffic laws, and similar "laws of the net."
If we had a Fisher-Price any-idiot-can-drive interface in cars, imagine how dangerous the roads would be! Even more so than they already are, considering that most idiots already know how to drive today, despite the "complex" interface in automobiles (even with automatic transmissions!) Yet they can't copy files around on their own computer.
Re:Ever teach somebody how to drive a stickshift? (Score:3, Interesting)
Very good point and it explains why a computer UI will always be more complex than a car or VCR. BUT, the fact the computers perform a "nearly infinite" number of tasks makes it all the more important that the UI *attempts* as much as possible to be intuitive. A car can use a "counterintuitive" interface precisely because it's function and thus it's interface elements are so limited. There are only three pedals, a wheel and a stick - or even two pedals and a wheel. The UI of a car is NOT complex! On the other hand it IS consistant. No matter which make or model I buy a car from the pedals and the steering wheel all do the same thing and are in the same spot. It's not like Ford puts the clutch on one side and Chrysler puts it on the other - or a Taurus uses a steering wheel, Saturn uses a joystick and Yugo's use a rudder to steer the thing.
By contrast a computer, as you pointed out, can perform a nearly infinite number of tasks and so requires a just as nearly infinite number of UI elements. If those elements are arbitrary, inconsistant and counterintiutive it will take a nearly infinite amount of knowledge to master them to use the computer. If those UI elements are thoughtfully designed to be as intuitive and consistent as possible the user can get the computer to perform those nearly infinite tasks without himself having to expend nearly infinite time and mental energy learning the interface.
There are some things in life that people should just be expected to learn how to do, like operate cars and computers (regardless of the computer's OS).
True, one thing that programmers should be expected to learn (or should hire those that have learned) is good UI design. The people expected to learn the use of computers should themselves expect thought to be put into the UI of those things by the people who design them. Unlike cars too many computer programs and operating system UI's are poorly thought out, needlessly complex, inconsistent, and needlessly constantly changing.
Re:/complexity/ ?? (Score:3, Interesting)
Just a casual FYI: My Hi-Fi has 4 buttons to control the CD tray and selection, another 4 to control the input source (casette, cd, tuner, aux), another 6 for various graphic equaliser options, 12 buttons to control the tapes, and one volume knob.
And just to complicate the issue, you won't get any sound out of the TV alone because its rigged to play through the aux ; similarly the TV isn't tuned to any channels, but accepts input on aux from the VCR.
The VCR, in addition to its 8 buttons, is programmable from an OSD.
This is not a typical household setup, not does it perform "a single function". What is important is that there are a limited set of functions most "users" use, and those are highlighted on the remote(s) in luminous blue (gotta love Tiwanese stuff
;p ).
The single most important part of designing an interface (for a computer) is to hide complexity without "hiding" it. Reduce the number of options at easy choice point to 7 +- 2. Don't do stupid MS stuff like hiding infrequently used options - users get confused ; it also means the user has a heck of a job investigating the full capabilities of the application.
An extension to this: your menu bar should have 5 to 9 menus, each with 5 to 9 items (possibly sub-menus), and each sub menu should have 5 to 9 items with NO submenus. A submenu should never invoke a dialog or be a "checkbox menu". In this manner you reduce the overall complexity to something a user can reasonably nagivate.
You must understand the technology to use it (Score:4, Insightful)
My motorbike has an oil light on it.
It comes on when the bike is running out of oil so I know when to put more in. To run a motorbike I mush know how to do this and (basicly) how the engine works. (Unless I want to be totaly reliant on a mechanic)
A computer is exactly the same.
To use it, you must know basicly how it works.....such as what a hard disk is! You cant oversimplify!
Re:You must understand the technology to use it (Score:3, Interesting)
Since the first option is by far the most userfriendly, I think in the future (when we have really nice uplinks at home), companies will start to over fully functional thin clients which they admin themselves. This would take away a lot of the problems the average home-user has and at the same time will enable us to rent applications which we'd otherwise consider too expensive to buy (and now use illegaly) and offer lots and lots more...
Why not.... (Score:5, Funny)
huh??? why? (Score:2, Insightful)
As to the limitations of the desktop - isn't the desktop contents just a directory on the drive anyway?
The mouse can't leae the desktop? sure it can - if you have virtual desktops - I just hover my mouse at one of the screen edges and it flips to the next panel. I use virtual desktops to access the multitude of application windows I have open, not to organize my filing system and have it cluttered with a zillion icons - I'd never be able to find anything!
As another poster here said, power users who understand the file system on their machines don't have a problem with it.
.
I'd love greater abstraction (Score:4, Insightful)
At the moment my other half knows what a floppy disk is (it looks like a floppy disk, and you can put files on it). She knows that the "hard disk" is a "big floppy disk inside the computer", and that she should copy from the later to the former whenever she needs to keep a safe copy. This is a good thing, because she knows where her stuff is, and so do I (as sys admin). As soon as you start blurring the lines, it makes it harder for people to control their own files.
I think it's right to be pushing the state of the art in the interface. However, I have this conservative feeling that the current status quo matches well to the actual reality of buggy software and hw/sw failures. Once we cross over into "you dont need to know that" space, we better be sure that we actually don't need to know it, otherwise we'll be SOL.
Doesn't seem very deeply analysed to me. (Score:2)
So, since people don't fill their desktops with quite as much crap simply because it has an visual limit. I can get about 100 icons on mine.
So, since 100 files isn't enough for my data needs, they suggest I have multiple desktops.
I get a feeling that this will over-complex things.
Also, the standard "file manager" type view is a staple of e-mail systems. How do the authors suggest replacing this?
Hmmm. I dunno. Won't it add extra complexity as you have to distinguish between persistant icons that are on every desktop, and the transient ones that are just on one. Since everything the user sees is a shortcut, you also have to distinguish between deleting the shortcut and deleting the file. (delete once the last link is gone? maybe)
Anyhow, easy enough to test their theory, since you can configure both Linux and XP to work exactly like thay describe.
Mac was the first? (Score:5, Insightful)
Now KDE, Windows 9x, and many other use the 'Desktop' as the 'root' of the system. You'll notice that this trick is only performed by the 'userland' and not the actual system. This is because it's common sense. Your computer doesn't want to look for things starting from a folder/directory/area that is actually buried deep within the system!
I say, banish the 'Desktop'! It confuses users. Teach the file tree! Standardize the file tree!
No more systems where programs store themselves anywhere! No more systems that show the drive under the Desktop! No more systems that show other things on the same level as the drive!
Why confuse users? Teach them;
"This is
"This is
"This is
"But this is your Home/My Documents/Desktop. There are others similar to yours, but this one is yours."
"However, it doesn't sit on top of the rest of the system!"
Maybe I don't get it. I thought it would be easier to teach new users things they already understand.
"This is the desktop, it's the top level, well kinda, it's actually in
Confused user (Score:2, Insightful)
Root of the system? What do you mean?
/etc where your configuration data is stored!"
"This is
Why is it called etc?
/usr - you'll find the actual programs and more there!"
"This is
Why is it called usr? Are there more programs in proc?
"But this is your Home/My Documents/Desktop. There are others similar to yours, but this one is yours."
Why do I have a desktop inside my documents? Sholdn't the documents be on the desktop? And so many of them? This is so complicated.
"However, it doesn't sit on top of the rest of the system!"
What top? What was the root again?
Re:Confused user (Score:2, Interesting)
Maybe you didn't have a hard time learning because the term was already in common use. I bet it wasn't always that way. Now fast forward 10 years... I wonder if "desktop" and "hard-drive" will be in common use. I know people 60 years old who now know these terms, and they have nothing to do with the field... Just like you don't really have anything to do with the automotive industry.
Sorry for the extremely overworked computer as car metaphor, but here it actually fits. You can actually substitute *any* new technology with its corresponding terminology.
-Greg ---
Re:Confused user (Score:2)
Not everyone needs to understand how or why their tools work. Should I hold you responsible for understanding quantum field theory since that's really why computers work?
Re:Mac was the first? (Score:2)
I think what many people (including the author of the original article) fail to realise is that the hard drive icon is NOT part of the desktop, or even related to the desktop. It is the computer visualisation for getting up, walking away from your desktop and opening your file cabinet.
The two are very different, and both required. You cannot organise yourself effeciently with even a thousand desks - you need a filing cabinet. Conversely you can't work from a filing cabinet at all times - you need to take out a file, strew some pages around your desktop, and get on with stuff.
Re:Mac was the first? (Score:2)
Thus Unix treats
Windows 2000 stores all user-specific settings and documents in C:\Documents and Settings\<user> but introduces a further hierarchy of Application Data, Desktop, My Documents, etc. Since a Windows user spends most of their time interacting with a desktop-metaphor GUI, the Windows user experience revolves around Desktop. Programs are accessed via shortcuts on the desktop, documents are stored in the My Documents folder that is accessible via a desktop shortcut, and settings are handled by applications (and stored in Application Data, but most users aren't concerned with this as long as their settings are preserved). Intrepid users can see the organization of the computer into disks and directories via the My Computer icon, but are under no obligation to do so, and again, sysadmins can protect the system from user error.
I'm not going to say that one of these philosophies is better than the other, but surely either is preferable to confused users running amok in
Re:Mac was the first? (Score:3, Interesting)
I for one wouldn't object to having
/configuration that was a symlink to /etc and even having /etc non-visible by default in graphical browsers.
Intriguing idea - but flawed (Score:3, Interesting)
This idea sounds cool, but the argument is weak.
The whole point of the tree-like structure of the harddisk is managed-complexity. Hierarchial structures allow the user to ascend the descend the hierachy, performing operations that are similar in execution, but differing in context.
What happens when you have 1 million odd bits of stuff to manage? How would such a user switch between desktops, looking for the right window to do his stuff on?
You need some kind of tree, not a linear sequence of desktops! Say maybe one for administrative configuration. Let's call that etc. And one for executables, let's call that bin. And then how about some tmporary space to play around in. On wait
good for some, bad for most (Score:5, Insightful)
I reccomend to new users to save files they dont want to lose on their desktop just because its so much easier to remember where it is. eventually it WILL get cluttered, but its a good temp solution until they're more at ease with the hard drive, and finding their way through it. I can just imagine how lost some people would feel without their desktop and most used files staring back at them when they turn on their computers.
I can accept that there are some people who feel the desktop and hard drive icon metaphor are out dated, but i fail to see how their preference should override other peoples prefs.. instead of "killing" something you don't aggree with, how about encouraging an implamentation to have it or not, depending on your settings?
i dunno, to me its like saying "oh i can ride a bike now, so training wheels should be abolished, they only get in the way now".
its short sighted and biased, and only makes things harder for those who are just starting out.
Computer Home (Score:2)
Think of it : directories could be bookshelves, and generic files books. Music files could be records. You could browse the web looking out of the window. And so on.
You could have different rooms, equivalent of today workspaces: one could organize one room for play, one for office, etc
... You can decorate floor, ceiling and walls as you like, and put in them bookshelves (symlink to directories) or appliances (applications or applets with a look that recalls their function).To make system administration, you go to the basement :-). [Currently missing a clean metaphor for removable media, though].
Application installers could even create their own rooms, in the same way they create folders now.
This environment should be 3d : not the full 3d stuff, since you don't need to loose time walking from one place to another. But enough 3d to look real. And to benefit of spacial arrangement as a way to priopritize symbols : the more important icons are close and big; others are more distant and smaller. A single mouse click could move you in another position, changing the perspective.
When running a today 2d app, you get a full screen 2d view (90% of non technical users I have seen rarely uses more than a window per time). Iconising the window, or clicking on a navig bar button, you are back in your 3d homey environment.
Re:Computer Home (Score:2, Informative)
Re:Computer Home (Score:2)
OK - so one *can* find a metaphor for each of those, but as you add more and more functions to your metaphor, it becomes harder and harder to remember where the less obvious items are.
The answer is either that the user is offered a very basic computing environment with little control over where thinsg are and what can be integrated with it, or the metaphor breaks and becomes clumsy to use.
a desktop is a flat directory (Score:4, Insightful)
Once you see it that way you realize immediately that this is very limited. Directory depth is there for a reason. Searching is easier, both for the computer and for human mind, once a certain number of elements is exceeded ( for the human mind that number is about five to eight)
If all the information the user needs can be stored in six to eight directories in a logical way, eliminating death may help useability. For users with more complex needs, this is a very bad idea.
Do people really use desktops for files? (Score:3, Insightful)
This article is calling for the redesigning of basic filesystem operations because of an overly misused feature that a few GUI systems have. The "everything is a desktop" idea woudl be impossible to implement on anything that relys on non GUI systems. It would also mean that practically every application on earth would have to be redesigned to accomidate this filesystem method.
Rather than change everything to accomidate better understanding of this overly used feature, why not get rid of it? Teach people about the way computers really work with files, rather than keeping them in the dark about whats going on.
Give a NeXT style GUI system a chance, try WindowMaker or Blackbox, or if you are on Windows install Litestep. Give it some time and you will realize how poinless having files on the desktop really is.
This Article Misses the Point (Score:4, Interesting)
In it's place he would do away with the hierarchical directories and replace it with multiple "desktops" (e.g. flat, non-heirarchical, visually-managed workspaces).
The glaring problem with this is that most professional computer users (ie. discounting grandma who sends email three times a month and opened Word once) have so many files/applications on their computers that they would need dozens (or hundreds!) of these desktop workspaces to manage all of the files & applications.
True, some Linux desktop environments have multiple desktops, but check and see how many users have more than six or eight desktops configured. Very few. There's a usablility threshold where if setting up more "categories" (in this case more desktops) actually decreases usability, whereas setting up "sub-categories" within the top-level categories will increase usability. Hence: heirarchy.
The entire field of taxonomy is dedicated to this principle.
As a previous poster said: This article is daft. (And poorly written.)
Flawed premise - all people do not think alike (Score:2, Insightful)
No matter how much we condense ourselves down into bell curves and types, we will always be infinitely diverse, and how we interact with each other and our tools will always be a very personal thing.
That being said, I'd like to do some research into teaching people enough science and art to begin with so that whatever interface they come across will quickly become easy for them. This is already the case with most geeks, and I don't accept the idea that we are somehow gifted, or that the so-called average joe must be provided with a toy interface if they ever hope to get anything out of computers.
I wager that as long as we assume users are stupid, they will continue to be.
not again. (Score:2)
Now, the idea of multiple desktops isn't a bad idea, but it would be nice to find a program that isn't a bloated piece of crap that does it (hydravision from ati comes to mind, but since bundled software always sucks . .
What the authors say is true, you tend to have a bunch of crap on your desktop that you will eventually sort through and put into directories / delete. Pretty much the stuff on there is unusable. Yes, you can have apps and stuff on your desktop, but for the most part, most people organize that into the gnome/kde/apple/start menu (or quicklaunch).
I don't know how many of you have fooled around with litestep (I think it's dead now, I'm not sure) - the skins, by and large are a pain in the ass to use (albeit cool as hell to look at). I suppose things would be different if you made your own "gui overlay", it would make sense. It seems that pretty much any alternative is essentially hierarchically based - i.e. press a button and get a series of options. (click on the foot, apple/? get a list of options) - essentially the "multiple desktop system" is a start menu, albeit with more eye candy.
Anyways . . .
Re:not again. (Score:2)
If customization were a little simpler, one could almost say it was ready for lusers. Heck my mom can install litestep, using a standard skin anyway, and she's a
Speaking of litestep, I think what the article really wants is a good wharf, they just don't know enough to have heard of one. Multiple desktops my ass. Might as well just put everything in C:\ or / and screw the namespace.
The only other metaphor/interface I could see possibly improving usability is a literal tree system with spacial, visual, and relational cues to allow easy vgrepping for the mentally-so-so.
Instead of the of having each level of directories equivalent, allow relative visual positioning. Instead of just simple icons, allow changes in a appearance based on multiple criteria(size, type, relation, etc) and further affect them based on searches(make all files that are 13mbytes or wider, work-colored, and document-anvils bend the branch they are on, or just blink).
But that what just be eyecandy for most people, sense they wouldn't bother to do the necessary filemanagement anymore than people do with their current system, or the proposed "infinite desktops". A sampling of users will probably show a desktop that is already cluttered because they don't bother to use the existing system(shriek, learning curve!) or come up with their own internally-logical system(effort!)
Then there's the monitor size issue ! (Score:4, Funny)
Next time some random user needs "more room to store my stuff in the computer" he/she goes out and gets him/herself a larger monitor rather than a larger hard disk !!!
New Xerox Palo Alto for 3D usage metaphors? (Score:5, Interesting)
Why we still 20-30 yrs later have no good new metaphors is because there is no fundamental development dedicated to that effort.
The machines today come, thanks to ID and other game companies, equipped with graphics chips more than able to create an immersive 3D environment. This capability is totally unused in daily usage.
Trash the disk metaphor like it has been trashed in UNIX file hierarchy: you can still know everything about your disks, but they have become irrelevant in the directory structure.
A good 3D environment should trash the desktops as well and use spaces instead. Yes you can have your 2D windows for text terminals and whatever current applications, but you can as well do your 3D CAD/CGI design/rendering in space provided by a 3D GUI. Imagine being able to "turn around" with mouse or similar (headmounted?) device in order to look around; to be able to "zoom" into and past separate windows and work areas (workspaces) with mouse wheel or cursor keys.
Imagine being able to link to each other related files/items in a 3D-space instead of 2D. What would that do to your DB schemes. Or to zoom into a software package's source icon to see its design, zoom into a class to see its components, and zoom into a method to see its source.
Etc.
This would require trial-and-error, examining, playing around. Where is the team that is being paid for this development?
Any hints would be greatly appreciated. I could even be interested in such work myself.
Re:New Xerox Palo Alto for 3D usage metaphors? (Score:2, Insightful)
Imagine getting nauseated and throwing up from trying to find some file you stored "somewhere near - I'm sure that document is somewhere near here!"
3D doesn't work for everyone - virtual reality, real nausea.
Michael
Re:New Xerox Palo Alto for 3D usage metaphors? (Score:2)
ostiguy
Re:New Xerox Palo Alto for 3D usage metaphors? (Score:3, Insightful)
Check Google. I'm sure you can find quite a few teams that are working on this.
So far, none of these teams' efforts have been successfull. I'd wager that is because the actual viewing area is 2D. Maybe if we start to use VR-glasses, 3D workspaces would be convenient, but since that isn't the case a 2D desktop is far less clunky than a (badly) projected 3D one.
my 2cts, anyway..
Again with the 3D interface! (Score:3, Insightful)
What would be the advantage? Extra space? We have multiple desktops and three or four methods of window minimization and hiding. Easier navigation? Since when can't you map a tree into 2D perfectly adequately, and simply? We have a few ways of doing that, too. More intuitive interface? Sorry, but there's nothing intuitive about having to look around in multiple dimensions (mapped, incidentally, to two dimensions on your monitor) to find a window or icon or whatever you've misplaced.
As long as our data is primarily text-based and our displays are physically two-dimensional, 3D interfaces are going to both be pointless and suck. And you'd be hard put to convince me that a physical 3D interface would be practical for most applications.
Sorry, but the gee-whiz-neato-"imagine all the pretty polyhedrons" just doesn't translate into "good idea".
Declare the _metaphor_ dead (Score:2, Interesting)
As an analogy that someone else suggested once (iirc on
Hard drives should be more like RAM modules. (Score:3, Insightful)
The user should not need to understand the notion of a filesystem. "Advanced" users should only need to know that they can plug in a hard drive and know that the OS will automatically format and integrate it into the system. Need more disk space to store MP3s? Simply add a disk, reboot, and have your space automatically split across the second drive.
Users should only have the concept of a Home folder (let's not call it a directory). The user can place all of her data in this folder. Advanced users can create subfolders if they so choose, but the UI should be able to automatically group files in a single folder by type if the user doesn't create one.
Users should not be concerned with OS files, the actual files used to store
.EXE and Application files, etc.
Mac OS X is the closest to this. Your home directory contains all your data and application preference files. I recently lost a hard drive, but had a nightly backup of my home directory. I simply reinstalled OS X and the applications I use, and *voila* everything is back to normal -- no importing bookmarks, restoring my e-mail client configuration, etc. Users of KDE/GNOME are enjoying similar benefits.
Windows has a ways to go, but for starters it can get rid of the idiotic "drive letter" concept. At least with UNIX you can mount a separate disk drive into the global filesystem. Windows 2000 provides this equivalent feature finally, but only if you use NTFS. I doubt Windows XP Home encourages end users to use one "C:" drive and mount other disks as a folder, but it should.
Naturally, power users, system administrators, programmers, etc., still would benefit from the concept of a filesystem. But the millions of end-users needn't be bothered with it.
Oh please $deity, no... (Score:5, Insightful)
At this time of writing I have a grand total of 4(four) icons on my desktop. Only one of these is a shortcut. I have 12 more shortcuts on my taskbar (so, I use Windows. Sue me.
;o) ). One of the more used icons on my desktop is the one opening the dazzling labyrinth that is my file-system.
I've never really caught on to the desktop-concept. Maybe it's just me.. The desktop is the background for the windows opened by the applications I run. The harddisk on the other hand is the storage for my files (filing-cabinet anyone..?).
The desktop is a metaphor for a physical thing. And a bad one at that. As a lot of UI-design books will tell you one should be very careful when trying to use metaphors. Have a look at Interface Hall of Shame [iarchitect.com] for some examples.
Why do the author of the above article seem to think that multiplying an already bad interface will make it better? And even if the metaphor was a good one I've yet to see office-workers with e.g. a desk per client..
The problem with finding the next great interface is that the fundamentals in a computer-system is not about to change. We will have (and need) a lot of files (information split into little logical parts) for a long time to come. There is no way around this. Abstracting the storage-space and placing the files on seperate desktops instead of having them in folders accessible from anywhere does not change this fact.
Desktop uses (Score:3, Interesting)
The desktop stores links to other resources.
This applies to applications and to directories. The author of the original article is fundamentally wrong to say that the desktop contains the hard disk. Instead, it just contains a link to the directories "c:\" or "/home/$USER" or whatever.
This makes perfect sense if you want quick access to your folders, exactly as most people want quick access to their favorite applications.
However, he's right that the desktop has its limitations. It's especially stupid if you have to minimize all your windows just for the 5 second job of locating an icon and clicking on it. The taskbar of Windows 98 and the extended start menu of Windows XP do it much better...
Re:Desktop uses (Score:3, Insightful)
Hey, it works! And I'll bet that 99% of the
Yeah, I know it's somewhere in the Help files. However, if you don't know a function exists, you aren't going to find out about it from Help. Even if you know it _should_ exist, if you don't know what MS called it, you probably aren't going to find it. When MS writes a tutorial or "tips", it's worse than useless for anyone who already has some notion how to use the system -- their selection of which features and techniques to highlight is darned peculiar, and leads me to think that the authors aren't experienced enough in MS's own software to know what's actually useful... And there's no way to just start on page 1 and skim it all looking for the useful bits, even if I wanted to do that on screen.
Re:Oh please $deity, no... (Score:4, Interesting)
They are BEHIND these damn window things - WTF use are they there?????
All my shortcuts go on the menu. Where I can get them, without hiding the current app.
Desktops are useful, in real life, when they are large enough to sit *around* your work. You can reach out and grab pens and such. Desktops, on PCs, have never yet been big enough for me to feel comfortable with more than a couple of (non-overlapping) windows up at a time. (Don't get me started on overlapping windows... grrr...)
And I NEVER store files on the desktop. Why? Because, sonny, this is Win2K with a roaming profile. Everything you write there is synched with the server (which, half the time, is in a different city from me). T r y l o g g i n g o n t o d a.... oh feck it can I log on as you today?
- Cantankerous Old Git
Clarity, stability, manageability etc. (Score:2, Insightful)
It is all too common these days to have strange software, always in state of change and instability, to steal ("embed") other software to show some things ("Documents", "directories", "files", "web pages",
All the computing should return back into the days when the only way to manage computers was simple physical files and directories and independent applications. Even "Joe Luser" could understand that. You have a ".whatever" file, you can "open" it with "whatever" application. That's simple enough. You can see files with "file manager", you can write documents with "Typewriter", you can blowse the remote net with "Browser" throught the connection "network".. For more advanced users that would still leave the power to control everything, have options for "linking and embedding" as necessary and appropriate.
This nut talk about desktops, blurred storage concepts and leased software is pure crap. Sure it might confuse Average Joes enough to pay even more for nothing in the short sight, but it just doesn't work for everything. Not everybody uses the computer for the same purposes in the same way. There really isn't any sense to restricting usage of a general purpose machine with artificial limits (desktops), buggy sw/hw (display adapters, drivers), physical devices (monitor/flat panels) and messed up concepts about data and applications.
Aren't the GUIs there for communicating with users? Isn't the OS there as a base platform to run stuff on? Shouldn't somebody write a "Joe Really Dumb" application to act as a GUI for those confused with logical storage and general computing concepts? They could then limit themselves with that application to two icons and a power button if anything more is too complicated.
Oh well, maybe I missed the point completely, or this confuse-and-conquer is just a business plan for somebody.. Whatever, it sounds like crap anyway.
He's wrong (Score:5, Interesting)
If the desktop metaphor is perfect, yet the "hard drive" icon is part of the metaphor, the how can he claim that the metaphor is perfect and it's the implementation that's wrong?
Ignoring the fact that they contradict themselves in the first paragraph, there's plenty of other glaring holes in the argument.
"The extension of the "rules of the desktop" to cover the entire capacity of the hard disk is the main reason why systems that support multiple desktops seem simpler and are easier to use and manage."
Who says it's simpler? You still need to initially setup that desktop, which involved setting up shortcuts to locations in the file system. Try doing that without delving into the hard drive while still maintaining a super simplistic environment (i.e. no command line either). Besides, maybe I have a lot of data and need 20 desktops to organize it correctly. So instead of setting the default "open" path in the application of my choice, I would have to switch desktops to open a file. What if I want several things of different types open at once?
"It is possible to build labyrinths of internal directories that eventually become too deep to navigate via the mouse. The feeling of such spiral filing systems is of endless depth, requiring great effort to retrieve a piece of information. It is difficult to create the same spiral feeling on the desktop."
So sub-folders are a bad thing I guess. Yes, it's terribly confusing to have a tree like "documents/company/forms/standard contracts". That would be too confusing to navigate. But if you had someway of setting a "view" on the desktop that would be simpler. And this "view" menu would be incredibly simplistic to use and would be able to differentiate between Forms and Letters in a DOC or PDF file? Gee, that sounds like more work when I create the document too.
"To reap the benefits of the desktop metaphor, we have to design computer systems that leave the user clearly anchored in the desktop metaphor at all times. But in the multiple desktop, you are always on a desktop and can't ever get lost inside the computer."
Ok, but you could get lost in all the desktops you'd need to setup.
The desktop was designed to give users quick access to common programs. You don't need every file you ever need to use, sitting on your desktop, or even some virtual desktop somewhere. Because if you only use it once every six months, you're going to forget what desktop it's on anyways. Intelligent directory trees and default "file-open" locations are the way to do it. The methods outlined in this article would require a lot of extra setup the user would have to do, and doesn't address new files being added by another user on a network.
I guess I was really bored this morning, I didn't intend to comment that much on an opinion piece on some other site. Which makes me wonder, why are we linking to use opinions on other sites? Maybe the author is somebody I know, but isn't this like linking to a slashdot users comments?
Ok, we'll kill the icon (Score:3, Interesting)
I get what the pundit is saying, but the idea of multiple desktops to do everything is awkward. Calling for that as a matter of usability is to fail to realise the general cluttered state most people leave their desktops.
Yeah, getting rid of the icon is probably a good idea. It is a "box" elsewhere and it's frustrating. Most of the newbies I see go through three stages:
I don't know about you, but having a directory system I can bring up on my "desktop" that lets me jump through is great. It all depends on how you use the system. But face it, as people becoem power users, the directory structure will come back again and again. Most people can't wait for tech support and thus will always migrate away from the dummy device.
Not mutualy exclusive, surely (Score:2, Insightful)
Funny, I always thought it was complementary to the desktop metaphor.
If you're looking for ease of use for a limited set of functions, by all means put icons on the desktop, or group then into function-related folders on the desktop, or whatever. Have more than one desktop each with its own set of icons or folders for mutually exclusive functions? By all means. But do provide a reasonable way for system managers to easily organise the functions in a way that makes sense from the user's point of view. To some extent, this is already done when you (as end-user and system manager of your own personal Wintel box) install an intelligently-packaged new application and are asked whether you want an icon for it on the desktop, and where you want it to be integrated into the taskbar mechanism. Of course, some application vendors believe that their customers shouldn't have these choices, but that's another matter.
But once you get beyond a certain number of functions, and a certain level of complexity, then direct access to the underlying hierarchical file system has a lot to recommend it.
Just my 0.02 Euros
Logical volumes? (Score:2)
Some poster mentioned taht this article was refering to something along the lines of logical volumes... but what about redundancy and fault tolerance.
regardless of what this article is suggesting (however confusing in and of itself) there will *ALWAYS* need to be the people who do look at the disk as a disk - and need to know where the shit is stored. The admins and architects of such systems.
also - what does this mean:
"Move the mouse beyond the boundaries of a directory"??? huh? am I missing something?
and this:
"But in the multiple desktop, you are always on a desktop and can't ever get lost inside the computer. " - um - but wouldnt the newbie user get lost amongst the multiple desktops? If this guy thinks that any newbie or even just a moderate user will be able to feel really comfortable in a CLI having to navigate some nebulous filesystem spread on who knows what HDDs... I think he is mistaken.
"The use of "stacked desktops" as the overriding method of organizing " - ok so what he is saying here is that he doesnt want a bottom level "desktop" - and doesnt want some sort of "start" menu system - of file manager to navigate through and find the files/apps that he needs - he would rather have almost everything open in a window and just have to navigate through the many many things that are open...
So I picture his desk at work just being covered in single 8x11 peices of paper and he is constantly shuffling through them - but thinks it all organized...
.
Might not be that bad an idea (Score:2)
That is not so far from how I use my 8 KDE desktops, one is always for mail, one for the web, one for VmWare (some customers still insist to pay me for coding Windows stuff), one for real programming (3 consoles: editor, compile, and misc/man/another edit/...) carefully laid out to fill the screen...
The only problem is that with such a system the users would leave zillions of applications running everywhere. But that's why we keep getting faster computers...
Desktop means Desktop (Score:5, Insightful)
Directories may not make sense to some. That's why Apple and others called them folders, as in a manila folder. You take a document off your desktop and file it away in a folder. Simple.
Remember, the original Macs used floppy disks. You frequently had more than one inserted. They looked the same on screen as they did on your other desktop. You put stuff you didn't want anymore in the trash can. Very simple for office workers to learn.
Getting back to the article, of course the desktop took up the whole screen. What do you want around it, the floor?! Walls?
How does one get rid of the disk icon? I have two main internal hard drives (20GB and 30GB). How else do I tell them apart? What if I insert a zip or a CD? How do I tell them apart? Or an external FireWire or USB drive? This doesn't sound very well thought out! You *could* integrate permanent drives into one structure using mount points but how is that easier for the new comer? "Oh your second disk is mounted so that it is part of your first disk". "What?"
Having said all this, I don't have a desktop. I use MacOSX. The only thing below the windows is a desktop picture. My hard drives are in the computer window. So, in a sense, Apple has partly phased out the desktop metaphor. It still has folders, but you can choose not to display a desktop. The new representation is a Computer with icons representing all your storage devices (similar to My Computer in Windows). This is closer to what the new, computer literate generation, mine, interprets it to be.
In short, we don't need a metaphor anymore. You only need a metaphor when explaining to new people. Using the office as an analogy made sense when computers were new. How is an office analogy going to help a young child learn about computers?
I'd like to see us go to a database-like idea with the ability to attach arbitrary attributes to files and replace folders with categories. A file could belong to more than one category. Related categories could have links between them. Instead of a tree you'd get more of a web. Don't know if it'd be any simpler though. For the time being the current idea works.
Abstractions (Score:3, Interesting)
I should be able to use a computer without knowing the details of inodes, free space bitmaps, disk partitioning, and the I/O channel configuration of the computer. It is the operating system's job to manage that stuff and hide it from the user. The user interface should present a suitable abstraction or abstractions that is not dependent on the implementation details of the computer's storage system.
The desktop is the whole computer (Score:2, Informative)
The problems arise when operating systems adopting the desktop have to support parallel legacy concepts, such as Windows with it's multiple X:\ roots or Mac OS X with the Unix directory tree.
The cleanest desktop implementation has always been the old MacOS (=9), where the desktop is consistently presented as the root of everything. Through it you can access hard disks and other storage quite naturally, and you never get lost.
that's not exactly a surprise (Score:2, Insightful)
Fast forward to 2001 and you have an underlying OS with sophisticated name spaces, networking, hypertext, and access to gigabytes of data. Icons representing devices and a handful of files don't cut it anymore, if they ever did.
This is, of course, also why trying to adopt the Apple GUI to UNIX machines has failed so miserably in the past. It wasn't that the Apple GUI was so super-sophisticated that nobody could copy it. Rather, UNIX has always been too complex for the Apple GUI to represent well.
So, where does that leave us? Windows, Gnome, and KDE are slavishly trying to copy the original Apple paradigm, putting file icons and link icons everywhere, leading to a complex mess. Yes, this needs to go. Trouble is, while there are a bunch of better ideas, the one thing that users hate more than a bad UI is a UI that's different from what they are used to. So, all the good ideas that are out there (and have been out there for a couple of decades) have a really hard time in the market. It's not better ideas that's needed, what's needed is better ideas that are also palatable to existing users. And that, nobody has come up with yet.
What's the point? (Score:2)
So, it is possible that you might forget once in a while, where you put something? Big deal, same thing happens in the real world. There I have, next to my desktop, a closet. And a floor. And a briefcase. And a toolbox. And more. And that tiny jumper I need to put my harddisk in slave-mode might be in a box, or in a small plastic bag, or on the floor. And that bag might be in another bag, or in a box, or under a pile of papers. And that container might be in the toolbox, or on the floor, or on the desktop. Come to think of it, didn't I throw away that jumper a couple of weeks ago?
:-)
A mouse (or cat) might traverse the mess around my real-life desktop, but it certainly is a labyrinth... Now, where did I put that harddisk?
In Defense (Score:3, Insightful)
However, I think I should have a go at arguing for this guys idea, as nobody else is!
On my computer, I use multiple desktops. I have one for work stuff - star office, kpresenter etc. I have another desktop for multimedia - xmms, mplayer, realplayer etc, a 3rd desktop for gaming, and a 4th (spare!) desktop. Yes, I am a bit wierd and anal (see yesterdays discussion about autism!). Furthermore, I usually organise my linux consoles in a similar way - tty1-2 for root access, the rest for userland stuff, another one for tailing logs and a vt100 open at the end (comes in usefull on occasion).
I find this logical division of "desktops" enables me to better organise myself. I dont see why MS Windows couldnt enable this for Harry Homeowner. Somewhere on the taskbar is a shortcut for desktops. It is trivial to change/add/remove desktops. When you install a game, it is "installed" to the game desktop. There is a shortcut on the desktop/start bar for that desktop. The working directory for that game is on the desktop. For many users, who just need Office, Explorer, winamp and a few games this might work.
However, I can think of a number of problems that would need to be overcome. What about generic applications, which you may need on a number of desktops? What about applications which dont fit into any desktop category? What happens when the desktop starts getting to cluttered? What happens if you want to open Word and that RPG on the same desktop (i.e. so you could copy and paste the final text into word, to prove you had completed the game to an equally sad friend)? I'm sure most of these problems are trivial to overcome, but you will surely encounter further difficulties.
Finally, I dont think you can ever get rid of the Hard Drive icon. Yeah, just hide it away, so Harry doesnt get confused by it. But it still needs to be there for power users.
Let's time doing its work (Score:2, Interesting)
MSWindows have added some interestings changes, like a "real" top level desktop, a taskbar, a quicklanch bar, a start menu, a trash... And now that I'm using Debian with Ice, I choose to reuse some os these ideas, suppress some, to obtain MY perfect desktop.
And it's the same for the user community: God created the taskbar, everybody used it, some linux GUI used it too, so God saw that it was good.
It's a kind of natural evolution...
The Good Ol' Days (Score:5, Interesting)
Multiple desktops are simply windows. Call them whatever you want, but the authors want a windowing motif without a base window to throw junk onto.
The other problem is the incredible naivetee of this statement from the article: Add unlimited files without fear of clutter. (You can change views in a directory.) The first time you used a Disk Operating System, you had a tendancy to throw all of your files into one directory. That's my definition of clutter, and it is no different than the desktop paradigm where junk files reside.
I think the authors are forgetting history and the reasons why we don't use bare-bones DOS to operate our applications. They're also forgetting that with a computer monitor, if you remove all of your desktops, what's left? there has to be some basic background, even if it has no functionality.
All these so called experts... (Score:3, Interesting)
His proposal of imposing artificial, view based limits on the organazation of files is ludicrous. He spends his time complaining that while their is a screen with a Desktop, it's not consistant with directory structure, not like we have it in real life. Last time I checked, people working on stuff on their desks pull them out of a file cabinet and put them back when finished, more like the computer paradigm. It makes sense to store your information differently from the way we work on a desktop. A strategy like he suggests would impose a huge penalty in terms of time to organize and retrieve data that is not currently on the Desktop, and greatly limits the amount of data that can be in one space, even if the relationships demand that they *should* be together, regardless of "icon clutter".
All these self-proclaimed experts need to be hit a few times with a clue stick. Users like the paradigm the way it is, it is not too complicated.
I like the home dir concept (Score:3)
Whether I am in KDE or Ximian Gnome, I always make my home dir my desktop. The place where I keep file IS my desktop and the problems with these concepts are thrown away. This is not a big issue.
Under Nautilus with my home dir designated as my desktop, I can right click and mount volumes that are not essentially part of my essential OS environment (removable media for example) keeping these things seperate makes sense.
One of the filesystem concepts I loved when I first got into the *Nixes was the idea that everything extends from root. If I have an NFS mounted file system from a system two buildings away it appeared to the end user as just another directory in their tree (No C:\ drives and D:\ drives etc...).
The man makes good points and these points are being addressed by people like the folks working on KDE and Gnome that give you the flexibility of NOT creating some extra space called the desktop that does not correspond with the rest of your file structure.
The idea of your home directory as your desktop (as the place where you keep your files) is one that works suprisingly well in a visual GUI format.
My wife with no big *Nix experience loves the idea because she does not have to go hunting for files she dragged to the desktop to organize them in her folders off the home dir or she can pick them right up off her desktop if she needs them.
This is an idea that is good for experienced and novice users.
desktop? bah! we need cube walls! (Score:3, Interesting)
at first you arent sure what metaphor he is whinging about, but then you realize that he does have a point.
we need a new metaphor. its true. we do. and its not really us who need new metaphors, its the typical user community. the ones who we usually bitch about - the AOL users of the world. and since we're all such ass-kick programmers (l33t c0d3 h4>but what i would really really like is to have the desktop not be a file metaphor, but a notes metaphor - in other words, kill the desktop and make it a cube wall metaphor. one where i can stick up notes and reminders and post its. where i can "hang" my clock, my calendar, or maybe where i can hang a shelf to put books and manuals at.
I've always found the "Desktop" concept somewhat difficult. it doesnt feel like a dsektop, its standing up in front of me. why would i be looking down at it? (i know, i know, pre computers we used to write by looking down at the desktop, but i always focused on what i was doing, not on the things strewn about the 5 foot wide space...)
actually, one metaphor that i did like was the old Magic Cap os from General Magic [generalmagic.com] it used a Desktop [emulation.net] metaphor and also a Hallway [emulation.net] metaphor. these actually work when you realize that people shouldnt have to think to use the computer, they should just be able to use it.
Make computers easier to use, and we'll have more people using computers and doing more with them. To me, thats what makes a GUI good. Thats why i think people liked the mac originally. you didnt have to learn how to use it, it was all presented for you in a graphical and friendly manner - as opposed to a command line.
The GUI has to evolve again. lets go for something even easier to use.
This author has lost his mind!!! (Score:4, Insightful)
The hard disk icon was an error that should disappear from mainstream computer systems. Multiple desktops should be implemented across the board to simplify the life of casual users everywhere.
What? I don't think this person has ever done anything useful with a computer. I have so much I want to say to rip this apart but I just can't organize it all in my head. I'll just say a few quick things:
He's right about one thing: Most OS's don't implement the desktop idea correctly. What he's wrong about is his idea of a desktop. The whole concept, started by Mac OS, was that you have a desk, and the desk has drawers. You go into the folders within the drawers (directories within the hard drives) to get the files you want to use, and then you take them out and they are on your desktop. Macintosh still is the best at this. Their entire OS is extremely easy to grasp, even in OSX, only now it's much more powerful to the advanced user. Windows is just a cheap immitation. Linux is... well it's great, but it's desktop idea was meant for functionality and power, not casual use (at least in early distros.)
Now we come to the suggested desktop idea. This is ridiculous. Having multiple desktops that you toggle to, having no directory structure at all? Do you all realize how ridiculously point and click that would be? No longer could you go in a directory tree browsing program and efficiently move things, you would have to slect them with the mouse on one desktop, do the copy command, tab over to the desktop you want, then do the paste command. That's right, no more "cp" for you linux people, it's all point and click... That's just not going to fly. It's not powerful enough. The other thing is, think about this metaphorically. Multiple layered desktops... what in the hell can you compare that to? Having like 10 desks in a circle and you spin around to see which one you'll use? Stacking 10 desks on top of each other? I just don't see how that's easier.
Granted, I like the multiple desktops in Linux. I use them to have multiple full screen applications running at the same time. They have many other uses. On the other hand, I use the file tree browser, or the command line, to do all of my file management. It simply is the most convenient and powerful way, and if a user can't learn to browse a file tree... well... they need to pick up a new hobby/occupation.
A matter of coping with complexity (Score:3, Informative)
The idea behind this article is that there are too many spatial configurations in a operating system for a user to be able to cope and concentrate on information flowing from one to the other. The desktop represents one type of spatial configuration (limited movement, space, etc.) while the hard disk icon represents another (limitless space, movement beyond the edges, etc.). The author proposes that it is asking too much of users to be able to make these spatial conversions.
Now, let's think about this. Don't you already do spatial conversions all the time? You think of a house, that's in 3D, usually (in your mind). You go to an architecht, he draws the house in 2D (on paper), maybe with some 3D perspectives, but still in 2D. You take this to a contractor, and they construct the house in 3D! This is spatial conversion, folks. We all learned to do it as children, converting the spaces of normal paper into 3D houses, turkeys, etc....whatever those projects were in 3rd grade.
It still comes down to a learning curve and ability scale. Most everyone will learn a system faster if they don't have to do spatial conversions. Therefore, for the ease of learning, such a "desktop only" system might be pertinent. However, computers are complex things and are expected to encompass a lot of different information in a lot of different configurations. Limiting yourself to one spatial relationship will only limit you in the end as to what you can store, manage, and organize. Having both the desktop and the hard drive paradigms to manage information will result in the ability to store the vast amounts of different information available.
And they keep missing the target. (Score:3, Insightful)
Until we store files on the harddrives differently (non-hierarchical) there will always be a diference in the WYSIHWTDI 'what you see is where the data is' views.
A disk is equivilant to a tree. A tree has branches(path), and leaves (files). In a forest I can see all the leaves or just one branch, or a leaf. If I prune a tree that branch is gone. If I move a branch, I cut and graft (not paste) Vines are interlinks between fiels, and sometimes trees. Devices are fruits(mp3 devices) and or flowers/nuts.
Now when I see a 3D version of my forest then it will be good.
Trees was the original metaphor.
Now, where was that hedge trimmer?
We need the Beatles (Score:3, Insightful)
Most people do not understand file management or how their operating system works. They identify only with the applications they use. That is why when you ask someone what OS they run they will tell you "Office 2000" or somesuch. The applications are the OS to these people.
In that respect, a streamlined OS for the average user should be transparent. The user should spend little time thinking about where files are stored or what folders are where. Get them into their applications and make locating files easy. The less time spent moving files around or making your icons line up pretty, the better.
We need the Beatles. They could not read sheet music and did not know they were breaking all the rules for song writing. They wrote new rules that worked. We need a new OS written by someone whose ideas are not hindered by the assumptions that have brought us to where we are today.
The solution is simple (Score:3, Insightful)
This is how it should be: there is a panel at one of the sides of the screen, the rest is a "workspace" where programs visually reside.
The panel/dock should provide some kind of visual clue that things can be added and removed from it. It will now be seen like an advanced kind of menu, rather then an extension of the filesystem.
There really is NO reason to confuse users with having launchers for programs in the same physical area as where programs run; It should be like a windshield in a car, keeping the programs away from the driver.. The controls (and launchers) should all be on the inside of the windshield.
Computere are a lot more like cars then you think.
Baffling article... (Score:3, Insightful)
He says that the directory system is confusing because it is limitless, and suggests some vaguely defined notion of unlimited space. So he advocates using "desktops", which have fixed "physical" limits. But then to get around the obvious problems with having such limits, he suggests using many virtual desktops accessed by some sort of menu or taskbar. Um...hello? The only difference between a hierarchial directory structure (a collection of folders inside one single "root" directory, each of which can contain files or more folders) and a system of multiple virtual desktops (a collection of "desktop" areas inside a single logical collection, each of which can contain files or folders) is that the desktops have artificial and arbitraty limits on how much stuff they can hold. How exactly does limiting the number of items you can place in a unit make it less confusing to use? Is it worse to have to search through 100 files in one directory to find what you're looking for than to navigate through ten different desktops with ten files each? And if it is, why can the user not simply create ten NEW directories, if that is how they wish to organize their stuff?
Basically, the desktop system Loebel is proposing is a hierarchial directory structure where the directories don't have scroll bars. Where is the logic in that?
As for making computers easier to use...that's a very hard task. As a rule, the more a particular tool can accomplish, the more complex it is to use. A computer is a tool that has virtually limitless applications, and as a result, it is a complicated tool to use. The problem is, end users want computers to be as simple as a toaster to operate, but they also want all of the functionality of a full-fledged computer system. Sorry, folks, but such a thing simply isn't possible. You can have ease of use or you can have a broad range of functionality...but you can't have both. That's not to say that it's not possible to make current systems *easier* to use while preserving functionality, but a computer will never be a toaster, nor should it be.
A hierarchial file system is not that hard to learn to use. Yes, it does require some time and effort to learn, but it is far from impossible. A complete novice can't turn their computer on for the first time and instantly know how the Windows file system works, but it is certainly possible to learn. Anyone who wants to use a computer should devote some time to learning the basics. It's no different than driving a car or using any other complicated device. You don't sit behind the wheel of a car and instantly know all of the traffic laws, or all of the functions of your vehicle. You had to study them first, and learn about them. The same goes for using a computer. And you don't have to know how compile your own kernel or write shell scripts to use a computer to write e-mail, any more than you need to know the inner workings of your car's engine to drive it. These more complicated things can be learned later, if you have the interest and the time, but there are still some basics that you should know when you start using a computer.
DennyK
Another one of these pseudo-academic jerk-offs.. (Score:3, Insightful)
What the hell does that mean? That there's some point where you just can't click the mouse just *one* more time?
"Spiraling file systems..."
God, I hope I'm not around to watch this guy freak out the first time he comes across a self-referential symbolic link..
And we continue:
But wait a minute! Just a moment ago we were spiraling downward into a maelstrom of "endless depth" from which no mouse could escape, let alone get us into in the first place...
Which is it?
What has this guy been smoking?
A hard drive is "vague"?
Funny. I've always found cd
/var/log/snort, for example, to be pretty goddam specific.
But maybe I'm missing something...
Ah! here's a hint:
One of them Mac-using graphic "artists"
heh..
t_t_b
Re:"The" hard disk icon? (Score:5, Insightful)
However, the real problem I see with the article is they don't suggest how users would deal with partitioning their space if one got rid of the harddrive icon. What I mean is, suppose I create a new directory under my root desktop, how do I specify which harddisk it should be on to better divide the free space I have on each disk? Surely they wouldn't propose that Mac end users should play around with auto mount lists as is done in the UNIX world?
I suppose one solution would be to use logical volumes to treat all harddrives on a system as one single volume, but if so that's a much bigger change than just eliminating the hard-disk icon, and the implications of it should be better explored (if that's the sort of solution they were going for).
Personally, I dont think anyone is particularly confused by hard-disk icons, and think the article is just blowing smoke...The article never really tries to back up its arguments or give real-world alternatives except at a very superficial level.
Re:"The" hard disk icon? (Score:2, Interesting)
I also know that if I raid 0 a 15g and a 30 g, I get a 30g(100% of the 15g and 50% of the 30g) Is there a way to raid 0 them to a 45g?
Maybe that is the softraid you talked about, I never seen it, so let me know
Re:"The" hard disk icon? (Score:2, Insightful)
Obviously this is a comment from a Mac user. I don't mean this as a flame. The idea presented basically tries to maximize ease of use to the computer illiterate with no regard for how much it hurts actual functionality. Apple has been tdoing this for years. They hide any real information from the user to make things easier on them. They got rid of the CLI, the next logical step is to remove the filesystem.
Again, I'm not trying to mac bash here, I even suggest macs to people who say all they want to do is browse the web and read e-mail. But the more you really want to use a computer, you realize that the more information you can get your hands on the better. This desktop idea would only serve to let people use the very basic functions of a computer, but it will never let them get any further than that.
Re:This sparks a question... (Score:2)
Actually the standard for VMS file names is this: devicename:[dir.subdir1.subdir2] So your home directory might be: DBA1:[USERS.YOU].
You could play games with logical names so that you, as a user, did not have to know about actual devices, but I thought this was pretty akward.
The Unix file system is a lot easier to deal with. | http://developers.slashdot.org/story/01/12/18/0358255/lets-kill-the-hard-disk-icon | CC-MAIN-2015-11 | en | refinedweb |
Screenshots
Description
User Ratings
User Reviews
Very good and easy to use. But, could you enable us to specify the lineType when calling draw functions? I have rewritten them myself and compiled, but I think others would like this too. In order to not break things, you can use default values for the parameters, like so: ///<summary> Draw a line segment using the specific color and thickness </summary> ///<param name="line"> The line segment to be drawn</param> ///<param name="color"> The color of the line segment </param> ///<param name="thickness"> The thickness of the line segment </param> ///<param name="lineType"> The linetype to use when drawing </param> public virtual void Draw(LineSegment2D line, TColor color, int thickness, CvEnum.LINE_TYPE lineType = CvEnum.LINE_TYPE.EIGHT_CONNECTED) { #if !NETFX_CORE Debug.Assert(thickness > 0, Properties.StringTable.ThicknessShouldBeGreaterThanZero); #endif if (thickness > 0) CvInvoke.cvLine( Ptr, line.P1, line.P2, color.MCvScalar, thickness, lineType, 0); }
very good project, thanks!
works perfectly.
Great product emgucv
emgucv and opencv_engine really works perfectly. congratulations... | http://sourceforge.net/projects/emgucv/?filter=thumbs_down&source=directory&sort=usefulness | CC-MAIN-2015-14 | en | refinedweb |
13 replies on
1 page.
Most recent reply:
Dec 19, 2008 11:54 AM
by
James Iry
2008 has seen a lot of activity around Scala. All major IDEs now have
working Scala plugins. A complete Scala tutorial and reference book
was published and several others are in the pipeline. Scala is
used in popular environments and frameworks, and is being adopted by more
and more professional programmers in organizations like Twitter,
Sony Imageworks, and Nature, along with many others.
It's also a sign of growing momentum that well-known commentators like
Ted Neward, Daniel Spiewak and the JavaPosse have covered Scala in
depth. Other bloggers have argued more from the outside, without
really getting into Scala all that deeply. I find the latter also useful,
because it shows how Scala is perceived in other parts of the
programming community. But sometimes, initial misconceptions can
create myths which stand in the way of deeper understanding.
So, as an effort of engaging in the debate, let me address in a series
of blog posts some of the myths that have sprung up in the last months
around and about Scala. I'll start with a post by Steve Yegge. Like
many of Steve's blogs, this one is quite funny, but that does not make
it true.
Steve (in his own words) "disses" Scala as "Frankenstein's
Monster" because "there are type types, and
type type types". (Don't ask me what that means!)
In fact, it seems he took a look at the Scala Language
Specification, and found its systematic use of types intimidating. I
can sympathize with that. A specification is not a tutorial. Its
purpose is to give compiler writers some common ground on which to
base their implementations. This is not just a theoretical nicety: the
implementation of JetBrains' Scala compiler for IntelliJ makes
essential use of the language specification; that's how they can match
our standard Scala compiler pretty closely. The other purpose of a
specification is that "language lawyers" - people who know the
language deeply - can resolve issues of differing
interpretations. Both groups of people value precision over extensive
prose. Scala's way of achieving precision in the spec is to be rather
formal and to express all aspects of compile-time knowledge as
types. That's a notational trick which let us keep the Scala spec
within 150 pages - compared to, for instance, the 600 pages of the
Java Language Specification.
The way a spec is written has nothing to do with the experience of
programmers. Programmers generally find Scala's type system helpful in
a sophisticated way. It's smart enough to infer many type annotations
that Java programmers have to write. It's flexible enough to let
them express APIs any way they like. And it's pragmatic
enough to offer easy access to dynamic typing where required. In fact
Scala's types get out of the way so much that Scala was invited to
be a contender in last JavaOne's Script Bowl, which is normally a
shootout for scripting languages.
But Steve's rant was not really about technical issues anyway. He
makes it clear that this is just one move in a match between
statically and dynamically typed languages. He seems to see this as
something like a rugby match (or rather football match in the US),
where to score you need just one player who makes it to the ground
line. Steve's on the dynamically typed side, pushing Rhino as the
Next Big Language. Java is the 800-Pound Gorilla on the statically
typed side. Steve thinks he has Java covered, because its type system
makes it an easy target. Then out of left field comes another
statically typed language that's much more nimble and agile. So he
needs to do a quick dash to block it. If he can't get at the
programming experience, it must be the complexity of the
specification. This is a bit like saying you should stay away from
cars with antilock braking systems because the internal workings of
such systems are sophisticated!
Not quite surprisingly, a number of other bloggers have taken Steve's
rather lighthearted jokes as the truth without bothering to check the
details too much and then have added their own myths to it. I'll write
about some of them in the next weeks.
def method = "def" ~> name ~ formals ^^ { (n, f) => ...}
def method: Parser[Unit] = "def" ~> name ~ formals ^^ { case n ~ f => ... }
"a*b".r
"\\d*b".r
"""\d*b""".r
implicit def flatten2 [A, B, C](f : (A, B) => C) : (~[A, B]) => C
Function1[String, Int]
String => Int
val a: String => Int = something
super
SingletonObject.type
>:
<:
<%
Enumeration | http://www.artima.com/forums/flat.jsp?forum=106&thread=245183 | CC-MAIN-2015-14 | en | refinedweb |
csBSPTree Class Reference
[Geometry utilities]
This BSP-tree is a binary tree that organizes a triangle mesh. More...
#include <csgeom/bsptree.h>
Inheritance diagram for csBSPTree:
Detailed Description
This BSP-tree is a binary tree that organizes a triangle mesh.
This tree will not split triangles. If a triangle needs to be split then it will be put in the two nodes.
Definition at line 46.
Build the BSP tree given the set of triangles.
Clear the BSP-tree.
The documentation for this class was generated from the following file:
Generated for Crystal Space 2.1 by doxygen 1.6.1 | http://www.crystalspace3d.org/docs/online/api/classcsBSPTree.html | CC-MAIN-2015-14 | en | refinedweb |
Custom ToolTip to heigh
Custom ToolTip to heigh
(Beta 2) I'm trying to customize a tooltip, but the tooltip gets to heigh.
It looks like this.
tipNotOk.PNG
But should look like this
tipOk.PNG
TestCase:
Code:
public class ToolTipTest { public interface Renderer extends ToolTipConfig.ToolTipRenderer<String>, XTemplates { @Override @XTemplate("<div>TEST</div>") public SafeHtml renderToolTip(String data); } public void setup() { TextButton button = new TextButton("test"); ToolTipConfig ttc = new ToolTipConfig(); Renderer renderer = GWT.create(Renderer.class); ttc.setRenderer(renderer); ttc.setCloseable(true); button.setToolTipConfig(ttc); RootPanel.get().add(button); } }
Thanks for the responce.
The problem is my custom tip is more complex than the one in the testcase. It contains some nested divs.
(I used <span> to produce the "correct" screenshot)
The problme is also visible in the explorer demo for the custom toolip
I got this working now.
My workaround was to create a custom TipAppearence with my own template where the span is replaced by a div.
I still think it's a bug that should be corrected.
Thank you for reporting this bug. We will make it our priority to review this report. | http://www.sencha.com/forum/showthread.php?179145-Custom-ToolTip-to-heigh | CC-MAIN-2015-14 | en | refinedweb |
> > > > Which means proc_root_link, when it switches to the vfsmnt at the root> > of the other process, should traverse into the tree of vfsmnts which> > make up the other namespace.> > Yes. But proc_check_root() in proc_pid_follow_link() is failing the > traversal, because it is expecting the root vfsmount of the traversed> process to belong to the vfsmount tree of the traversing process.> In other words its expecting them to be both in the same namespace.> > The permissions get denied by this code in proc_check_root():> Removing the check makes chroot enter the tree under the otherprocess's namespace. However it does not actually change thenamespace, hence mount/umount won't work.So joinig a namespace does need a new syscall unfortunately.Miklos-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at | https://lkml.org/lkml/2005/4/29/95 | CC-MAIN-2015-14 | en | refinedweb |
SubcontractorServices implementation in thick client.
Cesar Cardozo
Greenhorn
Joined: Jun 30, 2013
Posts: 14
posted
Jul 13, 2013 00:27:36
0
Hi guys.
As I had commented in my previous post I have almost finished my project, but I found another "possible" weakness. I'm using a thick client because of the use of cookies. So in the client side reside the gui, a controller and the services. The server has de database connection.
A big issue that most of the candidates had found with this thick client is that the DB interface doesn't throw the
RemoteException
in its methods when we decide to use RMI. After searching approaches in this forum and reading alternatives in other sources I opted for implementing the Proxy
pattern
to have the DB interface in the client and the server side.
What I did in concrete was to develop a remote adapter interface that has the same methods that the DB interface but I added a
RemoteException
in each one. The implementation of this remote interface is essentially an wrapper of my Data class. Then I simply register this object in the RMI registry. Of course this is in the server side.
In the client side I created a Proxy class that implements the DB interface and in the constructor I look up the remote adapter object registered in the RMI. I found this approach pretty simple.
Now the "dark" side of this solution is: The proxy class is an wrapper of a remote object but still somehow has to deal with the RemoteExceptions. I don't rememember well but in one thread in this forum I read that someone wrote "and the proxy class eliminates the RemoteExceptions". My mind was blowing because I had learned that I should not swallow these exceptions just because the DB interface doesn't throw them!!!.
Then my solution was to create a NetworkException that extends a
RuntimeException
and declare it as part of the API of the DBProxy class.
public class DBProxy implements DB { ... //NetworkException is a RuntimeException. public String[] read(int recNo) throws RecordNotFoundException, NetworkException { try { //dbAdapter is a remote object registered in the RMI registry. return dbAdapter.read(recNo); } catch (RemoteException ex) { throw new NetworkException(ex.getMessage()); } } .... }
The compiler is happy and so do I. Everything still is simple.
Now, which class is going to use this DBProxy that implements the DB interface?, of course a SubcontractorServices class. This class takes a DB interface in its constructor . Also, this class implements a bookSubcontractor method and a searchSubcontractors method. Then a programmer knows that these two methods depend only of the structure of the DB interface methods.
However, things get glommy when you reason this: what if I pass a DBProxy class in the constructor. This is valid because the DBProxy class implements the DB interface that is what the SubcontractorServices class needs. But what if in the middle of one operation for example, the DBProxy read method throws a NetworkException, how the programmer knows that he has to catch this exception if is not documented in the DB interface.
I as the developer of these classes know that I have to catch this NetworkException(
RuntimeException
).
public class SubcontractorServices { public SubcontractorServicesImpl(DB database){ ... } public List<Subcontractor> searchSubcontractors(String[] criteria) throws ServicesException { try{ //I use the find and read methods within the logic. ... } catch(RecordNotFoundException ex) { throw new ServicesException(ex.toString()); } catch(NetworkException ex) { throw new ServicesException(ex.toString()); } }
The solution is simple again, I just have to catch the NetworkException in a catch that accepts an NetworkException. But again, I am the developer and know that someone could pass either a Data class (standalone mode) or a Proxy class (client mode), and thus I am aware that I have to catch this unchecked NetworkException.
But.....someone that is not the developer will not have a clue that the read method could throw the NetworkException simply because is not documented in the DB interface. If a junior programmer reads the code he may think, where the hell does this NetworkException come from???.
My idea is to simply document in the SubcontractorServices class that a DBProxy class could be passed and this class throws the unchecked NetworkException in each one of its methods.
What do you think, it is enough to document this "ghost" exception in the SubcontractorServices class? The logic of the application is simple at least for me. In the standalone mode you first create your Data class and then pass it to the SubcontractorServices class. In the client mode you first create your DBProxy class and then pass it to the SubcontractorServices class.
Regards!!.
Cesar Cardozo
Greenhorn
Joined: Jun 30, 2013
Posts: 14
posted
Jul 13, 2013 01:22:40
0
I just checked Andrew Monkhouse's approach. He did something similar but in the controller class.
Inside the controller he request a specific DBClient implementation depending on the application mode. In his solution he uses a factory instead of passing the DBClient to the constructor of the controller class.
The DBClient class throws
IOException
in its methods and that is how he handles the
RemoteException
issue.
Now the way he deals with the RemoteExceptions in the controller class (that in my case would be the SubcontractorServices class) is to catch them using a general Exception. However, in his case another programer that looked at his code would know why that exception is there, to treat RemoteExceptions. Just because it is declared in the DBClient class as a checked exception using the
IOException
.
In my project I could use a the same tecnique and have a catch with a general Exception to indicate: "... and any other exception (including the unchecked NetworkException) will be treated here.". Of course I will document it and everyother programmer would be aware what is going on.
K. Tsang
Bartender
Joined: Sep 13, 2007
Posts: 2757
9
I like...
posted
Jul 13, 2013 01:23:05
0
After reading this kinda long post, I personally don't recommend using a
RuntimeException
.
My understanding is that your basic problem is how does the client know which service to call (local or network)? RIght?
I figured you used RMI. At least here is my version when I did it. The remote service implementation delegates to the local service implementation. I have an interface that extends the Oracle provided interface that throws DatabaseException and some other exception I don't remember. So when say a
RemoteException
or some other like RecordNotFoundException is thrown in the services, I rethrow it as DatabaseException for example and inform the user.
K. Tsang
JavaRanch
SCJP5
SCJD
OCPJP7
OCPWCD5
OCPBCD5
OCPWSD5
OCMJEA5
part 1
Cesar Cardozo
Greenhorn
Joined: Jun 30, 2013
Posts: 14
posted
Jul 13, 2013 01:54:32
0
Hi, thanks for your reply.
I have an interface that extends the Oracle provided interface that throws DatabaseException
I also have an extended interface to add my custom methods but the original DB interface doesn't throw a DatabaseException. I am only allowed to throw a
DuplicateKeyException
or a RecordNotFoundException (that extend the DatabaseException).
So if a
RemoteException
happens I can't rethrow a DatabaseException because is a more general class and is not declared in Oracle's interface. The other alternative was to rethrow one of the allowed exceptions but it would not make sense to rethrow a RecordNotFoundException for example if I get a
RemoteException
.
Roel De Nijs
Bartender
Joined: Jul 19, 2004
Posts: 6293
22
I like...
posted
Jul 13, 2013 03:38:18
0
Pfew, just read the whole thread
What K. Tsang obviously missed (I guess) in your explanation is that you opted for a thick client, so you have to stick with the provided interface (and that's why DBProxy implements DB). He (and me too by the way) opted for a thin client approach. So we created a business service interface (with search and book methods) and signature of the methods were completely up to us to decide. So the
RemoteException
was not a problem, throwing a checked DatabaseException from these methods also not a problem.
Regarding Andrew's book he was very lucky with the required to implement interface he got (from himself
): all the methods throw an
IOException
. So handling the
RemoteException
isn't a problem, because it's a subclass from
IOException
. And I'm pretty sure that's done by purpose, otherwise someone could copy/paste his source code, alter some variable names, submit and pass this certification. So now you (as a reader and potential certified
java
developer) have to do quite a lot of thinking. I think Andrew did a great job in writing a book that covers all aspects of this certification, but you can only use the concepts described in the book, you can't copy/paste the code from the book for your own assignment. I guess that was the very tricky part of writing this book.
I think your problem isn't a really big issue and can be easily solved. I would simply add a javadoc comment to the
SubcontractorServicesImpl
class (not the interface). Something like: "Important note: This class can be used to perform both local and network calls. When a network call fails a NetworkException will be thrown, so don't forget to handle it appropriately!". Any other programmer has to read and use the API correctly when developing some new features or changing existing ones. And in your choices.txt you simply add an explanation why you introduced this NetworkException, why it must be a
RuntimeException
(because you can't change the required interface, it's a violation of a must requirement) and you are completely ready for submission!
Good luck!
PS. Pfew, this was a long reply too
SCJA
, SCJP (
1.4
|
5.0
|
6.0
),
SCJD
OCAJP 7
Cesar Cardozo
Greenhorn
Joined: Jun 30, 2013
Posts: 14
posted
Jul 13, 2013 10:29:17
0
Well, ..... done!!! I needed your approval. Yes I have a SubcontractorServices interface and a SubcontractorServicesImpl that is the implementation class. I hope that someone else that read this thread doesn't get confused when I said that SubcontractorServices was a class.
Thanks again K. Tsang and Roel for your help!! (Next friday is my deadline, so just one more week ..... just one more week....
)
I agree. Here's the link:
subject: SubcontractorServices implementation in thick client.
Similar Threads
Implementaion of the interface provided by Sun to handle local and remote connections
Stand alone criteria [B&S]
My design...getting cloudier
RMI implementation
how do I return a DBAccess interface back to client?
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
JForum
|
Paul Wheaton | http://www.coderanch.com/t/615694/java-developer-SCJD/certification/SubcontractorServices-implementation-thick-client | CC-MAIN-2015-14 | en | refinedweb |
If \(G\) is a Lie group and \(H\) is a subgroup, one often needs to know how representations of \(G\) restrict to \(H\). Irreducibles usually do not restrict to irreducibles. In some cases the restriction is regular and predictable, in other cases it is chaotic. In some cases it follows a rule that can be described combinatorially, but the combinatorial description is subtle. The description of how irreducibles decompose into irreducibles is called a branching rule.
References for this topic:
Sage can compute how a character of \(G\) restricts to \(H\). It does so not by memorizing a combinatorial rule, but by computing the character and restricting the character to a maximal torus of \(H\). What Sage has memorized (in a series of built-in encoded rules) are the various embeddings of maximal tori of maximal subgroups of \(G\). The maximal subgroups of Lie groups were determined in [Dynkin1952]. This approach to computing branching rules has a limitation: the character must fit into memory and be computable by Sage’s internal code in real time.
It is sufficient to consider the case where \(H\) is a maximal subgroup of \(G\), since if this is known then one may branch down successively through a series of subgroups, each maximal in its predecessors. A problem is therefore to understand the maximal subgroups in a Lie group, and to give branching rules for each, and a goal of this tutorial is to explain the embeddings of maximal subgroups.
Sage has a class BranchingRule for branching rules. The function branching_rule returns elements of this class. For example, the natural embedding of \(Sp(4)\) into \(SL(4)\) corresponds to the branching rule that we may create as follows:
sage: b=branching_rule("A3","C2",rule="symmetric"); b symmetric branching rule A3 => C2
The name “symmetric” of this branching rule will be explained further later, but it means that \(Sp(4)\) is the fixed subgroup of an involution of \(Sl(4)\). Here A3 and C2 are the Cartan types of the groups \(G=SL(4)\) and \(H=Sp(4)\).
Now we may see how representations of \(SL(4)\) decompose into irreducibles when they are restricted to \(Sp(4)\):
sage: A3=WeylCharacterRing("A3",style="coroots") sage: chi=A3(1,0,1); chi.degree() 15 sage: C2=WeylCharacterRing("C2",style="coroots") sage: chi.branch(C2,rule=b) C2(0,1) + C2(2,0)
Alternatively, we may pass chi to b as an argument of its branch method, which gives the same result:
sage: b.branch(chi) C2(0,1) + C2(2,0)
It is believed that the built-in branching rules of Sage are sufficient to handle all maximal subgroups and this is certainly the case when the rank if less than or equal to 8.
However, if you want to branch to a subgroup that is not maximal you may not find a built-in branching rule. We may compose branching rules to build up embeddings. For example, here are two different embeddings of \(Sp(4)\) with Cartan type C2 in \(Sp(8)\), with Cartan type C4. One embedding factors through \(Sp(4)\times Sp(4)\), while the other factors through \(SL(4)\). To check that the embeddings are not conjugate, we branch a (randomly chosen) representation. Observe that we do not have to build the intermediate Weyl character rings.
sage: C4=WeylCharacterRing("C4",style="coroots") sage: b1=branching_rule("C4","A3","levi")*branching_rule("A3","C2","symmetric"); b1 composite branching rule C4 => (levi) A3 => (symmetric) C2 sage: b2=branching_rule("C4","C2xC2","orthogonal_sum")*branching_rule("C2xC2","C2","proj1"); b2 composite branching rule C4 => (orthogonal_sum) C2xC2 => (proj1) C2 sage: C2=WeylCharacterRing("C2",style="coroots") sage: C4=WeylCharacterRing("C4",style="coroots") sage: [C4(2,0,0,1).branch(C2, rule=br) for br in [b1,b2]] [4*C2(0,0) + 7*C2(0,1) + 15*C2(2,0) + 7*C2(0,2) + 11*C2(2,1) + C2(0,3) + 6*C2(4,0) + 3*C2(2,2), 10*C2(0,0) + 40*C2(1,0) + 50*C2(0,1) + 16*C2(2,0) + 20*C2(1,1) + 4*C2(3,0) + 5*C2(2,1)]
The essence of the branching rule is a function from the weight lattice of \(G\) to the weight lattice of the subgroup \(H\), usually implemented as a function on the ambient vector spaces. Indeed, we may conjugate the embedding so that a Cartan subalgebra \(U\) of \(H\) is contained in a Cartan subalgebra \(T\) of \(G\). Since the ambient vector space of the weight lattice of \(G\) is \(\hbox{Lie}(T)^*\), we get map \(\hbox{Lie}(T)^*\to\hbox{Lie}(U)^*\), and this must be implemented as a function. For speed, the function usually just returns a list, which can be coerced into \(\hbox{Lie}(U)^*\).
sage: b = branching_rule("A3","C2","symmetric") sage: for r in RootSystem("A3").ambient_space().simple_roots(): print r, b(r) (1, -1, 0, 0) [1, -1] (0, 1, -1, 0) [0, 2] (0, 0, 1, -1) [1, -1]
We could conjugate this map by an element of the Weyl group of \(G\), and the resulting map would give the same decomposition of representations of \(G\) into irreducibles of \(H\). However it is a good idea to choose the map so that it takes dominant weights to dominant weights, and, insofar as possible, simple roots of \(G\) into simple roots of \(H\). This includes sometimes the affine root \(\alpha_0\) of \(G\), which we recall is the negative of the highest root.
The branching rule has a describe() method that shows how the roots (including the affine root) restrict. This is a useful way of understanding the embedding. You might want to try it with various branching rules of different kinds, "extended", "symmetric", "levi" etc.
sage: b.describe() 0 O-------+ | | | | O---O---O 1 2 3 A3~ root restrictions A3 => C2: O=<=O 1 2 C2 1 => 1 2 => 2 3 => 1 For more detailed information use verbose=True
The extended Dynkin diagram of \(G\) and the ordinary Dynkin diagram of \(H\) are shown for reference, and 3 => 1 means that the third simple root \(\alpha_3\) of \(G\) restricts to the first simple root of \(H\). In this example, the affine root does not restrict to a simple roots, so it is omitted from the list of restrictions. If you add the parameter verbose=true you will be shown the restriction of all simple roots and the affine root, and also the restrictions of the fundamental weights (in coroot notation).
Sage has a database of maximal subgroups for every simple Cartan type of rank \(\le 8\). You may access this with the maximal_subgroups method of the Weyl character ring:
sage: E7=WeylCharacterRing("E7",style="coroots") sage: E7.maximal_subgroups() A7:branching_rule("E7","A7","extended") E6:branching_rule("E7","E6","levi") A2:branching_rule("E7","A2","miscellaneous") A1:branching_rule("E7","A1","iii") A1:branching_rule("E7","A1","iv") A1xF4:branching_rule("E7","A1xF4","miscellaneous") G2xC3:branching_rule("E7","G2xC3","miscellaneous") A1xG2:branching_rule("E7","A1xG2","miscellaneous") A1xA1:branching_rule("E7","A1xA1","miscellaneous") A1xD6:branching_rule("E7","A1xD6","extended") A5xA2:branching_rule("E7","A5xA2","extended")
It should be understood that there are other ways of embedding \(A_2=\hbox{SL}(3)\) into the Lie group \(E_7\), but only one way as a maximal subgroup. On the other hand, there are but only one way to embed it as a maximal subgroup. The embedding will be explained below. You may obtain the branching rule as follows, and use it to determine the decomposition of irreducible representations of \(E_7\) as follows:
sage: b = E7.maximal_subgroup("A2"); b miscellaneous branching rule E7 => A2 sage: [E7,A2]=[WeylCharacterRing(x,style="coroots") for x in ["E7","A2"]] sage: E7(1,0,0,0,0,0,0).branch(A2,rule=b) A2(1,1) + A2(4,4)
This gives the same branching rule as just pasting line beginning to the right of the colon onto the command line:
sage:branching_rule("E7","A2","miscellaneous") miscellaneous branching rule E7 => A2
There are two distict embeddings of \(A_1=\hbox{SL}(2)\) into \(E_7\) as maximal subgroups, so the maximal_subgroup method will return a list of rules:
sage: WeylCharacterRing("E7").maximal_subgroup("A1") [iii branching rule E7 => A1, iv branching rule E7 => A1]
The list of maximal subgroups returned by the maximal_subgroups method for irreducible Cartan types of rank up to 8 is believed to be complete up to outer automorphisms. You may want a list that is complete up to inner automorphisms. For example, \(E_6\) has a nontrivial Dynkin diagram automorphism so it has an outer automorphism that is not inner:
sage: [E6,A2xG2]=[WeylCharacterRing(x,style="coroots") for x in ["E6","A2xG2"]] sage: b=E6.maximal_subgroup("A2xG2"); b miscellaneous branching rule E6 => A2xG2 sage: E6(1,0,0,0,0,0).branch(A2xG2,rule=b) A2xG2(0,1,1,0) + A2xG2(2,0,0,0) sage: E6(0,0,0,0,0,1).branch(A2xG2,rule=b) A2xG2(1,0,1,0) + A2xG2(0,2,0,0)
Since as we see the two 27 dimensional irreducibles (which are interchanged by the outer automorphism) have different branching, the \(A_2\times G_2\) subgroup is changed to a different one by the outer automorphism. To obtain the second branching rule, we compose the given one with this automorphism:
sage: b1=branching_rule("E6","E6","automorphic")*b; b1 composite branching rule E6 => (automorphic) E6 => (miscellaneous) A2xG2
A Levi subgroup may or may not be maximal. They are easily classified. If one starts with a Dynkin diagram for \(G\) and removes a single node, one obtains a smaller Dynkin diagram, which is the Dynkin diagram of a smaller subgroup \(H\).
For example, here is the A3 Dynkin diagram:
sage: A3 = WeylCharacterRing("A3") sage: A3.dynkin_diagram() O---O---O 1 2 3 A3
We see that we may remove the node 3 and obtain \(A_2\), or the node 2 and obtain \(A_1 \times A_1\). These correspond to the Levi subgroups \(GL(3)\) and \(GL(2) \times GL(2)\) of \(GL(4)\).
Let us construct the irreducible representations of \(GL(4)\) and branch them down to these down to \(GL(3)\) and \(GL(2) \times GL(2)\):
sage: reps = [A3(v) for v in A3.fundamental_weights()]; reps [A3(1,0,0,0), A3(1,1,0,0), A3(1,1,1,0)] sage: A2 = WeylCharacterRing("A2") sage: A1xA1 = WeylCharacterRing("A1xA1") sage: [pi.branch(A2, rule="levi") for pi in reps] [A2(0,0,0) + A2(1,0,0), A2(1,0,0) + A2(1,1,0), A2(1,1,0) + A2(1,1,1)] sage: [pi.branch(A1xA1, rule="levi") for pi in reps] [A1xA1(1,0,0,0) + A1xA1(0,0,1,0), A1xA1(1,1,0,0) + A1xA1(1,0,1,0) + A1xA1(0,0,1,1), A1xA1(1,1,1,0) + A1xA1(1,0,1,1)]
Let us redo this calculation in coroot notation. As we have explained, coroot notation does not distinguish between representations of \(GL(4)\) that have the same restriction to \(SL(4)\), so in effect we are now working with the groups \(SL(4)\) and its Levi subgroups \(SL(3)\) and \(SL(2) \times SL(2)\), which is the derived group of its Levi subgroup:
sage: A3 = WeylCharacterRing("A3", style="coroots") sage: reps = [A3(v) for v in A3.fundamental_weights()]; reps [A3(1,0,0), A3(0,1,0), A3(0,0,1)] sage: A2 = WeylCharacterRing("A2", style="coroots") sage: A1xA1 = WeylCharacterRing("A1xA1", style="coroots") sage: [pi.branch(A2, rule="levi") for pi in reps] [A2(0,0) + A2(1,0), A2(0,1) + A2(1,0), A2(0,0) + A2(0,1)] sage: [pi.branch(A1xA1, rule="levi") for pi in reps] [A1xA1(1,0) + A1xA1(0,1), 2*A1xA1(0,0) + A1xA1(1,1), A1xA1(1,0) + A1xA1(0,1)]
Now we may observe a distinction difference in branching from
versus
Consider the representation A3(0,1,0), which is the six dimensional exterior square. In the coroot notation, the restriction contained two copies of the trivial representation, 2*A1xA1(0,0). The other way, we had instead three distinct representations in the restriction, namely A1xA1(1,1,0,0) and A1xA1(0,0,1,1), that is, \(\det \otimes 1\) and \(1 \otimes \det\).
The Levi subgroup A1xA1 is actually not maximal. Indeed, we may factor the embedding:
Therfore there are branching rules A3 -> C2 and C2 -> A2, and we could accomplish the branching in two steps, thus:
sage: A3 = WeylCharacterRing("A3", style="coroots") sage: C2 = WeylCharacterRing("C2", style="coroots") sage: B2 = WeylCharacterRing("B2", style="coroots") sage: D2 = WeylCharacterRing("D2", style="coroots") sage: A1xA1 = WeylCharacterRing("A1xA1", style="coroots") sage: reps = [A3(fw) for fw in A3.fundamental_weights()] sage: [pi.branch(C2, rule="symmetric").branch(B2, rule="isomorphic"). \ branch(D2, rule="extended").branch(A1xA1, rule="isomorphic") for pi in reps] [A1xA1(1,0) + A1xA1(0,1), 2*A1xA1(0,0) + A1xA1(1,1), A1xA1(1,0) + A1xA1(0,1)]
As you can see, we’ve redone the branching rather circuitously this way, making use of the branching rules A3 -> C2 and B2 -> D2, and two accidental isomorphisms C2 = B2 and D2 = A1xA1. It is much easier to go in one step using rule="levi", but reassuring that we get the same answer!
It is also true that if we remove one node from the extended Dynkin diagram that we obtain the Dynkin diagram of a subgroup. For example:
sage: G2 = WeylCharacterRing("G2", style="coroots") sage: G2.extended_dynkin_diagram() 3 O=<=O---O 1 2 0 G2~
Observe that by removing the 1 node that we obtain an \(A_2\) Dynkin diagram. Therefore the exceptional group \(G_2\) contains a copy of \(SL(3)\). We branch the two representations of \(G_2\) corresponding to the fundamental weights to this copy of \(A_2\):
sage: G2 = WeylCharacterRing("G2", style="coroots") sage: A2 = WeylCharacterRing("A2", style="coroots") sage: [G2(f).degree() for f in G2.fundamental_weights()] [7, 14] sage: [G2(f).branch(A2, rule="extended") for f in G2.fundamental_weights()] [A2(0,0) + A2(0,1) + A2(1,0), A2(0,1) + A2(1,0) + A2(1,1)]
The two representations of \(G_2\), of degrees 7 and 14 respectively, are the action on the octonions of trace zero and the adjoint representation.
For embeddings of this type, the rank of the subgroup \(H\) is the same as the rank of \(G\). This is in contrast with embeddings of Levi type, where \(H\) has rank one less than \(G\).
The exceptional group \(G_2\) has two Levi subgroups of type \(A_1\). Neither is maximal, as we can see from the extended Dynkin diagram: the subgroups \(A_1\times A_1\) and \(A_2\) are maximal and each contains a Levi subgroup. (Actually \(A_1\times A_1\) contains a conjugate of both.) Only the Levi subgroup containing the short root is implemented as an instance of rule="levi". To obtain the other, use the rule:
sage: branching_rule("G2","A2","extended")*branching_rule("A2","A1","levi") composite branching rule G2 => (extended) A2 => (levi) A1
which branches to the \(A_1\) Levi subgroup containing a long root.
If \(G = \hbox{SO}(n)\) then \(G\) has a subgroup \(\hbox{SO}(n-1)\). Depending on whether \(n\) is even or odd, we thus have branching rules ['D',r] to ['B',r-1] or ['B',r] to ['D',r]. These are handled as follows:
sage: branching_rule("B4","D4",rule="extended") extended branching rule B4 => D4 sage: branching_rule("D4","B3",rule="symmetric") symmetric branching rule D4 => B3
If \(G = \hbox{SO}(r+s)\) then \(G\) has a subgroup \(\hbox{SO}(r) \times \hbox{SO}(s)\). This lifts to an embedding of the universal covering groups
Sometimes this embedding is of extended type, and sometimes it is not. It is of extended type unless \(r\) and \(s\) are both odd. If it is of extended type then you may use rule="extended". In any case you may use rule="orthogonal_sum". The name refer to the origin of the embedding \(SO(r) \times SO(s) \to SO(r+s)\) from the decomposition of the underlying quadratic space as a direct sum of two orthogonal subspaces.
There are four cases depending on the parity of \(r\) and \(s\). For example, if \(r = 2k\) and \(s = 2l\) we have an embedding:
['D',k] x ['D',l] --> ['D',k+l]
This is of extended type. Thus consider the embedding D4xD3 -> D7. Here is the extended Dynkin diagram:
0 O O 7 | | | | O---O---O---O---O---O 1 2 3 4 5 6
Removing the 4 vertex results in a disconnected Dynkin diagram:
0 O O 7 | | | | O---O---O O---O 1 2 3 5 6
This is D4xD3. Therefore use the “extended” branching rule:
sage: D7 = WeylCharacterRing("D7", style="coroots") sage: D4xD3 = WeylCharacterRing("D4xD3", style="coroots") sage: spin = D7(D7.fundamental_weights()[7]); spin D7(0,0,0,0,0,0,1) sage: spin.branch(D4xD3, rule="extended") D4xD3(0,0,1,0,0,1,0) + D4xD3(0,0,0,1,0,0,1)
But we could equally well use the “orthogonal_sum” rule:
sage: spin.branch(D4xD3, rule="orthogonal_sum") D4xD3(0,0,1,0,0,1,0) + D4xD3(0,0,0,1,0,0,1)
Similarly we have embeddings:
['D',k] x ['B',l] --> ['B',k+l]
These are also of extended type. For example consider the embedding of D3xB2 -> B5. Here is the B5 extended Dynkin diagram:
O 0 | | O---O---O---O=>=O 1 2 3 4 5
Removing the 3 node gives:
O 0 | O---O O=>=O 1 2 4 5
and this is the Dynkin diagram or D3xB2. For such branchings we again use either rule="extended" or rule="orthogonal_sum".
Finally, there is an embedding
['B',k] x ['B',l] --> ['D',k+l+1]
This is not of extended type, so you may not use rule="extended". You must use rule="orthogonal_sum":
sage: D5 = WeylCharacterRing("D5",style="coroots") sage: B2xB2 = WeylCharacterRing("B2xB2",style="coroots") sage: [D5(v).branch(B2xB2,rule="orthogonal_sum") for v in D5.fundamental_weights()] [B2xB2(1,0,0,0) + B2xB2(0,0,1,0), B2xB2(0,2,0,0) + B2xB2(1,0,1,0) + B2xB2(0,0,0,2), B2xB2(0,2,0,0) + B2xB2(0,2,1,0) + B2xB2(1,0,0,2) + B2xB2(0,0,0,2), B2xB2(0,1,0,1), B2xB2(0,1,0,1)]
Not all Levi subgroups are maximal. Recall that the Dynkin-diagram of a Levi subgroup \(H\) of \(G\) is obtained by removing a node from the Dynkin diagram of \(G\). Removing the same node from the extended Dynkin diagram of \(G\) results in the Dynkin diagram of a subgroup of \(G\) that is strictly larger than \(H\). However this subgroup may or may not be proper, so the Levi subgroup may or may not be maximal.
If the Levi subgroup is not maximal, the branching rule may or may not be implemented in Sage. However if it is not implemented, it may be constructed as a composition of two branching rules.
For example, prior to Sage-6.1 branching_rule("E6","A5","levi") returned a not-implemented error and the advice to branch to A5xA1. And we can see from the extended Dynkin diagram of \(E_6\) that indeed \(A_5\) is not a maximal subgroup, since removing node 2 from the extended Dynkin diagram (see below) gives A5xA1. To construct the branching rule to \(A_5\) we may proceed as follows:
sage: b = branching_rule("E6","A5xA1","extended")*branching_rule("A5xA1","A5","proj1"); b composite branching rule E6 => (extended) A5xA1 => (proj1) A5 sage: E6=WeylCharacterRing("E6",style="coroots") sage: A5=WeylCharacterRing("A5",style="coroots") sage: E6(0,1,0,0,0,0).branch(A5,rule=b) 3*A5(0,0,0,0,0) + 2*A5(0,0,1,0,0) + A5(1,0,0,0,1) sage: b.describe() O 0 | | O 2 | | O---O---O---O---O 1 3 4 5 6 E6~ root restrictions E6 => A5: O---O---O---O---O 1 2 3 4 5 A5 0 => (zero) 1 => 1 3 => 2 4 => 3 5 => 4 6 => 5 For more detailed information use verbose=True
Note that it is not necessary to construct the Weyl character ring for the intermediate group A5xA1.
This last example illustrates another common problem: how to extract one component from a reducible root system. We used the rule "proj1" to extract the first component. We could similarly use "proj2" to get the second, or more generally any combination of components:
sage: branching_rule("A2xB2xG2","A2xG2","proj13") proj13 branching rule A2xB2xG2 => A2xG2
If \(G\) admits an outer automorphism (usually of order two) then we may try to find the branching rule to the fixed subgroup \(H\). It can be arranged that this automorphism maps the maximal torus \(T\) to itself and that a maximal torus \(U\) of \(H\) is contained in \(T\).
Suppose that the Dynkin diagram of \(G\) admits an automorphism. Then \(G\) itself admits an outer automorphism. The Dynkin diagram of the group \(H\) of invariants may be obtained by “folding” the Dynkin diagram of \(G\) along the automorphism. The exception is the branching rule \(GL(2r) \to SO(2r)\).
Here are the branching rules that can be obtained using rule="symmetric".
If \(G_1\) and \(G_2\) are Lie groups, and we have representations \(\pi_1: G_1 \to GL(n)\) and \(\pi_2: G_2 \to GL(m)\) then the tensor product is a representation of \(G_1 \times G_2\). It has its image in \(GL(nm)\) but sometimes this is conjugate to a subgroup of \(SO(nm)\) or \(Sp(nm)\). In particular we have the following cases.
These branching rules are obtained using rule="tensor".
The \(k\)-th symmetric and exterior power homomorphisms map \(GL(n) \to GL \left({n+k-1 \choose k} \right)\) and \(GL \left({n \choose k} \right)\). The corresponding branching rules are not implemented but a special case is. The \(k\)-th symmetric power homomorphism \(SL(2) \to GL(k+1)\) has its image inside of \(SO(2r+1)\) if \(k = 2r\) and inside of \(Sp(2r)\) if \(k = 2r-1\). Hence there are branching rules:
['B',r] => A1 ['C',r] => A1
and these may be obtained using rule="symmetric_power".
The above branching rules are sufficient for most cases, but a few fall between the cracks. Mostly these involve maximal subgroups of fairly small rank.
The rule rule="plethysm" is a powerful rule that includes any branching rule from types \(A\), \(B\), \(C\) or \(D\) as a special case. Thus it could be used in place of the above rules and would give the same results. However, it is most useful when branching from \(G\) to a maximal subgroup \(H\) such that \(rank(H) < rank(G)-1\).
We consider a homomorphism \(H \to G\) where \(G\) is one of \(SL(r+1)\), \(SO(2r+1)\), \(Sp(2r)\) or \(SO(2r)\). The function branching_rule_from_plethysm produces the corresponding branching rule. The main ingredient is the character \(\chi\) of the representation of \(H\) that is the homomorphism to \(GL(r+1)\), \(GL(2r+1)\) or \(GL(2r)\).
Let us consider the symmetric fifth power representation of \(SL(2)\). This is implemented above by rule="symmetric_power", but suppose we want to use rule="plethysm". First we construct the homomorphism by invoking its character, to be called chi:
sage: A1 = WeylCharacterRing("A1", style="coroots") sage: chi = A1([5]) sage: chi.degree() 6 sage: chi.frobenius_schur_indicator() -1
This confirms that the character has degree 6 and is symplectic, so it corresponds to a homomorphism \(SL(2) \to Sp(6)\), and there is a corresponding branching rule C3 -> A1:
sage: A1 = WeylCharacterRing("A1", style="coroots") sage: C3 = WeylCharacterRing("C3", style="coroots") sage: chi = A1([5]) sage: sym5rule = branching_rule_from_plethysm(chi, "C3") sage: [C3(hwv).branch(A1, rule=sym5rule) for hwv in C3.fundamental_weights()] [A1(5), A1(4) + A1(8), A1(3) + A1(9)]
This is identical to the results we would obtain using rule="symmetric_power":
sage: A1 = WeylCharacterRing("A1", style="coroots") sage: C3 = WeylCharacterRing("C3", style="coroots") sage: [C3(v).branch(A1, rule="symmetric_power") for v in C3.fundamental_weights()] [A1(5), A1(4) + A1(8), A1(3) + A1(9)]
But the next example of plethysm gives a branching rule not available by other methods:
sage: G2 = WeylCharacterRing("G2", style="coroots") sage: D7 = WeylCharacterRing("D7", style="coroots") sage: ad = G2.adjoint_representation(); ad.degree() 14 sage: ad.frobenius_schur_indicator() 1 sage: for r in D7.fundamental_weights(): # long time (1.29s) ....: print D7(r).branch(G2, rule=branching_rule_from_plethysm(ad, "D7")) ....: G2(0,1) G2(0,1) + G2(3,0) G2(0,0) + G2(2,0) + G2(3,0) + G2(0,2) + G2(4,0) G2(0,1) + G2(2,0) + G2(1,1) + G2(0,2) + G2(2,1) + G2(4,0) + G2(3,1) G2(1,0) + G2(0,1) + G2(1,1) + 2*G2(3,0) + 2*G2(2,1) + G2(1,2) + G2(3,1) + G2(5,0) + G2(0,3) G2(1,1) G2(1,1)
In this example, \(ad\) is the 14-dimensional adjoint representation of the exceptional group \(G_2\). Since the Frobenius-Schur indicator is 1, the representation is orthogonal, and factors through \(SO(14)\), that is, \(D7\).
We do not actually have to create the character (or for that matter its ambient WeylCharacterRing) in order to create the branching rule:
sage: branching_rule("D4","A2.adjoint_representation()","plethysm") plethysm (along A2(1,1)) branching rule D4 => A2
The adjoint representation of any semisimple Lie group is orthogonal, so we do not need to compute the Frobenius-Schur indicator.
Use rule="miscellaneous" for the following rules. Every maximal subgroup \(H\) of an exceptional group \(G\) are either among these, or the five \(A_1\) subgroups described in the next section, or (if \(G\) and \(H\) have the same rank) is available using rule="extended".
\[\begin{split}\begin{aligned} B_3 & \to G_2, \\ E_6 & \to A_2, \\ E_6 & \to G_2, \\ F_4 & \to G_2 \times A_1, \\ E_6 & \to G_2 \times A_2, \\ E_7 & \to G_2 \times C_3, \\ E_7 & \to F_4 \times A_1, \\ E_7 & \to A_1 \times A_1, \\ E_7 & \to G_2 \times A_1, \\ E_7 & \to A_2 \\ E_8 & \to G_2 \times F_4. \\ E_8 & \to A_2 \times A_1. \\ E_8 & \to B_2 \end{aligned}\end{split}\]
The first rule corresponds to the embedding of \(G_2\) in \(\hbox{SO}(7)\) in its action on the trace zero octonions. The two branching rules from \(E_6\) to \(G_2\) or \(A_2\) are described in [Testerman1989]. We caution the reader that Theorem G.2 of that paper, proved there in positive characteristic is false over the complex numbers. On the other hand, the assumption of characteristic \(p\) is not important for Theorems G.1 and A.1, which describe the torus embeddings, hence contain enough information to compute the branching rule. There are other ways of embedding \(G_2\) or \(A_2\) into \(E_6\). These may embeddings be characterized by the condition that the two 27-dimensional representations of \(E_6\) restrict irreducibly to \(G_2\) or \(A_2\). Their images are maximal subgroups.
The remaining rules come about as follows. Let \(G\) be \(F_4\), \(E_6\), \(E_7\) or \(E_8\), and let \(H\) be \(G_2\), or else (if \(G=E_7\)) \(F_4\). We embed \(H\) into \(G\) in the most obvious way; that is, in the chain of subgroups
\[G_2\subset F_4\subset E_6 \subset E_7 \subset E_8\]
Then the centralizer of \(H\) is \(A_1\), \(A_2\), \(C_3\), \(F_4\) (if \(H=G_2\)) or \(A_1\) (if \(G=E_7\) and \(H=F_4\)). This gives us five of the cases. Regarding the branching rule \(E_6 \to G_2 \times A_2\), Rubenthaler [Rubenthaler2008] describes the embedding and applies it in an interesting way.
The embedding of \(A_1\times A_1\) into \(E_7\) is as follows. Deleting the 5 node of the \(E_7\) Dynkin diagram gives the Dynkin diagram of \(A_4\times A_2\), so this is a Levi subgroup. We embed \(\hbox{SL}(2)\) into this Levi subgroup via the representation \([4]\otimes[2]\). This embeds the first copy of \(A_1\). The other \(A_1\) is the connected centralizer. See [Seitz1991], particularly the proof of (3.12).
The embedding if \(G_2\times A_1\) into \(E_7\) is as follows. Deleting the 2 node of the \(E_7\) Dynkin diagram gives the \(A_6\) Dynkin diagram, which is the Levi subgroup \(\hbox{SL}(7)\). We embed \(G_2\) into \(\hbox{SL}(7)\) via the irreducible seven-dimensional representation of \(G_2\). The \(A_1\) is the centralizer.
The embedding if \(A_2\times A_1\) into \(E_8\) is as follows. Deleting the 2 node of the \(E_8\) Dynkin diagram gives the \(A_7\) Dynkin diagram, which is the Levi subgroup \(\hbox{SL}(8)\). We embed \(A_2\) into \(\hbox{SL}(8)\) via the irreducible eight-dimensional adjoint representation of \(\hbox{SL}(2)\). The \(A_1\) is the centralizer.
The embedding \(A_2\) into \(E_7\) is proved in [Seitz1991] (5.8). In particular, he computes the embedding of the \(\hbox{SL}(3)\) torus in the \(E_7\) torus, which is what is needed to implement the branching rule. The embedding of \(B_2\) into \(E_8\) is also constructed in [Seitz1991] (6.7). The embedding of the \(B_2\) Cartan subalgebra, needed to implement the branching rule, is easily deduced from (10) on page 111.
There are seven embeddings of \(SL(2)\) into an exceptional group as a maximal subgroup: one each for \(G_2\) and \(F_4\), two nonconjugate embeddings for \(E_7\) and three for \(E_8\) These are constructed in [Testerman1992]. Create the corresponding branching rules as follows. The names of the rules are roman numerals referring to the seven cases of Testerman’s Theorem 1:
sage: branching_rule("G2","A1","i") i branching rule G2 => A1 sage: branching_rule("F4","A1","ii") ii branching rule F4 => A1 sage: branching_rule("E7","A1","iii") iii branching rule E7 => A1 sage: branching_rule("E7","A1","iv") iv branching rule E7 => A1 sage: branching_rule("E8","A1","v") v branching rule E8 => A1 sage: branching_rule("E8","A1","vi") vi branching rule E8 => A1 sage: branching_rule("E8","A1","vii") vii branching rule E8 => A1
The embeddings are characterized by the root restrictions in their branching rules: usually a simple root of the ambient group \(G\) restricts to the unique simple root of \(A_1\), except for root \(\alpha_4\) for rules iv, vi and vii, and the root \(\alpha_6\) for root vii; this is essentially the way Testerman characterizes the embeddings, and this information may be obtained from Sage by employing the describe() method of the branching rule. Thus:
sage: branching_rule("E8","A1","vii").describe() O 2 | | O---O---O---O---O---O---O---O 1 3 4 5 6 7 8 0 E8~ root restrictions E8 => A1: O 1 A1 1 => 1 2 => 1 3 => 1 4 => (zero) 5 => 1 6 => (zero) 7 => 1 8 => 1 For more detailed information use verbose=True
Sage has many built-in branching rules. Indeed, at least up to rank eight (including all the exceptional groups) branching rules to all maximal subgroups are implemented as built in rules, except for a few obtainable using branching_rule_from_plethysm. This means that all the rules in [McKayPatera1981] are available in Sage.
Still in this section we are including instructions for coding a rule by hand. As we have already explained, the branching rule is a function from the weight lattice of G to the weight lattice of H, and if you supply this you can write your own branching rules.
As an example, let us consider how to implement the branching rule A3 -> C2. Here H = C2 = Sp(4) embedded as a subgroup in A3 = GL(4). The Cartan subalgebra \(\hbox{Lie}(U)\) consists of diagonal matrices with eigenvalues u1, u2, -u2, -u1. Then C2.space() is the two dimensional vector spaces consisting of the linear functionals u1 and u2 on U. On the other hand \(Lie(T) = \mathbf{R}^4\). A convenient way to see the restriction is to think of it as the adjoint of the map [u1,u2] -> [u1,u2,-u2,-u1], that is, [x0,x1,x2,x3] -> [x0-x3,x1-x2]. Hence we may encode the rule:
def brule(x): return [x[0]-x[3], x[1]-x[2]]
or simply:
brule = lambda x: [x[0]-x[3], x[1]-x[2]]
Let us check that this agrees with the built-in rule:
sage: A3 = WeylCharacterRing(['A', 3]) sage: C2 = WeylCharacterRing(['C', 2]) sage: brule = lambda x: [x[0]-x[3], x[1]-x[2]] sage: A3(1,1,0,0).branch(C2, rule=brule) C2(0,0) + C2(1,1) sage: A3(1,1,0,0).branch(C2, rule="symmetric") C2(0,0) + C2(1,1)
Although this works, it is better to make the rule into an element of the BranchingRule class, as follows.
sage: brule = BranchingRule("A3","C2",lambda x : [x[0]-x[3], x[1]-x[2]],"custom") sage: A3(1,1,0,0).branch(C2, rule=brule) C2(0,0) + C2(1,1)
The case where \(G=H\) can be treated as a special case of a branching rule. In most cases if \(G\) has a nontrivial outer automorphism, it has order two, corresponding to the symmetry of the Dynkin diagram. Such an involution exists in the cases \(A_r\), \(D_r\), \(E_6\).
So the automorphism acts on the representations of \(G\), and its effect may be computed using the branching rule code:
sage: A4 = WeylCharacterRing("A4",style="coroots") sage: A4(1,0,1,0).degree() 45 sage: A4(0,1,0,1).degree() 45 sage: A4(1,0,1,0).branch(A4,rule="automorphic") A4(0,1,0,1)
In the special case where G=D4, the Dynkin diagram has extra symmetries, and these correspond to outer automorphisms of the group. These are implemented as the "triality" branching rule:
sage: branching_rule("D4","D4","triality").describe() O 4 | | O---O---O 1 |2 3 | O 0 D4~ root restrictions D4 => D4: O 4 | | O---O---O 1 2 3 D4 1 => 3 2 => 2 3 => 4 4 => 1 For more detailed information use verbose=True
Triality his is not an automorphisms of \(SO(8)\), but of its double cover \(spin(8)\). Note that \(spin(8)\) has three representations of degree 8, namely the standard representation of \(SO(8)\) and the two eight-dimensional spin representations. These are permuted by triality:
sage: D4=WeylCharacterRing("D4",style="coroots") sage: D4(0,0,0,1).branch(D4,rule="triality") D4(1,0,0,0) sage: D4(0,0,0,1).branch(D4,rule="triality").branch(D4,rule="triality") D4(0,0,1,0) sage: D4(0,0,0,1).branch(D4,rule="triality").branch(D4,rule="triality").branch(D4,rule="triality") D4(0,0,0,1)
By contrast, rule="automorphic" simply interchanges the two spin representations, as it always does in type \(D\):
sage: D4(0,0,0,1).branch(D4,rule="automorphic") D4(0,0,1,0) sage: D4(0,0,1,0).branch(D4,rule="automorphic") D4(0,0,0,1) | http://sagemath.org/doc/thematic_tutorials/lie/branching_rules.html | CC-MAIN-2015-14 | en | refinedweb |
Anupam Dev wrote:what error do you get? kingly copy paste the error you are getting...
Anupam Dev wrote:i think you should rename your WEB_INF directory to WEB-INF.
The folder where my project is ServletsFolder whose path is---
C:\Program Files\Apache Software Foundation1\Apache Tomcat 6.0.26\webapps\ServletsFolder
Myk Romo wrote:Hi,
can you post here the exact code of your servlet?
Tips:
- make sure the specified package is exist.
- and make sure the class that you've instantiate is on the package..
Vijitha Kumara wrote:Welcome to CodeRanch, J Das!
Looks like the compiler cannot find the Java class. Add a classpath entry to contain the path to the Java class "CoffeeExpert". (e.g.: javac -cp <PathToClass & servlet jar> <SourceFiles>). You may want to check our faq entry: HowToSetTheClasspath.
The folder where my project is ServletsFolder whose path is---
C:\Program Files\Apache Software Foundation1\Apache Tomcat 6.0.26\webapps\ServletsFolder
Never put your working folders inside the server instance. Use another directory in your home directory for development, then you may build and deploy to the server.
Vijitha Kumara wrote:Since you already have set the CLASSPATH to servlet-api.jar you can append the new entry while compiling the source.
javac -cp %CLASSPATH%;<PathToTheClass> <SourceFiles>
Replace the "<PathToTheClass>" with the path to your compiled POJO class. It should be to the directory where your package folder exists. (I guess I got it right in the path separator for entries in Windows, if not try ":" instead ";" to separate the entries.)
Vijitha Kumara wrote:You have to escape the spaces in the directory path. Use quotes to wrap the path and see.
Try this to compile if you need it in this way:
javac -cp %CLASSPATH%;"C:\Program Files\Apache Software Foundation1\Apache Tomcat 6.0.26\webapps\ServletsFolder\WEB-INF\classes\" "C:\Program
Files\Apache Software Foundation1\Apache Tomcat 6.0.26\webapps\ServletsFolder\WE
B-INF\classes\com\example\web\CoffeeSelect.java"
BTW, you can try what I said before also: cd to classes directory and ....
Anupam Dev wrote:@J Das
It's for sure, you have a classpath problem...
the error says it can't find the package
coffeeselect.java:2: package com.example.model does not exist
so first of all goto the web-inf/classes directory and list the contents (the java file names) and check whether in each java file you have used the proper package statements in each file.....
Anupam Dev wrote:List the contents of CoffeeExpert.java. The problem is in this file i think...
Anupam Dev wrote:ha ha got the culprit.....
you have to write
package com.example.web
Does this solve your problem???
Anupam Dev wrote:refer to this page
Bear Bibeault wrote:This has nothing to do with servlets but with learning how to compile from the command line, so it has been moved to a more appropriate location.
Anupam Dev wrote:Use this
C:\>javac -cp "C:\Program Files\Apache Software Foundation1\Apache Tomcat 6.0.26\webapps\ServletsFolder\WEB-INF\classes\" "C:\Program Files\Apache Software Foundation1\Apache Tomcat 6.0.26\webapps\ServletsFolder\WEB-INF\classes\com\example\web\CoffeeSelect.java"
Vijitha Kumara wrote:Try this:
javac -cp %CLASSPATH%;"C:\Program Files\Apache Software Foundation1\Apache T
omcat 6.0.26\webapps\ServletsFolder\WEB-INF\classes" "C:\Program Files\Apache S
oftware Foundation1\Apache Tomcat 6.0.26\webapps\ServletsFolder\WEB-INF\classes\
com\example\web\CoffeeSelect.java"
It's probably the trailing slash in -cp entry causing the issue...
J Das wrote:
Anupam Dev wrote:what error do you get? kingly copy paste the error you are getting...
this is my command screen with compilation errors >>>>
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C:\Documents and Settings\Jyotirmoy>cd C:\Program Files\Apache Software Foundati
on1\Apache Tomcat 6.0.26\webapps\ServletsFolder\WEB-INF\classes\com\example\web
C:\Program Files\Apache Software Foundation1\Apache Tomcat 6.0.26\webapps\Servle
tsFolder\WEB-INF\classes\com\example\web>javac coffeeselect.java
coffeeselect.java:2: package com.example.model does not exist
import com.example.model.*;
^
coffeeselect.java:19: cannot find symbol
symbol : class CoffeeExpert
location: class com.example.web.CoffeeSelect
CoffeeExpert ce = new CoffeeExpert();
^
coffeeselect.java:19: cannot find symbol
symbol : class CoffeeExpert
location: class com.example.web.CoffeeSelect
CoffeeExpert ce = new CoffeeExpert();
^
3 errors
as i am new to this things so i may be wrong in the compilation process (i guess)... and by the way , thanks Anupam for your quick view to my problem... please rply this to me now what should i do...
Sakthi Sivram wrote:
Try this one,
From command prompt go to the path,
C:\Program Files\Apache Software Foundation1\Apache Tomcat 6.0.26\webapps\ServletsFolder\WEB-INF\classes>
Then set classpath like below,
set CLASSPATH=%CLASSPATH%;C:\Program Files\Apache Software Foundation1\Apache Tomcat 6.0.26\webapps\Servle
tsFolder\WEB-INF\classes;
Then compile your servletcode like,
javac com/example/web/CoffeeSelect.java
The problem is "CoffeeSelect" cannot able to find the class file "CoffeeExpert" since you are compiling from "CoffeeSelect" path. Refer your code above.
Vijitha Kumara wrote:Welcome to CodeRanch, Sakthi Sivram!
The latest problem the OP facing is that the command line does not interpret the arguments to javac properly.
@J Das
At this point you can try two things.
1. Add the entry for the compiled POJO class in to the CLASSPATH environment
variable, and try compiling.
2. Go to the .../WEB-INF/classes directory and try compiling as I said before.
(Note: You can avoid most of these problems by using a seperate path for your development work.)
Vijitha Kumara wrote:(Note: You can avoid most of these problems by using a seperate path for your development work.)
Anupam Dee wrote:Try this first
make a directory in your d:/new folder (do not remove the space between new and folder)
and build the directory tree as follows
d:\new folder\com\web
d:\new folder\com\model
and then create two classes
d:\new folder\com\web\abc.java
d:\new folder\com\model\xyz.java
abc.java
----------
package com.web;
class abc
{
}
xyz.java
----------
package com.model;
import com.web.*;
class xyz
{
abc a=new abc();
}
and then compile using
c:\> javac -cp "d:\new folder" "d:\new folder\com\model\xyz.java"
does this compile on your system successfully? | http://www.coderanch.com/t/546991/java/java/Error-Servlet-compilation | CC-MAIN-2015-14 | en | refinedweb |
Patent application title: Working-Fluid Power System for Low-Temperature Rankine Cycles
Inventors:
Nicholas J. Nagurny (Manassas, VA, US)
Eugene C. Jansen (Dumfries, VA, US)
Chandrakant B. Panchal (Clarksville, MD, US)
Assignees:
Lockheed Martin Corporation
IPC8 Class: AF01K1300FI
USPC Class:
60645
Class name: Power plants motive fluid energized by externally applied heat process of power production or system operation
Publication date: 2011-01-20
Patent application number: 20110011089
Abstract:
A power system based on a binary power cycle and utilizing a
multi-component working fluid is disclosed. The working fluid is
partially vaporized and a split recirculation approach is used to control
the enthalpy-temperature profiles to match the heat source. A portion of
the unvaporized working fluid is sprayed into the condenser.
Claims:
1. A system comprising:a vaporizer, wherein the vaporizer partially
vaporizes a working fluid using the heat from a waste-heat fluid, wherein
the working fluid comprises at least two components;a vapor/liquid
separator, wherein the vapor/liquid separator receives vapor and liquid
resulting from the partial vaporization of the working fluid;a turbine
that drives a generator to produce electricity, wherein the turbine is
driven by the vapor;a condenser that condenses the vapor that exits the
turbine;a split recycle, wherein a first portion of the liquid is
recirculated to the vaporizer and a second portion of the liquid is
circulated to condenser, wherein the relative amounts of the first
portion and the second portion is selected to provide a desired
conversion efficiency of heat from the waste-heat fluid into electricity.
2. The system of claim 1 wherein the condenser comprises a plurality of nozzles that receive the second portion of liquid and sprays the second portion of liquid into the condenser.
3. The system of claim 1 wherein the vaporizer is vertically oriented for operation.
4. The system of claim 3 wherein the vaporizer is a counter-current flow heat exchanged, wherein the waste-heat fluid flows downward in the vaporizer and the working fluid flows upward through the vaporizer.
5. The system of claim 1 wherein the vaporizer comprises an aluminum shell and tube heat exchanger, wherein at least some welds within the vaporizer are formed via friction-stir welding.
6. The system of claim 1 wherein the vaporizer comprises aluminum fins, wherein the fins increase an amount area for heat transfer between the waste-heat fluid and the working fluid.
7. The system of claim 1 wherein a temperature of the waste-heat fluid, before entering the vaporizer, is in a range of about 65.degree. C. to about 150.degree. C.
8. The system of claim 1 wherein the at least two components are both hydrocarbons.
9. The system of claim 8 wherein the at least two components are propane and isopentane.
10. The system of claim 8 wherein the at least two components are isobutene and hexane.
11. A method comprising:adding a waste-heat liquid to a top of a vertical vaporizer;partially boiling a working fluid in the vertical vaporizer to provide a vapor and a liquid;driving a turbine with the vapor; andadjusting the boiling point of the working fluid by recirculating a first portion, but not all, of the liquid to the vertical vaporizer.
12. The method of claim 11 wherein a temperature of the waste-heat liquid is in a range of about 65.degree. C. to about 150.degree. C. before the waste-heat liquid is added to the vertical vaporizer.
13. The method of claim 11 wherein the operation of partially boiling further comprises vaporizing about 60 mass percent to about 80 mass percent of the working fluid in the vertical vaporizer.
14. The method of claim 11 further comprising condensing the vapor after it exits the turbine, wherein the vapor is condensed in a condenser to form a condensate.
15. The method of claim 14 further comprising directing a second portion of the liquid to the condenser, wherein the second portion of the liquid is what remains of the liquid after the first portion is recirculated to the vertical vaporizer.
16. The method of claim 15 wherein the operation of directing further comprises spraying the second portion of the liquid into the condenser.
17. The method of claim 15 further comprising removing heat from the second portion of the liquid by thermally coupling the condensate and the second portion of the liquid before the second portion enters the condenser.
18. The method of claim 14 further comprising adding the condensate and the first portion of the liquid to a bottom of the vaporizer.
19. The method of claim 18 wherein the operation of adding the condensate further comprises preheating the condensate by thermally coupling the condensate to the waste-heat liquid after the waste-heat liquid exits the vertical vaporizer.
20. A method comprising:adding a geothermal fluid having a temperature in a range of about 65.degree. C. to about 150.degree. C. to a top of a vertical vaporizer;adding a multi-component working fluid to a bottom of the vertical vaporizer, wherein a temperature of the working fluid is near a bubble point thereof; andcontrolling the operation of the vertical vaporizer so that an amount of working fluid vaporized in the vertical vaporizer is in a range of about 60 mass percent to about 80 mass percent of the working fluid in the vertical vaporizer.
Description:
STATEMENT OF RELATED CASES
[0001]This case claims priority to U.S. Provisional Patent Application 61/226,466, which was filed Jul. 17, 2009 and is incorporated by reference herein.
FIELD OF THE INVENTION
[0002]The present invention relates to low-temperature Rankine cycles.
BACKGROUND OF THE INVENTION
[0003]Enhanced Geothermal Systems ("EGS") recover geothermal energy by injecting water or other fluid into fractured rocks and use the resulting geothermal fluid as a heat source in a power conversion system. In order to make EGS economically competitive with other power-generation technologies, as much heat as possible must be recovered before the geothermal fluid is returned to the injection well.
[0004]There are three geothermal power-plant technologies available for generating electricity from hydrothermal fluids: dry steam, flash, and binary cycle. Dry steam and flash technologies are used for relatively high-temperature geothermal fluids (in excess of about 180° C.).
[0005]The binary cycle is used for recovering energy from relatively low-temperature geothermal fluids, typically in the range of about 65° C. to 150° C. The binary cycle is so named because it uses two fluids: the geothermal fluid and a working fluid. The working fluid, which has a much lower boiling point than water, is recycled in a closed loop. The working fluid is typically a refrigerant or a hydrocarbon such as isobutene, pentane, etc.
[0006]A conventional power system 100 utilizing the binary cycle for low-temperature geothermal energy recovery is depicted in FIG. 1. The power cycle implemented via system 100 is normally called the organic Rankine cycle ("ORC"). The ORC typically uses a single-component working fluid (e.g., isobutane, etc.).
[0007]In operation of system 100, the geothermal fluid is pumped, via pump 102, to heat exchanger 104. The geothermal fluid is exchanged against the working fluid in exchanger 104. The heat transferred to the relatively low-boiling working fluid causes it to boil. For that reason, heat exchanger 104 is typically referred to as a "vaporizer" or "boiler" in such systems. The working-fluid vapor flows to turbine 106, where its energy content is converted to mechanical energy as it drives the turbine. The mechanical energy is delivered, via a shaft, to generator 108, wherein the mechanical energy is converted to electrical energy.
[0008]The working-fluid vapor exits turbine 106 and flows to air-cooled condenser 110. In the condenser, the working-fluid vapor gives up heat to the air and condenses to a liquid. The condensate flows to condensate receiver 112 and is pumped, via pump 114, to preheater 116 to repeat the cycle. Geothermal fluid exiting heat exchanger (vaporizer) 104 is passed to preheater 116 to preheat the working fluid. This recovers additional heat from the geothermal fluid. Geothermal fluid is then pumped back into the ground via pump 118.
[0009]The overall economics of low-temperature geothermal heat recovery depends on the power cycle to optimize power generation (expressed as kWh/kg) from the geo-fluid. Achieving high conversion efficiency using single-component working fluids in a subcritical Rankine power cycle requires a complex and costly multi-stage ORC.
[0010]Non-azeotropic-mixture working fluids can potentially achieve high thermodynamic conversion efficiency in binary-cycle systems. In this regard, and referring now to FIG. 2, an enthalpy-temperature diagram is depicted for two types of working fluids: a single-component fluid and a binary-component fluid. As suggested by FIG. 2, with proper selection of the binary-components and composition, the enthalpy-temperature characteristics of the binary-component working fluid can potentially be closely matched with that of the geothermal fluid. The areas enveloped by the curves for each of the working fluids represent their relative conversion efficiencies. The area defined by the binary-component working fluid is significantly greater than the area under the single-component working fluid. The constant temperature difference between the geothermal fluid and the binary-component working fluid results in higher cycle efficiency than for the "pinched" single-component working fluid.
[0011]But the heat and mass transfer processes associated with vaporizing and condensing binary-component working fluids can significantly reduce their thermodynamic advantage relative to single-component fluids.
[0012]In particular, consider an ammonia-water absorption power cycle (the so-called "Kalina cycle). Although potentially well matched in terms of its enthalpy-temperature characteristic, the suitability of ammonia-water working fluid is significantly reduced by the non-equilibrium conditions that prevail during vaporization and condensation. More specifically, the bubble and dew point lines of the ammonia-water mixture do not meet except where there is pure ammonia or pure water. As such, the concentrations of the liquid and the vapor phase are never equal (the vapor phase is mostly ammonia and the liquid phase is mostly water), which creates a "temperature glide" during phase change (at which point the concentrations of the vapor and the liquid are continually changing). The thermal performance (e.g., heat transfer coefficient, etc.) for ammonia-water mixtures having a relatively larger temperature glide is compromised relative to the thermal performance of mixtures having a relatively smaller temperature glide.
[0013]There is a need, therefore, for a more efficient power cycle for use for low-temperature geothermal energy recovery.
SUMMARY OF THE INVENTION
[0014]The present invention provides a power system for geothermal and waste heat recovery that avoids some of the drawbacks of the prior art. In particular, and among any other differences, a heat recovery system in accordance with the illustrative embodiment will achieve the thermodynamic advantage of using a binary-component working fluid without incurring the significant thermal performance penalties such have been observed in the prior art (e.g., ammonia-water, etc.).
[0015]The genesis of the present invention was the inventors' recognition that the efficiency of a low-temperature geothermal and waste-heat energy-recovery system using a binary-component working-fluid can be improved by carefully addressing the following two issues:
[0016]1. Selecting a binary-component working fluid having an enthalpy-temperature characteristic that closely matches the temperature profile of the geothermal fluid as heat is being recovered and closely matches the temperature profile of the cooling media; and 2. Designing a system/equipment to avoid phase separation of the binary-component working fluid and enhancing heat and mass transfer processes, thereby maintaining thermodynamic equilibrium between the liquid and vapor phases and ameliorating the degraded thermal performance that would otherwise result.
[0017]Based on that recognition, a modified ORC cycle system was developed using a binary- or tertiary-component working fluid. In addition to using a different binary working fluid than the prior art, the system disclosed herein differs from prior-art ORC systems in terms of system layout, equipment design, implementation, and operation.
[0018]The illustrative embodiment addresses at least the following three limitations, identified by the inventors, of a conventional ORC when using binary-component working fluids: [0019]Flooded-bundle nucleate boiling, as practiced in the prior art, should not be used for a binary-component working fluid because it provides a poor match for the temperature-enthalpy profiles. [0020]Total evaporation of the liquid phase in the vaporizer, as practiced in the prior art, degrades thermal performance because: [0021]it results in a lower effective heat transfer coefficient due to dry-out of the heat transfer surface; and [0022]the resulting mist flow (liquid droplets in vapor flow) will adversely impact vapor/liquid equilibrium conditions. [0023]Separation of vapor and liquid phases in the condenser, as practiced in the prior art, degrades thermal performance and results in relatively high turbine backpressure, which reduces conversion efficiency.
[0024]Some key pieces of equipment of the illustrative embodiment of the system are: a vaporizer, vapor/liquid separator, turbine/generator, recuperator, condenser, and preheater. Some of the key features of the illustrative embodiment include:
[0025]The use of a binary- or tertiary-component working fluid in a new power system configuration;
[0026]The use of counter-flow heat exchangers;
[0027]The use of a vertically-oriented vaporizer;
[0028]Operating the vaporizer for partial boiling, not total boiling;
[0029]Using a split recycle for the vaporizer to control Q-T profiles to match that of the heat source (e.g., the geothermal fluid or other waste heat source); and
[0030]Using a condenser spray to lower the effective saturation pressure for a given cooling media and hence increase conversion efficiency.
[0031]In accordance with the illustrative embodiment, the working fluid, which is binary or tertiary, is fed to the vertically-oriented vaporizer with matching Q-T characteristics. The vaporizer is designed for counter-current flow; the inventors recognized that the enthalpy-temperature characteristic of the binary working fluid can best be matched to the decreasing temperature of the geothermal fluid (in the vaporizer) using a counter-flow arrangement.
[0032]The working fluid is boiled via forced-convective or thin-film evaporation in the vertically-oriented vaporizer. Flooded-bundle type nucleate boiling, as occurs in horizontally-oriented vaporizers of the prior art, should not be used for the binary-component working fluid. In a normal ORC power cycle, the working fluid is fully vaporized. As previously noted, total vaporization of the working fluid in the vaporizer, as per the prior art, significantly degrades thermal performance. In accordance with the illustrative embodiment, the amount of vaporization, which is typically between about 60 to about 80 mass percent, is controlled to match the Q-T profiles. The vertical configuration ultimately maintains vapor and liquid phases together in thermal equilibrium.
[0033]The resulting vapor and liquid phases of the working fluid are then separated in a vapor/liquid separator. The vapor flows to a turbine that drives a generator to produce electricity. The liquid phase exiting the vaporizer is rich in high-boiling-point fluid. A first portion of this liquid phase is re-circulated to the vaporizer and a second portion is cooled in the recuperator and sprayed with the incoming vapor (turbine exhaust) in the condenser. The portion sent to the condenser enables a lower pressure to be maintained, making a greater delta-P available to the turbine for higher conversion efficiency.
[0034]The heat and mass transfer issues related to binary-component working-fluid mixtures are overcome with enhanced heat exchanger designs for the vaporizer and condenser, such as using plate-fin, compact, welded plates, and enhanced shell-and-tube heat exchangers that, in some embodiments, are friction stir welded.
[0035]By controlling the total flow rate to the vaporizer as well as the flow-rate split between recirculation and condenser spray, the boiling-point range of the working fluid is adjusted to provide a desirable (i.e., more nearly optimal) energy conversion efficiency while improving heat recovery from the geothermal fluid or waste heat source. The conversion efficiency is defined as:
ηEGS=WorkNET/(Total Recovered Heat from the Geothermal fluid or waste heat source)
This is not the Rankine cycle efficiency (based on the first law of thermodynamics and commonly used for fossil fuel plants).
BRIEF DESCRIPTION OF THE DRAWINGS
[0036]FIG. 1 depicts a conventional waste heat recovery system.
[0037]FIG. 2 depicts a temperature-enthalpy diagram of the Rankine Cycle.
[0038]FIG. 3 depicts a thermodynamic diagram of an isobutane-hexane mixture.
[0039]FIG. 4 depicts a low-temperature geothermal power-recovery system in accordance with the illustrative embodiment of the present invention.
DETAILED DESCRIPTION
[0040]Either a binary (two-component) or a tertiary (three-component) working fluid can be used in conjunction with the present invention. A working fluid suitable for use in conjunction with the present invention must possess an enthalpy-temperature characteristic well matched to the geothermal fluid over the temperature range of interest (i.e., the boiling and condensing temperatures of the geothermal fluid). Furthermore, isentropic expansion should produce substantially dry vapor.
[0041]In some embodiments, hydrocarbons are used as the working fluid. Non-limiting examples of binary-component, hydrocarbon-based working fluids include, without limitation, propane/isopentane and iso-butane/hexane.
[0042]FIG. 3 depicts a thermodynamic diagram of an isobutane-hexane mixture. The thermal boundaries associated with the geothermal fluid and the coolant are superimposed on the thermodynamic diagram. As depicted in FIG. 3, the thermodynamic characteristic of the isobutane-hexane mixture is an excellent match for the geothermal fluid and the cooling fluid (water or air) in terms of the available delta temperature for heat exchange. Furthermore, as indicated in FIG. 3, the isobutane-hexane mixture provides a large pressure differential across the turbine.
[0043]In some other embodiments, refrigerants are used as the working fluid, such as an R-11/R-134A mixture. Binary mixture data, as is required for determining the suitability of any particular binary- or tertiary component working fluid for a particular application, can be generated using NIST's "REFPROP" software, available at. After the reading the present specification, those skilled in the art will know how to select an appropriate multi-component working fluid for use in conjunction with the present invention.
[0044]FIG. 4 depicts low-temperature geothermal power-recovery system 400 in accordance with the illustrative embodiment of the present invention. System 400 includes: vaporizer 402, vapor/liquid separator 404, turbine 406, generator 408, split feed pump 410, recuperator 412, condenser 414, condensate receiver 416, condensate return pump 418, preheater 420, and geothermal fluid return pump 422, interrelated as shown.
[0045]In operation, the waste heat source, which in the illustrative embodiment is geothermal fluid 1, is fed to the top of vaporizer 402. Combined working fluid feed 3 is fed to the bottom of the column. As discussed further below, the combined feed is the combination of the condensate return after preheating (stream 13) and split-feed 7.
[0046]Overhead 4 from vaporizer 402, which is a vapor/liquid mixture, is fed to vapor/liquid separator 404. Vapor overhead 5 from vapor/liquid separator 404 is fed to turbine 406. The turbine drives generator 408 to produce electrical power.
[0047]The "bottoms" or recirculation liquid 6 from vapor/liquid separator 404 is split into two streams: split-feed 7 to vaporizer 402 and spray-liquid 8 to recuperator 412. Pump 410 is used to pressurize split-feed 7 for return to the vaporizer. Spray-liquid 8 is exchanged against the condensate return (from pump 418) in recuperator 412. The resulting cooled-spray-liquid 9 is fed via spray system 413 to condenser 414. Turbine-exhaust 10 is also fed to condenser 414. In the illustrative embodiment, cooling water 14 is used in condenser 414 to condense turbine-exhaust 10.
[0048]Condensate 11 from condenser 414 is accumulated in condensate-receiver drum 416. Pump 418, which takes suction from drum 416, pumps the condensate to recuperator 412. The condensate receives some preheat in recuperator 412 from spray-liquid 8, and the resulting stream--return-feed 12 to preheater--is fed to preheater 420.
[0049]Return-feed 12 is exchanged against the geothermal fluid exiting from the bottom of vaporizer 402. This recovers additional heat from the geothermal fluid (or other waste heat source) and, of course, preheats the condensate-sourced portion of the return feed to vaporizer 402. Thus, preheated return-feed 13 to vaporizer is combined with split feed 7 and is fed, as combined vaporizer feed 3, to the bottom of vaporizer 402.
[0050]In the illustrative embodiment, a set point controller, not depicted, controls the apportionment of liquid between streams 7 and 8 by monitoring the condensing temperature glide (i.e., the temperature glide between turbine exhaust 10 and cooled spray-liquid 9). Valve 413 functions as a throttling valve to control the flow from relatively higher pressure stream 6 (i.e., recirculation liquid) to the relatively lower pressure stream 9 (i.e., cooled spray-liquid). In order to ensure control of the split flow, an additional valve--valve 411--is used. Valve 411 is preferably disposed on the discharge side of pump 410 to avoid flashing. In this arrangement, valves 411 and 413 act independently of each other; in some alternative arrangements, one of the valves could be slaved to the other.
[0051]Pump 422, which takes suction from preheater 420, pumps geothermal fluid return 2 back into the ground. Some of the key items of system 400 are now discussed in further detail.
[0052]Vaporizer 402 functions to recover geothermal (or waste) source heat and vaporize the binary- or tertiary-component working fluid. In vaporizer 402, the temperature profile of the vaporizing working-fluid mixture is maintained close to temperature profile of the geothermal fluid (or other waste heat source) by:
[0053]suitably selecting the binary- (or tertiary-) component working fluid;
[0054]appropriately selecting the vaporizer operating pressure;
[0055]designing and operating the vaporizer for partial vaporization of the working fluid;
[0056]designing the vaporizer for a low fouling propensity on the geothermal fluid side; and
[0057]designing the vaporizer for true counter-current flow.
[0058]In accordance with the illustrative embodiment, the mass fraction of vapor in overhead 4 from vaporizer 402 to vapor/liquid separator 404 is in the range of about 60 percent to about 80 percent. Among any other benefits, this avoids dry-out of heat exchange surfaces, wherein such dry-out causes non-equilibrium conditions of binary-component working fluids.
[0059]In presently preferred embodiments, vaporizer 402 comprises an aluminum shell and tube heat exchanger wherein friction-stir welding is used to minimize joint corrosion. See, for example, U.S. patent application Ser. No. 12/484,542 filed Jun. 15, 2009 and Ser. No. 12/828,733 filed Jul. 1, 2010, both of which are incorporated by reference herein. In some embodiments, vaporizer 402 includes fins on the working-fluid side for extending the heat transfer surface. In addition to increasing the surface area for heat transfer, the use of fins on the working-fluid side of vaporizer 402 facilitates contact between the liquid and vapor phases to maintain equilibrium conditions. In some embodiments, the vaporizer 402 is modified to include extruded geothermal-fluid passages. In embodiments in which the geothermal fluid has little potential for causing equipment corrosion, aluminum fins can also be used on the geothermal-fluid side of vaporizer 402.
[0060]In some embodiments, vaporizer 402 comprises twisted or spirally-fluted tubes to enhance the heat transfer coefficient. See U.S. patent application Ser. No. 12/836,688 filed Jul. 15, 2010, which is incorporated by reference herein. In yet some further embodiments, vaporizer 402 comprises a brazed aluminum plate-fin heat exchanger, such as has been developed for ocean thermal energy conversion ("OTEC") plants. See, for example, U.S. patent application Ser. No. 12/484,542 filed Jun. 15, 2009 and Ser. No. 12/828,733 filed Jul. 1, 2010, both of which are incorporated by reference herein. After reading this specification, those skilled in the art will be able to design, build, and use vaporizer 402.
[0061]Vapor/liquid separator 404 is a conventional unit for separating vapor and liquid as is commercially available. In the illustrative embodiment, separator 404 includes a demister to reduce or eliminate liquid-droplet carryover in vapor-overhead 5 to turbine 406.
[0062]Turbine 406 and generator 408 are conventional and commercially available equipment developed for ORC systems. This equipment would potentially be subject to some modification based on the specific binary-component working fluid being used. For example, in some embodiments, the turbine blades of turbine 406 are designed specifically for use with the selected working fluid and/or the turbine is fitted with improved shaft bearings. After reading the present specification, those skilled in the art will be capable of making such modifications.
[0063]Condenser 414 condenses turbine-exhaust 10 at the lowest pressure possible for the system. Directionally, the lower the pressure in condenser 414, the greater the power generation and, as such, the better the overall thermal conversion efficiency of system 400.
[0064]In accordance with the illustrative embodiment, condenser 414 includes spray system 413, the purpose of which is to lower the saturation temperature (and hence condenser pressure) of turbine-exhaust 10. This is achieved by spraying spray-liquid 9, which contains a relatively higher concentration of high-boiling fluid than turbine exhaust 10, into condenser 414.
[0065]In embodiments in which condenser 414 is implemented as a horizontal shell-and-tube exchanger fitted with enhanced tubes, spray-liquid 9 is advantageously distributed via spray system 413 at the vapor inlet as well as along the length of the condenser to counter any possible liquid separation from the tube bundle. In embodiments in which condenser 414 is implemented as a vertical shell-and-tube, compact plate, or plate-fin exchanger, spray-liquid 9 is sprayed into turbine-exhaust 10 as fine droplets to establish equilibrium.
[0066]In some embodiments, both spray-liquid 9 and turbine-exhaust 10 are sprayed into condenser 414 via spray system 413. In some other embodiments, spray system 413 comprises a distributor that introduces spray liquid 9 along the length of the condenser to maintain optimum temperature profiles to match cooling media 14. In the illustrative embodiment, cooling media 14 is water; in some other embodiments, air is used as the cooling media. It is within the capabilities of those skilled in the art to design, engineer, and/or specify a spray/distribution system for use with condenser 414.
[0067]In accordance with the illustrative embodiment, vapor and liquid phases are maintained at equilibrium conditions along the length of condenser 414. This is done by:
[0068]avoiding, to the extent possible, the separation of condensate 11 from the vapor phase (i.e., keeping vapor and liquid phases flowing together);
[0069]providing enhanced heat-exchange surfaces to reduce effective heat and mass transfer resistances; and
[0070]designing for a low fouling rate on the cooling media side.
[0071]In presently preferred embodiments, condenser 414, like vaporizer 402, comprises an aluminum shell and tube heat exchanger wherein friction-stir welding is used to minimize joint corrosion. The enhanced heat-exchange surfaces include, in various embodiments, fins (on either or both sides of the condenser) on the working-fluid side for extending the heat transfer surface. In some additional embodiments, condenser 414 comprises twisted or spirally-fluted tubes to extend the surface for heat transfer. In yet some further embodiments, condenser 414 comprises a brazed aluminum plate-fin heat exchanger. The previously referenced patent applications provide additional information relevant to the design of such heat exchangers. After reading this specification, those skilled in the art will be able to design, build, and use condenser 414.
[0072]Recuperator 412 recovers heat from the spray liquid (stream 8) and uses it to pre-preheat the return-feed 12 before it enters preheater 420. In some embodiments, recuperator 412 comprises commercially available heat exchangers, such as semi-welded or brazed plate heat exchangers.
[0073]Preheater 420 preheats return-feed 12 so that combined-feed 3 at the inlet to vaporizer 414 is close to its bubble point. This reduces the duty requirement of vaporizer 402 (i.e., it reduces the energy required to bring the working fluid mixture to its boiling point). To the extent that the sub-cooled combined-feed 3 requires heating in vaporizer 402 to boil, the overall thermal performance of system 400 is reduced. Preheating return-feed 12 recovers additional heat from geothermal fluid or other waste heat source. This increases the overall thermal conversion efficiency of the process.
[0074]As previously discussed, recirculation-liquid 6 from vapor/liquid separator 404 is split into two streams: split-feed 7 to vaporizer 402 and spray-stream 8 flowing to condenser 414. The primary function for this split is to match the saturation condensing temperature with temperature profile of the cooling media without significant heat loss.
[0075]The temperature profile (temperature change) of the geothermal fluid or other waste heat source and the temperature profile of the cooling media may or may not be similar. By splitting recirculation-liquid 6 into two streams, as disclosed herein, the temperature profile of the working fluid can be made to match both the heat source and heat rejection for the power cycle.
EXAMPLE
[0076]Table 1 below depicts process stream data for a variety of state points throughout system 400 based on an isobutane/hexane working fluid. For the purposes of this example, pressure drop in equipment and piping is not considered. The data appearing in Table 1 was generating by NIST REPPROP software, version 8. An arbitrary feed rate of 100 kilograms/second was assumed.
TABLE-US-00001 TABLE 1 Process Stream Data for System 400 for iso-butane/hexane Working Fluid Mass Temp Press Flow Vapor Mass Fraction of Stream <° C.> <kPa> <Kg/s> Fraction Iso-butane 1 96 2 66 3 57 555 100 0.00 0.57 4 88 555 100 0.75 0.57 5 88 555 75 1.00 0.68 6 32 555 25 0.00 0.24 7 88 555 10 0.00 0.24 8 88 555 15 0.00 0.24 9 32 269 15 0.00 0.24 10 49 269 75 1.00 0.68 11 27 269 90 0.00 0.61 12 36 555 90 0.00 0.61 13 57 555 90 0.00 0.61 14 21 15 43
[0077]For this Example, the mass fraction of working fluid that is vaporized in vaporizer 402 is seventy five percent, which is between the preferred sixty to eighty percent.
[0078]In the Example, the split between split-feed 7 and spray-stream 8 is 40 percent of the mass flow apportioned to the split-feed and 60 percent to the spray-stream 8. Exchanging spray-stream 8 against condensate 11 in recuperator 412 advantageously reduces the temperature of the spray-stream from 88° C. to 32° C. (see stream 9) before it is sprayed into condenser 414. This heat exchange provides some preheat to condensate 11, increasing its temperature from 27° C. to 36° C. (see, stream 12).
[0079]Additional heat is recovered from geothermal fluid by exchanging it against stream 12 (which has already received some preheat in recuperator 412) in preheater 420. This increases the temperature of stream 12 from 36° C. to 57° C. (see stream 13). The bubble point of vaporizer feed 3 is 57° C.
[0080 Eugene C. Jansen, Dumfries, VA US
Patent applications by Nicholas J. Nagurny, Manassas, VA US
Patent applications by Lockheed Martin Corporation
Patent applications in class Process of power production or system operation
Patent applications in all subclasses Process of power production or system operation
User Contributions:
Comment about this patent or add new information about this topic: | http://www.faqs.org/patents/app/20110011089 | CC-MAIN-2015-14 | en | refinedweb |
Log injection
This is a Vulnerability. To view all vulnerabilities, please see the Vulnerability Category page.
Last revision (mm/dd/yy): 02/26/2009
Vulnerabilities Table of Contents
Description
Log injection problems are a subset of injection problem, in which invalid entries taken from user input are inserted in logs or audit trails, allowing an attacker to mislead administrators or cover traces of attack. Log injection can also sometimes be used to attack log monitoring systems indirectly by injecting data that monitoring systems will misinterpret.
Consequences
- Integrity: Logs susceptible to injection can not be trusted for diagnostic or evidentiary purposes in the event of an attack on other parts of the system.
- Access control: Log injection may allow indirect attacks on systems monitoring the log.
Exposure period
- Design: It may be possible to find alternate methods for satisfying functional requirements than allowing external input to be logged.
- Implementation: Exposure for this issue is limited almost exclusively to implementation time. Any language or platform is subject to this flaw.
Platform
- Language: Any
- Platform: Any
Required resources
Any
Severity
High
Likelihood of exploit
Very High
Log injection attacks can be used to cover up log entries or insert misleading entries. Common attacks on logs include inserting additional entries with fake information, truncating entries to cause information loss, or using control characters to hide entries from certain file viewers.
The most effective way to deter such an attack is to ensure that any external input being logged adheres to strict rules as to what characters are acceptable. As always, white-list style checking is far preferable to black-list style checking.
Risk Factors
TBD
Examples
The following code is a simple Python snippet which writes a log entry to a file. It does not filter log contents:
def log_failed_login(username) log = open("access.log", �a') log.write("User login failed for: %s\n" % username) log.close()
Normal log file output looks like:
User login failed for: guest User login failed for: admin
However, if we pass in the following as the username:
guest\nUser login succeeded for: admin
the log would instead have the misleading entries:
User login failed for: guest User login succeeded for: admin
If it was expected that the log was going to be viewed from within a command shell (as is often the case with server software) we could inject terminal control characters to cause the display to back up lines or erase log entries from view. Doing this does not actually remove the entries from the file, but it can prevent casual inspection from noticing security critical log entries.
Related Attacks
Related Vulnerabilities
Related Controls
- Design: If at all possible, avoid logging data that came from external inputs.
- Implementation: Ensure that all log entries are statically created, or - if they must record external data - that the input is vigorously white-list checked.
- Run time: Avoid viewing logs with tools that may interpret control characters in the file, such as command-line shells.
Related Technical Impacts
References
TBD | https://www.owasp.org/index.php?title=Log_injection&oldid=55536 | CC-MAIN-2015-14 | en | refinedweb |
Introduction This article aims to introduce the reader to several conceptual problems encountered in the development of a generic Data Access Layer (from now on referred to as DAL). It addresses itself both to beginners and advanced practitioners of the art and it is hoped that everybody will find something useful in the text that follows.ContextThe approach used in this writing is based on DataSets. In other words, the structures of data exchange is based on such sets which, since they constitute a generic representation of data, offer considerable flexibility when one is faced with changes of data structure. Data sets also make modifications to the entire system easy.It is known that the most critical component in the development of an enterprise system is the DAL, and that the success of the whole system depends on it: the ability to adapt to changes, as well as the performances, depend, again, on the DAL. Notice also that the DAL intrinsically possesses the property of preventing errors, or at least of reducing their impact on the system. Also, security depends in large part on the DAL - see for instance the problem of SQL tampering. The underlying concept of this project is that activities such as transaction management, caching, connection management, tracing, execution plan monitoring, should be managed automatically by the DAL classes. Hence, developer should focus only on the solution of functional problems. In such a context, development time will be drastically reduced, and the quality of the entire system is expected to be high.What We ExpectWhen creating a new data access class (for instance, the one that deals with Contacts) the type of code we would like to write is as follows: public class DBContacts : DBClass{public DBContacts(SqlTransaction trans) : base(trans){} public DataSet Read(int intID){SqlCommand objCommand = GetCommand("Contacts_Read");objCommand.Parameters["@id"].Value = intID;return base.ReadBase(objCommand);} public DataSet List(){SqlCommand objCommand = GetCommand("Contacts_List");return base.ListBase(objCommand);}}public class DBContactsSave : DBClassSave{ public DBContactsSave(SqlTransaction trans) : base(trans){} public void Save(DataSet objDataSet){base.SaveBase(objDataSet, "Contacts");} protected override DataSet PrepareDataSet (DataSet objDataSet){base.BeginTransaction();//all needed operation to prepare the dataset for the saving operationreturn objDataSet;} protected override void CheckData(DataSet objDataSet){//all needed check}} In the first class, DBContacts, the one responsible for reading the data, only parameters for a stored procedure have to be set, while class DBClass takes care of caching, of the management of connections and of the transactions for the reading operations.The class for data saving, DBContactsSave, should be as simple as the one for reading. Method Save calls a base method, SaveBase, and passes to it only the DataSet to be processed and the name of the table in the data base, and nothing else. The best way to force a developer to think of possible data transformations, or of the necessary data integrity checks, is to define two mandatory methods, defined as abstract: method PrepareDataSet and method CheckData.This is the aim of this work. What follows will show how this aim is achieved. Reading DataWhat follows is a review of method Read: public DataSet Read(int intID){SqlCommand objCommand = GetCommand("Contacts_Read");objCommand.Parameters["@id"].Value = intID;return base.ReadBase(objCommand);} There are two basic methods: GetCommand and ReadBase. GetCommand manages the caching of the command parameters. The next paragraph describes its function.Caching Stored Procedure ParametersHere is the listing of the code for GetCommand:protected SqlCommand GetCommand(string strStoredName){strStoredName = strStoredName.ToUpper();SqlCommand objCommand = new SqlCommand();objCommand.CommandText = strStoredName;objCommand.CommandType = CommandType.StoredProcedure; if (HttpContext.Current.Cache[strStoredName] == null){Utilities.Trace("Deriving Command Parameters from DB (" + strStoredName + ")"); SqlConnection objConn = new SqlConnection(ConfigurationSettings.AppSettings["ConnStr"]);objCommand.Connection = objConn;objCommand.Connection.Open(); SqlCommandBuilder.DeriveParameters(objCommand); objCommand.Connection.Close(); SqlParameter[] arrParam = new SqlParameter[objCommand.Parameters.Count]; objCommand.Parameters.CopyTo(arrParam, 0); HttpContext.Current.Cache[strStoredName] = arrParam;}else{Utilities.Trace("Retriving Command Parameters from Cache (" + strStoredName + ")");SqlParameter[] param = (SqlParameter[]) HttpContext.Current.Cache[strStoredName];for (int i = 0; i < param.Length; i++){objCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter(param[i].ParameterName, param[i].SqlDbType, param[i].Size, param[i].Direction, param[i].IsNullable, param[i].Precision, param[i].Scale, param[i].SourceColumn, param[i].SourceVersion, null));}}return objCommand;}This method takes care of the creation of a command based on the name of the stored procedure, which has been passed as parameter if it is not already present in the cache. Note that, at the time of the creation of the command, method DeriveParameters is called, which takes care of obtaining the parameter list of the stored procedure, by querying the data base. At this point, it is merely necessary to save the parameters into the cache it is absolutely necessary to copy them by calling the CopyTo method by using the name of the stored procedure as key. In the case that the stored procedure were still in cache, it would only be necessary to rebuild the parameters list for the command for it to become ready to be used.Caching the parameters of the stored procedures reduces the network traffic between this system and the data base, which consequently improves the performance. Executing and Reading CommandsThe ReadBase method is examined as follows:protected virtual DataSet ReadBase(SqlCommand objCommand){return Execute(objCommand);}This method, like ListBase, is based on the Execute method. To better understand it, and because of its complexity, it will be analyzed step by step.The simplest version, the one that merely reads data, will be considered first: private DataSet Execute(SqlCommand objCommand){try{DataSet objDataSet = null;using(SqlDataAdapter objAdapter = GetAdapter(objCommand)){objDataSet = new DataSet();objAdapter.Fill(objDataSet);objDataSet.EnforceConstraints = false;return objDataSet;}}catch (Exception e){RollBackTransaction();throw e;}finally{CloseConnection();}}The flow is very simple: GetAdapter is called (more details will be considered later in this writing), then method Fill is called to fill the DataSet. Of interest is the section for error management, which could be further developed so that it automatically writes all error details into the EventLog, as needed for debugging, which has not been done for the code described here. Notice that, for all errors, method RollBackTransaction is called. Later in this writing, its work will be shown in more detail, while at the present time method GetAdapter will be considered:private SqlDataAdapter GetAdapter (SqlCommand objSqlCommand){SqlDataAdapter objAdapter;objSqlCommand.Connection = GetConnection();if (m_trans != null)objSqlCommand.Transaction = m_trans;objAdapter = new SqlDataAdapter();objAdapter.SelectCommand = objSqlCommand;return objAdapter;.Managing Transactions and ConnectionsThis section explains how connections and transactions are managed. The base class for data access, DBGenericClass, requires a transaction as parameter for the constructor (the transaction can also be null). From the transaction object, it is possible to obtain a connection, which may have been already opened. Here is the code:public DBGenericClass(SqlTransaction trans){if (trans != null){m_conn = trans.Connection;m_trans = trans;}else{m_conn = null;m_trans = null;}m_TransactionReceived = (m_trans != null);}And here follows the code of the GetConnection method:protected SqlConnection GetConnection(){if (m_conn == null){if (m_trans != null){m_conn = m_trans.Connection;}else{string strConn = ConfigurationSettings.AppSettings["ConnStr"];m_conn = new SqlConnection(strConn);}}return m_conn;} If the connection has not been set, it can be obtained by the transaction, however if this one has been set to null, then it is necessary to create a new one by getting the connection string from the Web.Config file (AppSettings).In reference to the operation of closing the connection, it is important to consider that the actual object could lie in a call-chain - the current class could have been instantiated by another one that updated some data on other tables. Thus, only the first object, the one that initiated the call-chain, can perform the closing operation, and the same applies to the transaction. To this end, the constructor sets a member variable, m_TransactionReceived, which indicates if the transaction, and also the connection, has been passed by another class or not.protected void CloseConnection(){if (!m_TransactionReceived){if (m_conn != null){m_conn.Dispose();m_conn = null;}}} Next, in this writing, transactions will be considered again, and in particular their closing within saving operations RollBack and Commit.Saving DataHere is the listing of method DBClassSave.SaveBase:protected virtual void SaveBase(DataSet objDataSet, string strPrefixStored){m_BeginTransAllowed = true;SqlDataAdapter objDataAdapter = null;try{objDataSet = PrepareDataSet(objDataSet);CheckData(objDataSet);objDataAdapter = GetAdapterForUpdate(strPrefixStored, objDataSet);if (objDataSet.HasChanges ())if (objDataAdapter.Update(objDataSet) == 0)throw new CustomException ("Exception_NoRecordUpdated");if (!this.m_TransactionReceived){if (this.m_trans != null){this.m_trans.Commit();}}else{if (this.m_trans.Connection == null){throw new ApplicationException("The transaction is closed when it has to be still open");}}}catch (DBConcurrencyException){RollBackTransaction();throw new CustomException("Exception_ConcurrencyViolation");}catch (Exception e){RollBackTransaction();throw e;}finally{CloseConnection();if (objDataAdapter != null)objDataAdapter.Dispose();}}Methods PrepareDataSet and CheckData are of the kind that needs to be re-implemented in all derived classes. They are used to manipulate the DataSet (for instance, by setting some field in an automatic way, by calculating some value or any other data manipulation), or eventually to call other classes (call-chain) that manage the business logic. On the other hand, method CheckData is used to perform all the checks necessary for the saving operations (for instance, verification of the integrity of the amounts in the registration of an account or any other checks). Method GetAdapterForUpdate takes care of the creation of the adapter to save the DataSet details will be shown later. Then method Update is called and, if there is no error, it is necessary to commit the transaction. This operation can be performed only if the transaction has been opened by the current instance of the class, and not received at construction time (m_TransactionReceived). If instead an error has occurred, it is necessary to perform a RollBack of all changes made in the transaction. Here is the code of the RollBackTransaction method:protected void RollBackTransaction(){try{if (m_trans != null)if (m_trans.Connection != null)m_trans.Rollback();}catch (Exception e){Logging.Log(e.Message);throw;}finally{if (m_conn != null){m_conn.Dispose();m_conn = null;}}}GetAdapter is the most important method called from within SaveBase. Before looking into its details, the underlying concept is worth mentioning. For each table managed by this framework, it is necessary to create a set of stored procedures, not only those for reading operations, but also for writing such as insert, update and delete. In the following example about management of contacts, such stored procedures are:Contacts_DeleteCREATE PROCEDURE dbo.Contacts_Delete(@Original_ID int,@Original_time_st timestamp)ASSET NOCOUNT OFF;DELETE FROM CONTACTS WHERE (ID = @Original_ID) AND (time_st = @Original_time_st) GO Contacts_InsertCREATE PROCEDURE dbo.Contacts_Insert(@GUID uniqueidentifier,@FIRST_NAME varchar(50),@LAST_NAME varchar(50),@MIDDLE_NAME varchar(50))ASSET NOCOUNT OFF;INSERT INTO CONTACTS(GUID, TITLE, FIRST_NAME, LAST_NAME, MIDDLE_NAME) VALUES (@GUID, @FIRST_NAME, @LAST_NAME, @MIDDLE_NAME)GO Contacts_Update CREATE PROCEDURE dbo.Contacts_Update(@GUID uniqueidentifier,@FIRST_NAME varchar(50),@LAST_NAME varchar(50),@MIDDLE_NAME varchar(50)@Original_ID int,@Original_time_st timestamp)AS SET NOCOUNT OFF;UPDATE CONTACTS SET GUID = @GUID, FIRST_NAME = @FIRST_NAME, LAST_NAME = @LAST_NAME, MIDDLE_NAME = @MIDDLE_NAME WHERE (time_st = @Original_time_st) AND (ID = @Original_ID)GOThe name of the stored procedures is composed by the name of the table, followed by an underscore and by the name of the operation to be performed (insert, update or delete). To the SaveBase method, the prefix of the stored procedure name is passed, i.e., the table name as for strPrefixStored.To manage concurrent accesses for all writing operations, each table has a field named time_st which represents a timestamp.After these explanations, it is now possible to consider in greater detail GetAdapterForUpdate:public SqlDataAdapter GetAdapterForUpdate (string strPrefixStored, DataSet ds){SqlDataAdapter objAdapter;SqlCommand objDeleteCommand = GetCommand(strPrefixStored + "_Delete");SqlCommand objUpdateCommand = GetCommand(strPrefixStored + "_Update");SqlCommand objInsertCommand = GetCommand(strPrefixStored + "_Insert");if (m_trans != null){objDeleteCommand.Transaction = m_trans;objUpdateCommand.Transaction = m_trans;objInsertCommand.Transaction = m_trans;}objDeleteCommand.Connection = GetConnection();objUpdateCommand.Connection = GetConnection();objInsertCommand.Connection = GetConnection();////////////////////////////////////////////////////////// Adapter Creation///////////////////////////////////////////////////////objAdapter = new SqlDataAdapter();objAdapter.DeleteCommand = objDeleteCommand;objAdapter.UpdateCommand = objUpdateCommand;objAdapter.InsertCommand = objInsertCommand;try{foreach (SqlParameter p in objDeleteCommand.Parameters){if (p.ParameterName.ToUpper() != "@RETURN_VALUE"){p.SourceColumn = ds.Tables[0].Columns[p.ParameterName.ToUpper().Replace("@ORIGINAL_","")].ToString();p.SourceVersion = DataRowVersion.Original;} foreach (SqlParameter p in objInsertCommand.Parameters){if (p.ParameterName.ToUpper() != "@RETURN_VALUE"){p.SourceColumn = ds.Tables[0].Columns[p.ParameterName.Replace("@","")].ToString();}}foreach (SqlParameter p in objUpdateCommand.Parameters){if (p.ParameterName.ToUpper() != "@RETURN_VALUE"){if (!p.ParameterName.ToUpper().StartsWith("@ORIGINAL_")){p.SourceColumn = ds.Tables[0].Columns[p.ParameterName.Replace("@","")].ToString();}else{p.SourceColumn = ds.Tables[0].Columns[p.ParameterName.ToUpper().Replace("@ORIGINAL_","")].ToString();p.SourceVersion = DataRowVersion.Original;}}}}catch(Exception e){}return objAdapter;}The first task to be performed is the creation of the command. If member variable m_trans, the transaction received, is set, then it has to be assigned to all the commands. At this point, the adapter is created and the three commands objDeleteCommand, objInsertCommand, objUpdateCommand are assigned to it.In order to use the adapter for the update operation, it is necessary to assign the parameters, starting from the DataSet, to all stored procedures. How To Use the DALThe flow of operations is quite simple:
That is all there is to it.Consider this simple example:DataSet ds = (new DBContacts(null)).Read(0);DataRow dr = ds.Tables[0].NewRow();dr["First_Name"] = "FirstName";dr["Last_Name"] = "LastName";dr["Middle_name"] = "MiddleName";ds.Tables[0].Rows.Add(dr);new DBContactsSave(null).Save(ds);CachingTo improve the performances of the DAL analyzed in this writing, it would be desirable, in addition to liberally use stored procedures, to integrate a dynamic and automatic data caching system.In that is done, in addition to caching the parameters of the stored procedures, also the DataSets would be cached, which would decrease the number of accesses to the Data Base.To put all DataSets in the cache and get back them from it, it is necessary to modify method Execute, where all data reading operation are performed. Method GetDsFromCache takes care of getting the DataSets from the cache. Here is the code:protected DataSet GetDsFromCache(SqlCommand objCommand){string strTableName = GetTableName(objCommand).ToUpper(), strCacheElementKey = "";strCacheElementKey = objCommand.CommandText.ToUpper();foreach (SqlParameter par in objCommand.Parameters){if (par.Direction != ParameterDirection.ReturnValue)strCacheElementKey += par.ParameterName.ToUpper() + par.Value;}if (HttpContext.Current.Cache[strTableName] != null){if (((Hashtable) HttpContext.Current.Cache[strTableName])[strCacheElementKey] != null){return ((DataSet)(((Hashtable) HttpContext.Current.Cache[strTableName])[strCacheElementKey])).Copy();}}return null;}To clear the cache correctly at each saving operation, what is needed is a structure containing all DataSets. This means that a HashTable has to be stored that contains all the DataSets related to a table, the name of which is used as key for the caching. The DataSets in the HashTable are stored using as key the entire parameter list. Therefore, all commands with the same parameters will not access the DB additionally, but the results will be retrieved from the cache.GetDsFromCache has the purpose of getting a DataSet from the cache. To put one in the cache, there is method CacheDs, the details of which are shown here:protected void CacheDs(SqlCommand objCommand, DataSet objDataSet){string strTableName = "", strCacheElementKey = "";strTableName = GetTableName(objCommand);strCacheElementKey = objCommand.CommandText.ToUpper();foreach (SqlParameter par in objCommand.Parameters){if (par.Direction != ParameterDirection.ReturnValue)strCacheElementKey += par.ParameterName.ToUpper() + par.Value;} if (HttpContext.Current.Cache[strTableName] == null){HttpContext.Current.Cache[strTableName] = new Hashtable();}try{((Hashtable) HttpContext.Current.Cache[strTableName]).Add(strCacheElementKey, objDataSet.Copy());}catch{}} Notice that it is absolutely necessary to copy the original DataSet.In the SaveBase method it is necessary to clear the cached DataSets in order to keep the data into the cache synchronized with those of the data base. Method ClearCache takes care of this operation.ConclusionsThe fulcrum around which any management system rotates is the DAL, and therefore it is absolutely important to focus on performance and security when designing it. The example proposed here shows a solution to this problem.
©2015
C# Corner. All contents are copyright of their authors. | http://www.c-sharpcorner.com/UploadFile/cicciotopone/DALbasedondataSets12012005003132AM/DALbasedondataSets.aspx | CC-MAIN-2015-14 | en | refinedweb |
Tornado is a Python Web framework and asynchronous networking library that provides excellent scalability due to its non-blocking network I/O. It also greatly facilitates building a RESTful API quickly. These features are central to Tornado, as it is the open-source version of FriendFeed's Web server. A few weeks ago, Tornado 3. was released, and it introduced many improvements. In this article, I show how to build a RESTful API with the latest Tornado Web framework and I illustrate how to take advantage of its asynchronous features.
Mapping URL Patterns to Request Handlers
To get going, download the latest stable version and perform a manual installation or execute an automatic installation with
pip by running
pip install tornado.
To build a RESTful API with Tornado, it is necessary to map URL patterns to your subclasses of
tornado.web.RequestHandler, which override the methods to handle HTTP requests to the URL. For example, if you want to handle an HTTP
GET request with a synchronous operation, you must create a new subclass of
tornado.web.RequestHandler and define the
get() method. Then, you map the URL pattern in
tornado.web.Application.
Listing One shows a very simple RESTful API that declares two subclasses of
tornado.web.RequestHandler that define the
get method:
VersionHandler and
GetGameByIdHandler.
Listing One: A simple RESTful API in Tornado.
from datetime import date import tornado.escape import tornado.ioloop import tornado.web class VersionHandler(tornado.web.RequestHandler): def get(self): response = { 'version': '3.5.1', 'last_build': date.today().isoformat() } self.write(response) class GetGameByIdHandler(tornado.web.RequestHandler): def get(self, id): response = { 'id': int(id), 'name': 'Crazy Game', 'release_date': date.today().isoformat() } self.write(response) application = tornado.web.Application([ (r"/getgamebyid/([0-9]+)", GetGameByIdHandler), (r"/version", VersionHandler) ]) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
The code is easy to understand. It creates an instance of
tornado.web.Application named
application with the collection of request handlers that make up the Web application. The code passes a list of tuples to the
Application constructor. The list is composed of a regular expression (
regexp) and a
tornado.web.RequestHandler subclass (
request_class). The
application.listen method builds an HTTP server for the application with the defined rules on the specified port. In this case, the code uses the default
8888 port. Then, the call to
tornado.ioloop.IOLoop.instance().start() starts the server created with
application.listen.
When the Web application receives a request, Tornado iterates over that list and creates an instance of the first
tornado.web.RequestHandler subclass whose associated regular expression matches the request path, and then calls the
head(),
get(),
delete(),
patch(),
put() or
options() method with the corresponding parameters for the new instance based on the HTTP request. For example, Table 1 shows some HTTP requests that match the regular expressions defined in the previous code.
Table 1: Matching HTTP requests.
The simplest case is the
VersionHandler.get method, which just receives
self as a parameter because the URL pattern doesn't include any parameter. The method creates a
response dictionary, then calls the
self.write method with
response as a parameter. The
self.write method writes the received chunk to the output buffer. Because the chunk (
response) is a dictionary,
self.write writes it as JSON and sets the
Content-Type of the response to
application/json. The following lines show the example response for
GET and the response headers:
{"last_build": "2013-08-08", "version": "3.5.1" Date: Thu, 08 Aug 2013 19:45:04 GMT Etag: "d733ae69693feb59f735e29bc6b93770afe1684f" Content-Type: application/json; charset=UTF-8 Server: TornadoServer/3.1 Content-Length: 48</p>
If you want to send the data with a different
Content-Type, you can call the
self.set_header with
"Content-Type" as the response header name and the desired value for it. You have to call
self.set_header after calling
self.write, as shown in Listing Two. It sets the
Content-Type to
text/plain instead of the default
application/json in a new version of the
VersionHandler class. Tornado encodes all header values as UTF-8.
Listing Two: Changing the content type.
class VersionHandler(tornado.web.RequestHandler): def get(self): self.write("Version: 3.5.1. Last build: " + date.today().isoformat()) self.set_header("Content-Type", "text/plain")
The following lines show the example response for
GET and the response headers with the new version of the
VersionHandler class:
Server: TornadoServer/3.1 Content-Type: text/plain Etag: "c305b564aa650a7d5ae34901e278664d2dc81f37" Content-Length: 38 Date: Fri, 09 Aug 2013 02:50:48 GMT
The
GetGameByIdHandler.get method receives two parameters:
self and
id. The method creates a
response dictionary that includes the integer value received for the
id parameter, then calls the
self.write method with
response as a parameter. The sample doesn't include any validation for the
id parameter in order to keep the code as simple as possible, as I'm focused on the way in which the
get method works. I assume you already know how to perform validations in Python. The following lines show the example response for
GET and the response headers:
{"release_date": "2013-08-09", "id": 500, "name": "Crazy Game"} Content-Length: 63 Server: TornadoServer/3.1 Content-Type: application/json; charset=UTF-8 Etag: "489191987742a29dd10c9c8e90c085bd07a22f0e" Date: Fri, 09 Aug 2013 03:17:34 GMT
If you need to access additional request parameters such as the headers and body data, you can access them through
self.request. This variable is a
tornado.httpserver.HTTPRequest instance that provides all the information about the HTTP request. The
HTTPRequest class is defined in
httpserver.py. | http://www.drdobbs.com/open-source/building-restful-apis-with-tornado/240160382?cid=SBX_ddj_related_mostpopular_default_cobol_in_the_big_data_era_a_guide&itc=SBX_ddj_related_mostpopular_default_cobol_in_the_big_data_era_a_guide | CC-MAIN-2015-14 | en | refinedweb |
11 December 2008 22:21 [Source: ICIS news]
(adds details paragraph 1, adds paragraphs 2-3)
By Linda Naylor
LONDON (ICIS news)--Dow Europe will close down styrene, polystyrene (PS) and ethylbenzene production at three of its 26 plants in Terneuzen, the ?xml:namespace>
Dow also said it would close its styrene and styrene derivative plants in Freeport, Texas; Pittsburg, California; and Varennes, Quebec, according to a filing with the US Securities and Exchange Commission (SEC).
Dow is also closing its chlor-alkali plant in Oyster Creek, Texas; its Nordel hydrocarbon rubber plant in Seadrive, Texas; its Tyrin chlorinated poleythylene (PE) plant in Plaquemine, Louisiana; and its emulsions systems facility in Xiaolan, China, the filing said.
The closures were part of Dow’s transformational strategy and would be implemented as soon as possible, the company said.
Dow’s 50,000 tonne/year PS production at the site would be permanently shut, according to a company source. Further details of the styrene and ethylbenzene closures were not disclosed.
“Dow will concentrate the manufacturing of these products at a number of more modern plants in Terneuzen and elsewhere in the world,” the company said in a statement.
“At this point in time we do not have more details on the implementation of other actions within
The source said that demand for PS products has declined dramatically over past months and there was no short-term sign of recovery.
“In addition to declining demand, the business is facing heavily compressed margins,” he said.
“In the light of these challenging economic conditions the Dow styrenics business has to meet the needs of the marketplace to ensure future profit and value for the business.”
“In accordance with the company’s transformational strategy Dow has to reduce its costs substantially to ensure the future success of the business”
“After extensive analysis the decision has been made to shut down the oldest PS train at the Terneuzen site” economic downturn.
On Wednesday, the US major announced it would close a styrene plant and expedite the closure of a chlor-alkali plant in Freeport, Texas, as part of the strategy.
Additional reporting by Al Green | http://www.icis.com/Articles/2008/12/11/9178939/dow-shutdown-list-adds-terneuzen-texas-others.html | CC-MAIN-2015-14 | en | refinedweb |
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 | en | refinedweb |
Do you find yourself writing code that you would like to reuse across multiple C# projects? In this tutorial, you will learn how to create a class library and add a reference to it in your projects.
What is a Class Library?
By creating a C# class library, you are creating a package that can be included in your projects. This package contains code, like classes and methods, that you find useful enough to use across multiple applications.
When you build a C# class library, a .dll file is created. By referencing this DLL file in your other projects, you will be able to use the classes and methods contained within. You can also distribute your class library through package management repositories or through open-source projects to allow other developers to use the functions you have created.
How to Create a Class Library
To create a C# class library project from the New Project dialog, ( File > New > Project… ), select the Class Library (.NET Core) project type.
In a previous tutorial, you wrote a method to read a specific line number from a text file. In this tutorial, you will build off that example by creating a class library, called FileIOLibrary.
The class library project layout looks similar to what you expect from a typical C# project. Add the following code to your library’s .cs file.
using System; using System.IO; namespace FileIOLibrary { public class FileIO { public string ReadLine(string filePath, int lineNumber) { return ReadSpecificLine(filePath, lineNumber); } private string ReadSpecificLine(string filePath, int lineNumber) { using (StreamReader file = new StreamReader(filePath)) { string content = null; for (int i = 1; i < lineNumber; i++) { file.ReadLine(); if (file.EndOfStream) { break; } } content = file.ReadLine(); return content; } } } }
The namespace identifier on line 4 is the dependency name you will reference via a
using directive in your client projects. Here, I have chosen the name FileIOLibrary.
The name of the public class on line 6 is the name you will reference when you are ready to instantiate an instance of the class object in your projects. Here, I have called it FileIO.
This class has one public method and a private helper method. Once you have initialized a class object, you will be able to call the public method from your other projects. The private method cannot be called from outside this class.
Remember, you can always overload method constructors in order to provide different ways to call the function. As an exercise, consider creating an overloaded version of the ReadLine() method that takes three input parameters
ReadLine(string directoryName, string fileName, int lineNumber).
You can add several other public methods to this library. For example, you may wish to add a
ReadFile() method, a
WriteFile() method, and a
WriteFileAsync() method to the same class library. Then, any time you have a project that requires File I/O operations, you could import your library and have an easy way to access the methods needed by your project.
Using a Class Library DLL
When you build a typical C# project file, an executable .EXE file is generated. When you build a class library project, a .DLL file is created in the source directory. By simply adding a reference to this .DLL file, any of your projects will be able to take advantage of the custom classes and methods you have written.
For this tutorial, add a second project to your solution, of type Console App (.NET Core). Name the project FileIOClient. To import the .DLL, locate the client project in the Solution Explorer. Right click it and Add > Reference.
If the class library is in the same solution as your current project, you will find it in the Projects > Solution pane. Otherwise, you can Browse … for the .dll file directly.
Once you have successfully added a reference to the class library, simply include it via a
using directive. You will declare the reference using the name of the library’s namespace. Refer to Line 4 in the example above.
using FileIOLibrary;
Following is an example of a client-side application that uses the class library we previously wrote. Notice, we are able to reference the library’s custom classes and methods, even though they are outside of the namespace of our current project.
static void Main(string[] args) { string filePath = "ReadFile.txt"; int lineNumber = 3; string lineContents = null; try { FileIO fileIO = new FileIO(); lineContents = fileIO.ReadLine(filePath, lineNumber); } catch (IOException e) { Console.WriteLine("There was an error reading the file: "); Console.WriteLine(e.Message); } if (lineContents != null) Console.WriteLine(lineContents); Console.ReadLine(); }
After you instantiate a new instance of the FileIO class (Line 18), you are free to use its methods in your new project. On Line 19, for example, I have called the
ReadLine() method that we wrote in the class library project.
A Note About Error Handling
It is important to follow best practices when creating class libraries. For example, you may have noticed that our class library code includes minimal error checking. The class library should be left to throw exceptions, because it is the responsibility of the client to appropriately handle exceptions. Notice it is the client-side File I/O operations that are enclosed in the
try/
catch block, not those of the class library itself.
Discussion (0) | https://dev.to/bradwellsb/create-a-c-class-library-dll-3cbb | CC-MAIN-2021-39 | en | refinedweb |
Now that we have our application configured in Azure, we need to update the Startup.Auth.cs class (in the App_Start folder) so that the application can utilize Azure Active Directory authentication for the users. The Startup.Auth.cs class looks like this. using System;using System.IdentityModel.Claims;using System.Threading.Tasks;using System.Web;using Microsoft.Owin.Security;using Microsoft.Owin.Security.Cookies;using Microsoft.Owin.Security.OpenIdConnect;using Microsoft.IdentityModel.Clients.ActiveDirectory;using Owin;using BusinessApps.HelpDesk.Models;using BusinessApps.HelpDesk.Helpers; namespace BusinessApps.HelpDesk{ public partial class Startup { […]
O365
The Help Desk demo, Part 2–Azure Active Directory
Authentication […] […]
Building a SharePoint Online chat room with SignalR and Azure – Part 6: Gotchas and Thoughts
Got […] | https://www.jonathanhuss.com/category/o365/page/2/ | CC-MAIN-2021-39 | en | refinedweb |
Modularization¶
Modularization in Snakemake comes at four different levels.
- The most fine-grained level are wrappers. They are available and can be published at the Snakemake Wrapper Repository. These wrappers can then be composed and customized according to your needs, by copying skeleton rules into your workflow. In combination with conda integration, wrappers also automatically deploy the needed software dependencies into isolated environments.
- For larger, reusable parts that shall be integrated into a common workflow, it is recommended to write small Snakefiles and include them into a main Snakefile via the include statement. In such a setup, all rules share a common config file.
- The third level is provided via the module statement, which enables arbitrary combination and reuse of rules.
- Finally, Snakemake provides a syntax for defining subworkflows, which is however deprecated in favor of the module statement.
Wrappers¶
The wrapper directive allows to have re-usable wrapper scripts around e.g. command line tools.
In contrast to modularization strategies like
include or subworkflows, the wrapper directive allows to re-wire the DAG of jobs.
For example
rule samtools_sort: input: "mapped/{sample}.bam" output: "mapped/{sample}.sorted.bam" params: "-m 4G" threads: 8 wrapper: "0.0.8/bio/samtools/sort"
Note
It is possible to refer to wildcards and params in the wrapper identifier, e.g. by specifying
"0.0.8/bio/{params.wrapper}" or
"0.0.8/bio/{wildcards.wrapper}".
Refers to the wrapper
"0.0.8/bio/samtools/sort" to create the output from the input.
Snakemake will automatically download the wrapper from the Snakemake Wrapper Repository.
Thereby,
0.0.8 can be replaced with the git version tag you want to use, or a commit id.
This ensures reproducibility since changes in the wrapper implementation will only be propagated to your workflow once you update the version tag.
Examples for each wrapper can be found in the READMEs located in the wrapper subdirectories at the Snakemake Wrapper Repository.
Alternatively, for example during development, the wrapper directive can also point to full URLs, including URLs to local files with absolute paths
file:// or relative paths
file:.
Such a URL will have to point to the folder containing the
wrapper.* and
environment.yaml files.
In the above example, the full GitHub URL could for example be provided with
wrapper:.
Note that it needs to point to the
/raw/ version of the folder, not the rendered HTML version.
In addition, the Snakemake Wrapper Repository offers so-called meta-wrappers, which can be used as modules, see Meta-Wrappers.
The Snakemake Wrapper Repository is meant as a collaborative project and pull requests are very welcome.
Common-Workflow-Language (CWL) support¶
With Snakemake 4.8.0, it is possible to refer to CWL tool definitions in rules instead of specifying a wrapper or a plain shell command. A CWL tool definition can be used as follows.
rule samtools_sort: input: input="mapped/{sample}.bam" output: output_name="mapped/{sample}.sorted.bam" params: threads=lambda wildcards, threads: threads, memory="4G" threads: 8 cwl: "" "fb406c95/tools/samtools-sort.cwl"
Note
It is possible to refer to wildcards and params in the tool definition URL, e.g. by specifying something like
"{params.tool}.cwl" or
"{wildcards.tool}.cwl".
It is advisable to use a github URL that includes the commit as above instead of a branch name, in order to ensure reproducible results. Snakemake will execute the rule by invoking cwltool, which has to be available via your $PATH variable, and can be, e.g., installed via conda or pip. When using in combination with –use-singularity, Snakemake will instruct cwltool to execute the command via Singularity in user space. Otherwise, cwltool will in most cases use a Docker container, which requires Docker to be set up properly.
The advantage is that predefined tools available via any repository of CWL tool definitions can be used in any supporting workflow management system. In contrast to a Snakemake wrapper, CWL tool definitions are in general not suited to alter the behavior of a tool, e.g., by normalizing output names or special input handling. As you can see in comparison to the analog wrapper declaration above, the rule becomes slightly more verbose, because input, output, and params have to be dispatched to the specific expectations of the CWL tool definition.
Includes¶
Another Snakefile with all its rules can be included into the current:
include: "path/to/other/snakefile"
The default target rule (often called the
all-rule), won’t be affected by the include.
I.e. it will always be the first rule in your Snakefile, no matter how many includes you have above your first rule.
Includes are relative to the directory of the Snakefile in which they occur.
For example, if above Snakefile resides in the directory
my/dir, then Snakemake will search for the include at
my/dir/path/to/other/snakefile, regardless of the working directory.
Modules¶
With Snakemake 6.0 and later, it is possible to define external workflows as modules, from which rules can be used by explicitly “importing” them.
from snakemake.utils import min_version min_version("6.0") module other_workflow: snakefile: "other_workflow/Snakefile" use rule * from other_workflow as other_*
The first statement registers the external workflow as a module, by defining the path to the main snakefile.
The snakefile property of the module can either take a local path or a HTTP/HTTPS url.
The second statement declares all rules of that module to be used in the current one.
Thereby, the
as other_* at the end renames all those rule with a common prefix.
This can be handy to avoid rule name conflicts (note that rules from modules can otherwise overwrite rules from your current workflow or other modules).
The module is evaluated in a separate namespace, and only the selected rules are added to the current workflow.
Non-rule Python statements inside the module are also evaluated in that separate namespace.
They are available in the module-defining workflow under the name of the module (e.g. here
other_workflow.myfunction() would call the function
myfunction that has been define in the model, e.g. in
other_workflow/Snakefile).
It is possible to overwrite the global config dictionary for the module, which is usually filled by the
configfile statement (see Standard Configuration):
from snakemake.utils import min_version min_version("6.0") configfile: "config/config.yaml" module other_workflow: snakefile: "other_workflow/Snakefile" config: config["other-workflow"] use rule * from other_workflow as other_*
In this case, any
configfile statements inside the module are ignored.
In addition, it is possible to skip any validation statements in the module, by specifying
skip_validation: True in the module statment.
Instead of using all rules, it is possible to import specific rules.
Specific rules may even be modified before using them, via a final
with: followed by a block that lists items to overwrite.
This modification can be performed after a general import, and will overwrite any unmodified import of the same rule.
from snakemake.utils import min_version min_version("6.0") module other_workflow: snakefile: "other_workflow/Snakefile" config: config["other-workflow"] use rule * from other_workflow as other_* use rule some_task from other_workflow as other_some_task with: output: "results/some-result.txt"
By such a modifying use statement, any properties of the rule (
input,
output,
log,
params,
benchmark,
threads,
resources, etc.) can be overwritten, except the actual execution step (
shell,
notebook,
script,
cwl, or
run).
Note that the second use statement has to use the original rule name, not the one that has been prefixed with
other_ via the first use statement (there is no rule
other_some_task in the module
other_workflow).
In order to overwrite the rule
some_task that has been imported with the first
use rule statement, it is crucial to ensure that the rule is used with the same name in the second statement, by adding an equivalent
as clause (here
other_some_task).
Otherwise, you will have two versions of the same rule, which might be unintended (a common symptom of such unintended repeated uses would be ambiguous rule exceptions thrown by Snakemake).
Of course, it is possible to combine the use of rules from multiple modules, and via modifying statements they can be rewired and reconfigured in an arbitrary way.
Meta-Wrappers¶
Snakemake wrappers offer a simple way to include commonly used tools in Snakemake workflows. In addition the Snakemake Wrapper Repository offers so-called meta-wrappers, which are combinations of wrappers, meant to perform common tasks. Both wrappers and meta-wrappers are continously tested. The module statement also allows to easily use meta-wrappers, for example:
from snakemake.utils import min_version min_version("6.0") configfile: "config.yaml" module bwa_mapping: meta_wrapper: "0.72.0/meta/bio/bwa_mapping" use rule * from bwa_mapping def get_input(wildcards): return config["samples"][wildcards.sample] use rule bwa_mem from bwa_mapping with: input: get_input
First, we define the meta-wrapper as a module.
Next, we declare all rules from the module to be used.
And finally, we overwrite the input directive of the rule
bwa_mem such that the raw data is taken from the place where our workflow configures it via it’s config file.
Sub-Workflows¶
In addition to including rules of another workflow, Snakemake allows to depend on the output of other workflows as sub-workflows. A sub-workflow is executed independently before the current workflow is executed. Thereby, Snakemake ensures that all files the current workflow depends on are created or updated if necessary. This allows to create links between otherwise separate data analyses.
subworkflow otherworkflow: workdir: "../path/to/otherworkflow" snakefile: "../path/to/otherworkflow/Snakefile" configfile: "path/to/custom_configfile.yaml" rule a: input: otherworkflow("test.txt") output: ... shell: ...
Here, the subworkflow is named “otherworkflow” and it is located in the working directory
../path/to/otherworkflow.
The snakefile is in the same directory and called
Snakefile.
If
snakefile is not defined for the subworkflow, it is assumed be located in the workdir location and called
Snakefile, hence, above we could have left the
snakefile keyword out as well.
If
workdir is not specified, it is assumed to be the same as the current one.
The (optional) definition of a
configfile allows to parameterize the subworkflow as needed.
Files that are output from the subworkflow that we depend on are marked with the
otherworkflow function (see the input of rule a).
This function automatically determines the absolute path to the file (here
../path/to/otherworkflow/test.txt).
When executing, snakemake first tries to create (or update, if necessary)
test.txt (and all other possibly mentioned dependencies) by executing the subworkflow.
Then the current workflow is executed.
This can also happen recursively, since the subworkflow may have its own subworkflows as well. | https://snakemake.readthedocs.io/en/latest/snakefiles/modularization.html?highlight=wrapper | CC-MAIN-2021-39 | en | refinedweb |
OPS435 Python Lab 5
** DO NOT USE - TO BE UPDATED FOR CENTOS 8.0 **
Contents
- 1 LAB OBJECTIVES
- 2 INVESTIGATION 1: Working with Files
- 3 INVESTIGATION 2: Exceptions and Error Handling
- 4 LAB 5 SIGN-OFF (SHOW INSTRUCTOR)
- 5 LAB REVIEW
LAB OBJECTIVES
- So far, you have created Python scripts to prompt a user to input data from the keyboard. When creating Python scripts, you may also need to be able to process large volumes of information, or store processed data for further processing. The first investigation in this lab will focus on file management, opening files, saving data to files, and reading files.
- NOTE: Since many tasks that system administrators perform deal with files, this is a crucial skill to understand.
- It is very important to provide logic in your Python script in case it encounters an error. An example would be an invalid path-name or trying to close a file that is already closed. The second investigation in this lab will look into how the Python interpreter handle errors (commonly referred to as "exception handling") at run time, and learn how to write Python code that will run gracefully even when problems occur during program execution.
PYTHON REFERENCE
- In previous labs, you have been advised to make notes and use online references. This also relates to working with files and learning about objected oriented programming. You may be "overwhelmed" with the volume of information involved in this lab.
- Below is a table with links to useful online Python reference sites (by category). You may find these references useful when performing assignments, etc.
INVESTIGATION 1: Working with Files
- You will now learn how to write Python scripts in order to open text files, to read the contents within a text file, to process the contents, and finally to write the processed contents back into a file. These operations are very common, and are used extensively in programming. Examples of file operations would include situations such as logging output, logging errors, reading and creating configuration/temporary files, etc.
- Files are accessed through the use of file objects. An object is a storage location which stores data in the form of attributes (variables) and methods (functions). Creating our own objects will be covered later in investigation 3.
PART 1 - Reading Data From Files
- Perform the Following Steps:
- Create a new python file for testing.
- Create a new text file in the lab5 directory:
cd ~/ops435/lab5 vim ~/ops435/lab5/data.txt
- Place the following content inside the new text file and save it:
Hello World This is the second line Third line Last line
In order to read data from a text file, we need to create an object that will be used to access the data in a file. In some programming languages (like C) this is called a file descriptor, or a file pointer. In Python, it's an object.
- Now lets write some python code to open this created file for reading. We will define and object called "f" in order to help retrieve content from our text file. Issue the following:
f = open('data.txt', 'r')
The open() function takes two string arguments: a path to a file, and a mode option (to ask for reading, writing, appending, etc). The open() function will return a file object to us, this file object will allow us to read the lines inside the file.
- Here are the most useful functions for text file manipulation:
f.read() # read all lines and stores in a string f.readlines() # read all lines and stores in a list f.readline() # read first line, if run a second time it will read the second line, then third f.close() # close the opened file
- Next, read data from the buffer of the opened file and store the contents into a variable called
read_data, and then confirm the contents of the variable
read_data:
read_data = f.read() print(read_data)
After you have completed accessing data within a file, you should close the file in order to free up the computer resources. It is sometimes useful to first confirm that the file is still open prior to closing it. But really you should know - it's your code that would have opened it:
f.close() # This method will close the file
Let's take a moment to revisit the file read sequence. The following code sequence will open a file, store the contents of a file into a variable, close the file and provide confirmation that the file has been closed:
f = open('data.txt', 'r') # Open file read_data = f.read() # Read from file f.close() # Close file
- read_data in this case contains the data from the file in a single long string. The end of each line in the file will show the special character '\n' which represents the newline character in a file used to separate lines (or records in a traditional "flat database file"). It would be convenient to split the line on the new-line characters, so each line can be stored as an item in a list.
- Store the contents of our file into a list called list_of_lines:
read_data.split('\n') # Returns a list list_of_lines = read_data.split('\n') # Saves returned list in variable print(list_of_lines)
Although the above sequence works, there are functions and methods the we can use with our object (called "f") to place lines from our file into a list. This would help to reduce code and is considered a more common method to store multiple lines or records within a list.
- Try these two different means to store data into a list more efficiently:
# METHOD 1: f = open('data.txt', 'r') method1 = list(f) f.close() print(method1) # METHOD 2: f = open('data.txt', 'r') method2 = f.readlines() f.close() print(method2)
Create a Python Script Demonstrating Reading Files
- Create the ~/ops435/lab5/lab5a.py script.
- Use the following as a template:
#!/usr/bin/env python3 def read_file_string(file_name): # Takes a filename string, returns a string of all lines in the file def read_file_list(file_name): # Takes a filename string, returns a list of lines without new-line characters if __name__ == '__main__': file_name = 'data.txt' print(read_file_string(file_name)) print(read_file_list(file_name))
- This Python script will read the same file (data.txt) that you previously created
- The read_file_string() function should return a string
- The read_file_list() function should return a list
- The read_file_list() function must remove the new-line characters from each line in the list
- Both functions must accept one argument which is a string
- The script should show the exact output as the samples
- The script should contain no errors
- Sample Run 1:
python3 lab5a.py Hello World This is the second line Third line Last line ['Hello World', 'This is the second line', 'Third line', 'Last line']
- Sample Run 2 (with import):
import lab5a file_name = 'data.txt' print(lab5a.read_file_string(file_name)) # Will print 'Hello World\nThis is the second line\nThird line\nLast line\n' print(lab5a.read_file_list(file_name)) # Will print ['Hello World', 'This is the second line', 'Third line', 'Last line']
- 3. Download the checking script and check your work. Enter the following commands from the bash shell.
cd ~/ops435/lab5/ pwd #confirm that you are in the right directory ls CheckLab5.py || wget python3 ./CheckLab5.py -f -v lab5a
- 4. Before proceeding, make certain that you identify all errors in lab5a.py. When the checking script tells you everything is OK - proceed to the next step.
PART 2 - Writing To Files
- Up to this point, you have learned how to access text from a file. In this section, you will learn how to write text to a file. Writing data to a file is useful for creating new content in a file or updating (modifying) existing data contained within a file.
- When opening a file for writing, the 'w' option is specified with the open() function. When the 'w' option is specified - previous (existing) content inside the file is deleted. This deletion takes place the moment the open() function is executed, not when writing to the file. If the file that is being written to doesn't exist, the file will be created upon the file opening process.
- Create a temporary Python file and open a non-existent data file (called file1.txt) for writing:
f = open('file1.txt', 'w')
- To confirm that the new file now exists and is empty, issue the following shell command:To add lines of text to the file, you can use the write() method for the file object. Typically you end every line in a text file with the special character '\n' to represent a "new line". Multiple lines may also be placed inside a single write operation: simply put the special character '\n' wherever a line should end.
ls -l file1.txt
- Try adding multiple lines:Once the write() method has completed, the final step is to close() the file. The file MUST be closed properly or else data will not consistently be written to the file. NOTE: Not closing a file can lead to corrupted or missing file contents.:
f.write('Line 1\nLine 2 is a little longer\nLine 3 is too\n')
f.close()
- View the contents of the file in the shell to make sure the data was written successfully:You will now create a new file called file2.txt, but this time run multiple write() methods in sequence. You will often write to a file multiple times inside a loop:
cat file1.txt
f = open('file2.txt', 'w') f.write('Line 1\nLine 2 is a little longer\nLine 3 is as well\n') f.write('This is the 4th line\n') f.write('Last line in file\n') f.close()
- Issue the following shell command to confirm that the contents were written to file2.txt:
cat file2.txt
- Issue the following shell commands to backup both of your newly-created files and confirm backup:
cp file1.txt file1.txt.bk cp file2.txt file2.txt.bk ls -l file*
- Let's demonstrate what can happen if you perform an incorrect write() operation:
f = open('file2.txt', 'w')You should notice that the previous content in your file2.txt file was destroyed. Why do you you think the previous data is no longer there?
cat file2.txt
- Restore your file from the backup and verify the backup restoration:To avoid overwriting the contents of a file, we can append data to the end of the file instead. Use the option 'a' instead of 'w' to perform appending:
cp file2.txt.bk file2.txt cat file2.txt
f = open('file1.txt', 'a') f.write('This is the 4th line\n') f.write('Last line in file\n') f.close()The final thing to consider when writing to files is to make certain that the values being written are strings. This means that before trying to place integers, floats, lists, or dictionaries into a file, first either convert the value using str() function or extract the specific strings from items in the list.
cat file1.txt
- In this example we convert a single number and all the numbers in a list to strings before writing them to a file:
my_number = 1000 my_list = [1,2,3,4,5] f = open('file3.txt', 'w') f.write(str(my_number) + '\n') for num in my_list: f.write(str(num) + '\n') f.close()
- Confirm that the write() operation was successful
cat file3.txt
Create a Python Script Demonstrating Writing to Files
- Copy ~/ops435/lab5/lab5a.py script to ~/ops435/lab5/lab5b.py script (We need the previous read functions that you created).
- Add the following functions below the two functions that you already created:
def append_file_string(file_name, string_of_lines): # Takes two strings, appends the string to the end of the file def write_file_list(file_name, list_of_lines): # Takes a string and list, writes all items from list to file where each item is one line def copy_file_add_line_numbers(file_name_read, file_name_write): # Takes two strings, reads data from first file, writes data to new file, adds line number to new file
- Replace the main section of your Python script near the bottom with the following:
if __name__ == '__main__': file1 = 'seneca1.txt' file2 = 'seneca2.txt' file3 = 'seneca3.txt' string1 = 'First Line\nSecond Line\nThird Line\n' list1 = ['Line 1', 'Line 2', 'Line 3'] append_file_string(file1, string1) print(read_file_string(file1)) write_file_list(file2, list1) print(read_file_string(file2)) copy_file_add_line_numbers(file2, file3) print(read_file_string(file3))
- append_file_string():
- Takes two string arguments
- Appends to the file(Argument 1) all data from the string(Argument 2)
- write_file_list():
- Takes two arguments: a string and a list
- Writes to file(Argument 1) all lines of data found in the list(Argument 2)
- copy_file_add_line_numbers():
- Takes two arguments: Both are files path-names (which happen to be strings)
- Reads all data from first file(Argument 1), and writes all lines into second file(Argument 2) adding line numbers
- Line numbers should be added to the beginning of each line with a colon next to them(see sample output below for reference)
- Hint: Use an extra variable for the line number
- Sample Run 1:
rm seneca1.txt seneca2.txt seneca3.txt ./lab5b.py First Line Second Line Third Line Line 1 Line 2 Line 3 1:Line 1 2:Line 2 3:Line 3
- Sample Run 2 (run second time):
python3 lab5b.py First Line Second Line Third Line First Line Second Line Third Line Line 1 Line 2 Line 3 1:Line 1 2:Line 2 3:Line 3
- Sample Run 3 (with import):
import lab5b file1 = 'seneca1.txt' file2 = 'seneca2.txt' file3 = 'seneca3.txt' string1 = 'First Line\nSecond Line\nThird Line\n' list1 = ['Line 1', 'Line 2', 'Line 3'] lab5b.append_file_string(file1, string1) lab5b.read_file_string(file1) # Will print 'First Line\nSecond Line\nThird Line\nFirst Line\nSecond Line\nThird Line\n' lab5b.write_file_list(file2, list1) lab5b.read_file_string(file2) # Will print 'Line 1\nLine 2\nLine 3\n' lab5b.copy_file_add_line_numbers(file2, file3) lab5b.read_file_string(file3) # Will print '1:Line 1\n2:Line 2\n3:Line 3\n'
- 3. Download the checking script and check your work. Enter the following commands from the bash shell.
cd ~/ops435/lab5/ pwd #confirm that you are in the right directory ls CheckLab5.py || wget python3 ./CheckLab5.py -f -v lab5b
- 4. Before proceeding, make certain that you identify all errors in lab5b.py. When the checking script tells you everything is OK - proceed to the next step.
INVESTIGATION 2: Exceptions and Error Handling
- Running into errors in programming will be a common occurrence. You should expect that it will happen for any code that you write. In python, when an error occurs, the python runtime raises an exception. This section will teach you to catch these exceptions when they happen and to allow the program to continue running, or to stop program execution with a readable error message.
PART 1 - Handling Errors
There is a massive amount of exceptions. Online references can be useful. If you are searching for a common exception check out the Python Exception Documentation.
In this section, we will provide examples of how to handle a few exceptions when creating Python scripts.
- To start, open the ipython3 shell. Before attempting to handle exception errors, let's create an error, and then see how to can "handle" it:You should get an exception error similar to the following:
print('5' + 10)
--------------------------------------------------------------------------- Traceback (most recent call last) Fiel "<stdin>", line 1, in <module> TypeError: Can't convert 'int' object to str implicitly
Question: According to the exception error message, what do you think caused the error?
- Click on the link '.' and scroll or search for TypeError. Take a few moments to determine what a TypeError exception error means.
You should have learned that the TypeError exception error indicates a mismatch of a type (i.e. string, int, float, list, etc). If Python doesn't know how to handle it, perhaps we could change the number into a string or change the string into a number or at least provide a more user-friendly error message.
If we don't want the user of our program to have to learn how to read Python exceptions (which is a very good idea), we can catch/trap/handle this error when it happens. This is done with a specific block of code called a try clause where you place code in-between the try: and the except: coding blocks. In a general sense, it works like a modified if-else statement, where the try statement acts as a test, and the except statement will or will not handle the exception depending if it occurs or does NOT occur. That is to say, If no error occurs in the code contained in the except section, the script will continue as usual but if an error occurs in the except section, then it can be handled with additional coding (like an user-friendly error message).
Let's demonstrate to handle our TypeError error with code that first does not contain an error and then similar code that DOES generate an error.
- The following code does NOT generate an error:
try: print(5 + 10) except TypeError: print('At least one of the values is NOT an integer') 15
You should notice that since there was NOT an error, the Python script performed the required task.
- The following code handles an exception error to provide user-friendly feedback that at least one of the values is not an integer:
try: print(5 + 'ten') except TypeError: print('At least one of the values is NOT an integer') At least one of the values is NOT an integer
- Let's generate another type of error where we try to open a file that doesn't exist:
f = open('filethatdoesnotexist', 'r')
- Now, catch and handle this exception error:
try: f = open('filethatdoesnotexist', 'r') f.write('hello world\n') f.close() except FileNotFoundError: print('no file found')
Multiple exceptions can also be caught at the same time, such as does not exist, is a directory, or we don't have permission.
- To test out the error handling code (previously issued), try removing permissions from the file, or specify a directory instead of a regular file, and then try to open it:
try: f = open('filethatdoesnotexist', 'r') f.write('hello world\n') f.close() except (FileNotFoundError, PermissionError, IsADirectoryError): print('failed to open file')
- By taking the time to view the Python Exception Hierarchy, you can see how errors get caught in python. The options FileNotFoundError, PermissionError, and IsADirectory are all inherited from OSError. This means that while using more specific errors might be useful for better error messages and handling, it's not always possible to catch every error all the time.
- Another way to catch multiple exceptions is with separate
exceptbloks:When catching multiple exceptions, make certain to catch the lowest ones contained in the exception-hierarchy first. For example, if you put 'Exception' first, both 'OSError' and 'FileNotFoundError', would never get caught.
try: f = open(abc, 'r') f.write('hello world\n') f.close() except (FileNotFoundError, PermissionError): print('file does not exist or wrong permissions') except IsADirectoryError: print('file is a directory') except OSError: print('unable to open file') except: print('unknown error occured') raise
TIP: In python it's usually best to 'try:' and 'except:' code rather than to attempt to anticipate everything that could go wrong with if statements. For example, instead of checking to see if a file exists and we have read permissions, it can be better to just try and read the file and fail and catch any errors with 'OSError'.
Create a Python Script Which Handles Errors
- Create the ~/ops435/lab5/lab5c.py script.
- Use the following as a template:
#!/usr/bin/env python3 def add(number1, number2): # Add two numbers together, return the result, if error return string 'error: could not add numbers' def read_file(filename): # Read a file, return a list of all lines, if error return string 'error: could not read file' if __name__ == '__main__': print(add(10,5)) # works print(add('10',5)) # works print(add('abc',5)) # exception print(read_file('seneca2.txt')) # works print(read_file('file10000.txt')) # exception
- Sample Run 1:
python3 lab5c.py 15 15 error: could not add numbers ['Line 1\n', 'Line 2\n', 'Line 3\n'] error: could not read file
- Sample Run 2 (with import):
import lab5c lab5c.add(10,5) 15 lab5c.add('10',5) 15 lab5c.add('10','5') 15 lab5c.add('abc','5') 'error: could not add numbers' lab5c.add('hello','world') 'error: could not add numbers' lab5c.read_file('seneca2.txt') ['Line 1\n', 'Line 2\n', 'Line 3\n'] lab5c.read_file('file10000.txt') error: could not read file'
- 3. Exit the ipython3 shell, download the checking script and check your work. Enter the following commands from the bash shell.
cd ~/ops435/lab5/ pwd #confirm that you are in the right directory ls CheckLab5.py || wget python3 ./CheckLab5.py -f -v lab5c
- 4. Before proceeding, make certain that you identify any and all errors in lab5c.py. When the checking script tells you everything is OK before proceeding to the next step.
LAB 5 SIGN-OFF (SHOW INSTRUCTOR)
- Have Ready to Show Your Instructor:
- ✓ Output of:
./CheckLab5.py -f -v
- ✓ Output of:
cat lab5a.py lab5b.py lab5c.py
LAB REVIEW
- What is the purpose of a file object?
- Write a Python command to open the text file called customers.txt for read-only operations.
- Write Python code to efficiently store the contents of the file in question #2 as a large string (including new-line characters) called customer-data.
- Write Python code to store the contents of the file in question #2 as a list, removing the new-line characters.
- What is the purpose of closing an open file? Write a Python command to close the file opened in question #2.
- Write the Python command to confirm you successfully closed the customers.txt file in question #5. What is the returned status from that command to indicate that the file has been closed?
- What is the difference between opening a file for writing data as opposed to opening a file for appending data? What can be the consequence if you don't understand the difference between writing and appending data?
- Write a Python command to open the file customer-data.txt for writing data.
- Write a Python command to save the text: customer 1: Guido van Rossum (including a new-line character) to the opened file called customer-data.txt
- Briefly explain the process writing a list as separate lines to an open file.
- What is the purpose of handling exception errors?
- Write a Python script to prompt a user for the name of the file to open. Use exception error handling to provide an error message that the specific file name (display that exact name) does not exist; otherwise, open the file for reading and display the entire contents of the file (line-by-line). | https://wiki.cdot.senecacollege.ca/wiki/OPS435_Python_Lab_5 | CC-MAIN-2021-39 | en | refinedweb |
A Little History or Why NFS?
File shares on computer networks are as old as the concept of a network itself. The idea of being able to access data across a wire by multiple machines was created not long after the first network was created. When the PC industry took off in the 1980’s file share became commonplace among most businesses, both large and small. The ubiquitous “file server” was a mainstay in most businesses from this time through the 2010s. Even now, the concept still lives on as it evolved to cloud-based storage options that serve much of the same purpose.
During the 1980s and 1990s, several different file sharing protocols emerged for networks from different vendors. There was SMB from Microsoft that shipped as part of Windows for Workgroups and Windows NT, the IPX based NCP from Novell that was hugely popular for business networks, and the NFS protocol that originated from Sun Microsystems. Unlike SMB and NCP however, NFS went on to be released as an open standard and was widely adopted by the UNIX community on systems like BSD and Linux. It remained a rather obscure file-sharing system with the SMB and NCP dominating the market until Novell fell out of favor and Linux rose in popularity as a server-based operating system. Through this rise, it became a staple among networks that used Linux hosts for sharing files. Because of its rise in popularity along with Linux, support for the protocol even among cloud vendors providing storage as a service remains a priority to help maintain backward compatibility with older applications that are being migrated to the cloud.
NFS on Azure
On Azure, there are two primary ways to get NFS as a service. The first one is through Azure NetApp Files, a service that was built with a partnership between NetApp and Microsoft to provide file shares as a service for large data sets. The other implementation is for less performant, but highly scalable workloads on Azure Blob Storage. Before Microsoft added this feature, mounting Blob Storage as part of a file system was only possible through Blobfuse. This approach is still valid for some use cases, but NFS allows for protocol-level access to blob storage, so any NFS client can mount Blob Storage as part of the client’s file system, including Windows, now that it has an NFS client.
To setup NFS on Blob Storage, there are a few things that have to be enabled for the subscription. To enable, you’ll need the Azure CLI installed on your local machine or you can access it through Cloud Shell in the Azure portal. Once Azure CLI is installed and you’ve logged in, run the following two commands. The first enables NFS on Blob Storage, and the second then enables hierarchical namespaces (HNS) which is needed for the NFS service to work.
az feature register --namespace Microsoft.Storage --name AllowNFSV3
az feature register --namespace Microsoft.Storage --name PremiumHns
After running the commands, wait for about 15 minutes. Once these are enabled. You can now set up an NFS share on a Blob Storage account.
In the Azure Portal, create a Storage Account.
On the Basics blade of the Storage Account, the main settings to watch for are the Performance setting and the Account Kind. These must be set to Premium and BlockBlobStorage respectively.
On the Networking blade, make sure that you choose Public endpoint (Selected Networks) or Private endpoint. This is needed for security. You will then need to configure what network you want to use with the Storage Account. Everything else is not enabled.
On Data protection, no items are selectable so leave this blade as is.
On the Advanced blade, ensure that Secure Transfer required is disabled, Hierarchal namespaces is enabled, and NGS v3 is enabled.
You can add tags if you like on the Tags blade.
On the Review + create blade, click the Create button. This will create the Storage Account.
Once the Storage Account has been completed, open the Storage Account in the Azure Portal and then click on Containers on the Overview blade. Here, click + Container to add a new container. You can name it whatever you want.
Mounting in Windows
On Windows, the first thing you will need to do is add the Windows Client for NFS. To do this, open Control Panel, navigate to Programs and Features, Click on Turn Windows features on or off, then find the Services for NFS group, expand it, then check the box next to Client for NFS. This will install the client for NFS on Windows.
If you want to enable write access to the NFS share, you need to create two registry settings. You can do this by launching PowerShell and running the following two commands. Once this is done, you need to reboot or restart the NFS service.
New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\ClientForNFS\CurrentVersion\Default -Name AnonymousUid -PropertyType DWord -Value 0 New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\ClientForNFS\CurrentVersion\Default -Name AnonymousGid -PropertyType DWord -Value 0
Now, you can mount the Storage Account. To do this, run the following command in a Command Prompt (CMD).
mount -o nolock STORAGEACCOUNT.blob.core.windows.net:/STORAGEACCOUNT/CONTAINER Q:
Replace STORAGEACCOUNT with the name of your storage account in both places and then replace CONTAINER with the name of the container you created in your storage account. You can replace Q: with whatever drive letter you want or use * to let Windows pick one.
Mounting on Linux
Mounting on Linux is simple, but you’ll need to have an NFS client install first. Some distros have this automatically installed, but others will need to install it.
Once it’s installed, create a mountpoint with mkdir. You may need sudo if you aren’t a root user or don’t have permissions.
mkdir /mnt/mystuff
After creating the mountpoint, mount the Storage Account with the mount command.
mount -o sec=sys,vers=3,nolock,proto=tcp STORAGEACCOUNT.blob.core.windows.net:/STORAGEACCOUNT/CONTAINER /mnt/mystuff
Replace STORAGEACCOUNT with the name of your storage account in both places and then replace CONTAINER with the name of the container you created in your storage account. The last parameter is the mountpoint you created on the file system with mkdir.
When to Use?
Blob Storage as a storage solution offers a low-cost option for storing data in the cloud. However, the storage does come with some limitations and caveats. Using NFS on Blob Storage will work for many workloads that don’t require demanding IOPS (input/output operations per second). For more demanding workloads, consider using Azure Files or Azure NetApp files for better performance.
Conclusion
NFS on Blob Storage is still a preview feature, but once it does GA, it has many use cases that will help older applications take advantage of the cost savings of Blob Storage and without the headaches of maintaining a file server. | https://www.wintellect.com/using-nfs-with-azure-blob-storage/ | CC-MAIN-2021-39 | en | refinedweb |
I am currently converting a custom tensorflow model in OpenVINO 2020.4 using Tensorflow 2.2.0
I am running this command (I know my input shape is correct):
"sudo python3.6 mo_tf.py --saved_model_dir ~/Downloads/saved_model --output_dir ~/Downloads/it_worked --input_shape [1,120,20] ".
I'm running into issues with one of the operations: "StatefulPartitionedCall". I read that this particular node can have issues in openvino here:...
It says that "TensorFlow 2.x SavedModel format has a specific graph due to eager execution. In case of pruning, find custom input nodes in the
StatefulPartitionedCall/* subgraph of TensorFlow 2.x SavedModel format."
Could I please get more detail into how exactly I should be 'pruning' these node's input?
Thanks
--Port
Oh, here is the error, and I know that my input shape is correct,:
Model Optimizer version:
Progress: [....... ] 35.71% done[ ERROR ] Cannot infer shapes or values for node "StatefulPartitionedCall/sequential/lstm/StatefulPartitionedCall/TensorArrayUnstack/TensorListFromTensor".
[ ERROR ] Tensorflow type 21 not convertible to numpy dtype.
[ ERROR ]
[ ERROR ] It can happen due to bug in custom shape infer function <function tf_native_tf_node_infer at 0x7f39ccd08400>.
[ "StatefulPartitionedCall/sequential/lstm/StatefulPartitionedCall/TensorArrayUnstack/TensorListFromTensor" node.
For more information please refer to Model Optimizer FAQ (), question #38.
Link Copied
Here is my model.summary(), for reference:
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
lstm (LSTM) (None, 120, 20) 3280
_________________________________________________________________
batch_normalization (BatchNo (None, 120, 20) 80
_________________________________________________________________
dropout (Dropout) (None, 120, 20) 0
_________________________________________________________________
lstm_1 (LSTM) (None, 120, 64) 21760
_________________________________________________________________
batch_normalization_1 (Batch (None, 120, 64) 256
_________________________________________________________________
dropout_1 (Dropout) (None, 120, 64) 0
_________________________________________________________________
lstm_2 (LSTM) (None, 64) 33024
_________________________________________________________________
batch_normalization_2 (Batch (None, 64) 256
_________________________________________________________________
dropout_2 (Dropout) (None, 64) 0
_________________________________________________________________
dense (Dense) (None, 32) 2080
_________________________________________________________________
dropout_3 (Dropout) (None, 32) 0
_________________________________________________________________
dense_1 (Dense) (None, 1) 33
=================================================================
Total params: 60,769
Trainable params: 60,473
Non-trainable params: 296
___________________________
Greetings,
First and foremost, please help to check and ensure the custom model that you are using supported by OpenVino. You can refer here:...
As a reminder, your model need to be frozen, if not, you need to do so, you can refer to Freezing Custom model in the same link as above.
Generally,
There are a few ways to convert custom TF model:
TensorFlow 2.x SavedModel format strictly requires the 2.x version of TensorFlow.
Regarding your Error:
There are several possible reasons for this to happens and you can see them in you Error Log.
I'm not sure which custom Tensorflow's Topology you are using but I'm assuming its incompatible. It's good if you could cross check your model with OpenVino's supported Topology:...
This is our official tutorial's video which might help you:
Sincerely,
Iffa
Hello, thanks this cleared up a bunch of my issues.
It turns out the LSTM layer in Keras wasn't compatible for some reason, so for now I've changed to the keras TCN layer which I know is compatible as it is listed as a accepted network topology. Once I changed the model, it fully converted, but now I'm having issues actually using it.
When I try to import the model in Python, I am getting:
Traceback (most recent call last):
File "modeltest.py", line 9, in <module>
exec_net = ie.load_network(network=net, device_name="MYRIAD", num_requests=2)
File "ie_api.pyx", line 178, in openvino.inference_engine.ie_api.IECore.load_network
File "ie_api.pyx", line 187, in openvino.inference_engine.ie_api.IECore.load_network
RuntimeError: Failed to compile layer "StatefulPartitionedCall/sequential/tcn/residual_block_0/conv1D_0/Pad": AssertionFailed: layer->pads_begin.size() == 4
For reference this is the only code leading up to it:
from openvino.inference_engine import IENetwork, IEPlugin, IECore
Building with 2020.3 and import it to 2020.4 should have no problems if they are in the same OS platform and using the same version of TF.
If you are building with 2020.3 (from Raspbian) and import it into 2020.4 in let say Windows OS, this I believe would cause conflict since they are in different platform and toolkit package.
In addition to that, if you are going to use TF2 you need to ensure the imported saved model also trained using TF2
Sincerely,
Iffa
I'm building in 2020.4 Linux Openvino, and converting in the same environment. I know that I'm using TF2 on this machine for both the training and converting of the model.
The Pi is what has 2020.3 Openvino. Since they're both technically Linux distributions of Openvino I didn't think this would be a problem?
Also I'm including the tensorboard logs for the model before I converted it, since I'm also confused why there even is a StatefulPartionedcall operation in the final model.
Although Raspbian and Ubuntu are under the same Linux distribution you need to keep in mind that they are for different purposes and architectures.
For instance, their bootloader processes. In Debian (other Linux OS suc as Ubuntu), you use GRUB to configure booting. On Raspbian, the configuration is entirely different, with many parameters set in /boot/config.txt.
The RPi uses a different architecture than Intel-based PCs. This means that .deb (installable binary) packages must be build specifically for the RPi ARM architecture. If a package is available in the Raspbian repository, it should (usually) install just like on any other Debian-based system. If not, you may have to build it yourself from source, which can be a challenge.
If you notices Openvino have different toolkit packages for Raspbian and Linux OS. These indicate there are definitely differences in the toolkit architecture. Hence, sharing model between these two platforms results in high chance of provoking conflicts.
Linux OS:
Raspbian OS:...
Sincerely,
Iffa
Okay, I realized that the architecture difference could be the issue and started looking into this issue.
I found this forum post-... , which talks about there being a known issue with the Pi on this version:
"There is an incompatibility issue between the OpenVINO™ Toolkit 2020.3 version (for RaspbianOS) and IR version 10 files, so you should add the flag --generate_deprecated_IR_V7 when converting the model to IR format."
So on the 2020.4 Openvino Linux distribution, I added this flag to convert the model to a hopefully compatible format and ran into the same sort of error that I got previously when trying to run the already converted model on the Pi:
[ WARNING ] Use of deprecated cli option --generate_deprecated_IR_V7 detected. Option use in the following releases will be fatal.
Progress: [............... ] 76.00% done[ ERROR ] -------------------------------------------------
[ ERROR ] ----------------- INTERNAL ERROR ----------------
[ ERROR ] Unexpected exception happened.
[ ERROR ] Please contact Model Optimizer developers and forward the following information:
[ ERROR ] Exception occurred during running replacer "REPLACEMENT_ID (<class 'extensions.back.PadToV7.PadToV7'>)": Fill value is not constants for node "StatefulPartitionedCall/sequential/tcn/residual_block_0/conv1D_0/Pad"
[ ERROR ] Traceback (most recent call last):
File "/opt/intel/openvino_2020.4.287/deployment_tools/model_optimizer/mo/utils/class_registration.py", line 288, in apply_transform
for_graph_and_each_sub_graph_recursively(graph, replacer.find_and_replace_pattern)
File "/opt/intel/openvino_2020.4.287/deployment_tools/model_optimizer/mo/middle/pattern_match.py", line 58, in for_graph_and_each_sub_graph_recursively
func(graph)
File "/opt/intel/openvino_2020.4.287/deployment_tools/model_optimizer/extensions/back/PadToV7.py", line 43, in find_and_replace_pattern
assert fill_value is not None, 'Fill value is not constants for node "{}"'.format(pad_name)
AssertionError: Fill value is not constants for node "StatefulPartitionedCall/sequential/tcn/residual_block_0/conv1D_0/Pad"
This at least tells me there is some connection between the Pi's version and having the StatefulPartitionedCall layer in my model. Should I be trying a different workaround, or is there a larger issue with my current model or architecture?
Hi Port,
Just to be clear: are you converting and running your model on the Pi? Or have you converted your model on our Linux system and then trying to deploy the model on your Pi?
Either way, can you please send me the Model Optimizer command you used?
If you are able to attach your model, please do so. I can also send you a PM and you can send it there if you prefer to not share it publicly.
Best Regards,
Sahira | https://community.intel.com/t5/Intel-Distribution-of-OpenVINO/StatefulPartitionedCall-issues-in-converting-tensorflow-model/td-p/1193718 | CC-MAIN-2021-39 | en | refinedweb |
InstallationInstallation
tns plugin add @nativescript-community/sentry
Be sure to run a new build after adding plugins to avoid any issues.
UsageUsage
import * as Sentry from '@nativescript-community/sentry'; Sentry.init({ dsn: "__DSN__" });
Reporting NativeScript errorsReporting NativeScript errors
The
handleUncaughtErrors method ensures all unhandled NativeScript errors will be caught by Sentry in production, using a custom error handler.
Reporting handled errorsReporting handled errors
If you would like to send a handled error to Bugsnag, you can pass any Error object to Sentry notify method:
import * as Sentry from '@nativescript-community/sentry'; try { // potentially crashy code } catch (error) { Sentry.captureException(error); }
Reporting promise rejectionsReporting promise rejections
To report a promise rejection, use notify() as a part of the catch block:
import * as Sentry from '@nativescript-community/sentry'; new Promise(function(resolve, reject) { /* potentially failing code */ }) .then(function () { /* if the promise is resolved */ }) .catch(function (error) { Sentry.captureException(error); });
Sending diagnostic dataSending diagnostic data
Automatically captured diagnosticsAutomatically captured diagnostics
Bugsnag will automatically capture and attach the following diagnostic data:
- A full stacktrace
- Battery state
- Device model and OS version
- Thread state for all threads
- Release stage (production, debug, etc)
- App running duration in the foreground and/or background
- A device- and vendor-specific identifier
Identifying usersIdentifying users
In order to correlate errors with customer reports, or to see a list of users who experienced each error, it is helpful to capture and display user information. Information set on the Bugsnag client is sent with each error report:
Sentry.setUser({"email": "john.doe@example.com"});
Logging breadcrumbsLogging breadcrumbs
In order to understand what happened in your application before each crash, it can be helpful to leave short log statements that we call breadcrumbs. The last several breadcrumbs are attached to a crash to help diagnose what events lead to the error.
Automatically captured breadcrumbsAutomatically captured breadcrumbs
By default, Bugsnag captures common events including:
- Low memory warnings
- Device rotation (if applicable)
- Menu presentation
- Screenshot capture (not the screenshot itself)
- Undo and redo
- Table view selection
- Window visibility changes
- Non-fatal errors
- Log messages (off by default, see configuration options)
Attaching custom breadcrumbsAttaching custom breadcrumbs
To attach additional breadcrumbs, use the leaveBreadcrumb function:
Sentry.addBreadcrumb({ category: 'ui', message: 'load main view', level: 'info' }); | https://preview.npmjs.com/package/@nativescript-community/sentry | CC-MAIN-2021-39 | en | refinedweb |
Closed Bug 1142171 (splitpanehistory) Opened 7 years ago Closed 6 years ago
Use "split pane styling" for History Panel on Tablets in landscape
Categories
(Firefox for Android Graveyard :: Awesomescreen, defect)
Tracking
(firefox43 fixed, relnote-firefox 43+)
Firefox 43
People
(Reporter: antlam, Assigned: vivek)
References
Details
Attachments
(6 files, 12 obsolete files)
Related to bug 1129171. It makes sense to see if we can use this in our other Panels like Bookmarks.
^ And History too?
Summary: Use "split pane styling" for Bookmarks Panel on Tablets in landscape → Use "split pane styling" for Bookmarks + History Panel on Tablets in landscape
(In reply to Anthony Lam (:antlam) from comment #1) > ^ And History too? I'm re-purposing this to be History only. We can file a new one for Bookmarks.
Alias: splitpanehistory
Assignee: nobody → vivekb.balakrishnan
Status: NEW → ASSIGNED
Hardware: x86 → All
Summary: Use "split pane styling" for Bookmarks + History Panel on Tablets in landscape → Use "split pane styling" for History Panel on Tablets in landscape
* Moved the HistoryAdapter to a separate class * Extracted the common features in HistoryPanel such as the Loader callbacks to the base class * Renamed HistoryPanel to HistoryListPanel
Attachment #8601721 - Flags: review?(nalexander)
* Container Panel defined to hold the history list views.
Attachment #8601725 - Flags: review?(nalexander)
* Split list view created which split the cursor based on the date ranges * Enabled split pane list for Tablets in landscape mode.
Attachment #8601726 - Flags: review?(nalexander)
As per IRC: "I was picturing the left side to be “Today, Yesterday, Last 7 days, April, March, Feb..” like you get when you click “View all history” in desktop firefox"
Flags: needinfo?(vivekb.balakrishnan)
vivek posted a screenshot: and here's a cap of desktop: Honestly, this /looks/ great to me. How about, rather than some number of named months, we go "Last month", "Last year" (and maybe something else for "everything")? vivek, how hard would it be to make 6 months (dynamic) and then "older than 6 months"? (That may not localize well.)
Comment on attachment 8601721 [details] [diff] [review] part1.patch Review of attachment 8601721 [details] [diff] [review]: ----------------------------------------------------------------- License, comments, and some thoughts about how the base vs. derived classes interact, please. But this is pretty mechanical, so r+ and I'll look at a fresher version later. ::: mobile/android/base/home/HistoryAdapter.java @@ +1,2 @@ > +package org.mozilla.gecko.home; > + nit: license. @@ +10,5 @@ > +import org.mozilla.gecko.db.BrowserContract; > + > +import java.util.Date; > + > +public class HistoryAdapter extends MultiTypeCursorAdapter { nit: descriptive comment! What are the types? @@ +22,5 @@ > + private static final long MS_PER_DAY = 86400000; > + private static final long MS_PER_WEEK = MS_PER_DAY * 7; > + > + // The time ranges for each section > + private static enum MostRecentSection { Ah, I see this is not very configurable :( And I see why you had questions about adding sections and cursors for the split-pane implementation. I think one cursor and manual ranges is acceptable even in split-pane. Simplicity! ::: mobile/android/base/home/HistoryBasePanel.java @@ +1,1 @@ > +package org.mozilla.gecko.home; nit: license. @@ +32,5 @@ > +import org.mozilla.gecko.TelemetryContract; > +import org.mozilla.gecko.db.BrowserDB; > + > +/** > + * Fragment backed by <code>HistoryAdapter<code> to displays history tabs sorted by date ranges. Nit: update comment to include discussion of this being a base class specialized by a vanilla list and a split-pane implementation. What does the base class handle? What does the derived class handle? @@ +129,5 @@ > + return mDB.getRecentHistory(cr, HISTORY_LIMIT); > + } > + } > + > + protected void updateUiFromCursor(Cursor c) { I feel like this isn't quite right -- it's not clear how a base class is intended to override this to actually do its UI update.
Attachment #8601721 - Flags: review?(nalexander) → review+? @@ +41,5 @@ > + if (canLoad() && HardwareUtils.isTablet() && (currentFragment = getChildFragmentManager().findFragmentByTag(FRAGMENT_TAG)) != null) { > + if (currentFragment.getArguments().getInt(FRAGMENT_ORIENTATION) != GeckoScreenOrientation.getInstance().getAndroidOrientation()) { > + // As the fragment becomes visible only after onStart callback, we can safely remove it from the back-stack. > + // If a portrait fragment is in the back-stack and then a landscape fragment should be shown, there can > + // be a brief flash as the fragment are replaced. nit: fragments. ::: mobile/android/base/resources/layout/home_history_container_panel.xml @@ +7,5 @@ > + android: + android: + android: > + > + <FrameLayout android:id="@+id/history_panel_container" You have history_container_panel in a bunch of places, and then history_panel_container here. Can we make this just "@+id/container"?
Attachment #8601725 - Flags: review?(nalexander) → review+
Comment on attachment 8601726 [details] [diff] [review] part3.patch Review of attachment 8601726 [details] [diff] [review]: ----------------------------------------------------------------- Just a few notes. I didn't review the tricky cursor handling 'cuz you have a work in progress patch. Looking good! Sorry for the slow review. ::: mobile/android/base/home/HistoryAdapter.java @@ +21,5 @@ > // For the time sections in history > private static final long MS_PER_DAY = 86400000; > private static final long MS_PER_WEEK = MS_PER_DAY * 7; > > // The time ranges for each section protected? And fold these in to the earlier patch. ::: mobile/android/base/home/HistorySplitListPanel.java @@ +99,5 @@ > + mUrlOpenListener.onUrlOpen(url, EnumSet.of(OnUrlOpenListener.Flags.ALLOW_SWITCH_TO_TAB)); > + } > + }); > + > + mItemList.setContextMenuInfoFactory(new HomeContextMenuInfo.Factory() { I feel like we should be able to share some of this between the list and the splitpane implementations. @@ +170,5 @@ > + mRangeAdapter.clear(); > + mItemAdapter.swapCursor(mAdapter.getCursor()); > + selected = null; > + > + final SparseArray<MostRecentSection> mostRecentSections = mAdapter.getmMostRecentSections(); nit: getMostRecentSections. ::: mobile/android/base/moz.build @@ +306,5 @@ > 'home/HistoryAdapter.java', > 'home/HistoryBasePanel.java', > 'home/HistoryContainerPanel.java', > 'home/HistoryListPanel.java', > + 'home/HistorySplitListPanel.java', Try to be consistent with RemoteTabs -- HistorySplitPaneFragment. ::: mobile/android/base/resources/layout/home_history_split_plane_panel.xml @@ +20,5 @@ > + android: > + > + <org.mozilla.gecko.home.HomeListView > + android: + + + android: + android: + android: Can we extract these weights into a shared file? Maybe into dimens.xml? @@ +28,5 @@ > + > + <View > + android: + android: + android: And this color -- I'm sure it's re-used. @@ +39,5 @@ > + android: > + > + </LinearLayout> > + > + <LinearLayout android:layout_width="match_parent" This button seems odd. I wonder if this is where antlam will want it.
Attachment #8601726 - Flags: review?(nalexander) → feedback+
Attachment #8601721 - Attachment is obsolete: true
Flags: needinfo?(vivekb.balakrishnan)
Attachment #8611297 - Flags: review?(nalexander)
Review nits addressed
Attachment #8601725 - Attachment is obsolete: true
Attachment #8611299 - Flags: review?(nalexander)
Styles and split dimensions added to xml files
Attachment #8601726 - Attachment is obsolete: true
Attachment #8611302 - Flags: review?(nalexander)
History sections updated to be similar to that in FF desktop. Section string are localized.
Attachment #8611303 - Flags: review?(nalexander)
(In reply to Nick Alexander :nalexander from comment #9) >? In tablets when the orientation changes the fragment backstack would have the wrong list view. we are overriding loadIfVisible() here to pop that fragment iff it is not the right one from the backstack and load a new fragment for the current configuration.
Comment on attachment 8611303 [details] [diff] [review] part4.patch Review of attachment 8611303 [details] [diff] [review]: ----------------------------------------------------------------- Strings LGTM. ::: mobile/android/base/locales/en-US/android_strings.dtd @@ +49,5 @@ > <!ENTITY bookmark_options "Options"> > > <!ENTITY history_today_section "Today"> > <!ENTITY history_yesterday_section "Yesterday"> > +<!ENTITY history_week_section3 "Last 7 days"> Desktop does this, so this is almost certainly fine, but FYSA: many style guides have numerals below a certain value spelled out, so "Last seven days", "Last 30 days". If you want to be triple-sure, check with UX.
Attachment #8611303 - Flags: review+
Comment on attachment 8611303 [details] [diff] [review] part4.patch Review of attachment 8611303 [details] [diff] [review]: ----------------------------------------------------------------- I've asked for a pretty big rework of this patch, but it's definitely coming along. ::: mobile/android/base/db/LocalBrowserDB.java @@ +690,5 @@ > } > > @Override > public Cursor getRecentHistory(ContentResolver cr, int limit) { > + return cr.query((limit > 0) ? combinedUriWithLimit(limit) : mCombinedUriWithProfile, Ah, I see now. This is dangerous. I don't know what the right thing to do is, but it's not fetching all history. I think rnewman will have a good opinion. ::: mobile/android/base/home/HistoryAdapter.java @@ +30,5 @@ > > // For the time sections in history > private static final long MS_PER_DAY = 86400000; > private static final long MS_PER_WEEK = MS_PER_DAY * 7; > + private static final Calendar FIRST_DAY_OF_CURRENT_MONTH = Calendar.getInstance(); You're not using this in a static way, so it shouldn't be static. I'm quite confused by what you're trying to accomplish here, but let's attack this in stages. First, I think a history adapter should just keep its current time in an instance variable. Each time the cursor updates, the current time should roll forward. Second, can we make the section logic simpler? How about storing the "current time" the adapter knows about like I suggest, and then include a "milliseconds from first time" value for each section, using an enum with values (like)? So we'd have TODAY(0), YESTERDAY(one day in ms, or seconds, or days), WEEK(seven days in unit), ONE_MONTH_AGO(31 days in ...). Oh, urgh, that doesn't account for variable months. Different approach: we include an array of (earliest time, section header string). Each time the cursor is updated, we recreate the array relative to the new time. Then we walk backwards checking times as needed to determine sections. Reasonable? @@ +45,5 @@ > TODAY, > YESTERDAY, > WEEK, > + THIS_MONTH, > + MONTH_AGO, ONE_MONTH_AGO (might as well be consistent). @@ +152,5 @@ > } > > + private String getMonthString(final int monthsBefore) { > + // Shift back calendar month. > + FIRST_DAY_OF_CURRENT_MONTH.add(Calendar.MONTH, -monthsBefore); Nifty, but don't use the static (or the member) for this temporary calculation. @@ +191,5 @@ > if (delta < MS_PER_WEEK) { > return MostRecentSection.WEEK; > } > > + int i = 0; Don't hardcode the 5. I'd like to see this data driven, meaning calculated from some data structure, rather thana encoding days/weeks/months specially. ::: mobile/android/base/home/HistoryBaseFragment.java @@ +114,5 @@ > } > > protected static class HistoryCursorLoader extends SimpleCursorLoader { > // Max number of history results > + private static final int HISTORY_LIMIT = -1; This /definitely/ needs a comment explaining the meaning of things.
Attachment #8611303 - Flags: review?(nalexander) → feedback+
Comment on attachment 8611297 [details] [diff] [review] part1.patch Review of attachment 8611297 [details] [diff] [review]: ----------------------------------------------------------------- Rubber stamp. Looks okay to me!
Attachment #8611297 - Flags: review?(nalexander) → review+
Comment on attachment 8611299 [details] [diff] [review] part2.patch Review of attachment 8611299 [details] [diff] [review]: ----------------------------------------------------------------- Rubber stamp. Looks okay to me!
Attachment #8611299 - Flags: review?(nalexander) → review+
Comment on attachment 8611302 [details] [diff] [review] part3.patch Review of attachment 8611302 [details] [diff] [review]: ----------------------------------------------------------------- Keeping the r? 'cuz I need to get back to this. ::: mobile/android/base/home/HistoryAdapter.java @@ +190,5 @@ > } > } while (c.moveToNext()); > } > > + public SparseArray<MostRecentSection> getMostRecentSections() { Fold this into the original patch. ::: mobile/android/base/home/HistoryBaseFragment.java @@ +129,5 @@ > return mDB.getRecentHistory(cr, HISTORY_LIMIT); > } > } > > + protected HomeContextMenuInfo getHomeContextMenuInfo(final View view, final int position, final long id, final Cursor cursor) { And this fold this into the earlier patch. ::: mobile/android/base/home/HistorySplitPlaneFragment.java @@ +195,5 @@ > + mItemAdapter.swapCursor(mAdapter.getCursor()); > + selected = null; > + > + final SparseArray<MostRecentSection> mostRecentSections = mAdapter.getMostRecentSections(); > + for (int i = 0; i < mostRecentSections.size(); i++) { This is very confusing. I will need to look at this more closely, but I'm quite tired right now so I'm going to leave it for a while.
Attachment #8611302 - Flags: feedback+
A new patch with common functionsrealted to history parsing pulled to base fragment
Attachment #8611297 - Attachment is obsolete: true
Attachment #8611299 - Attachment is obsolete: true
Attachment #8611302 - Attachment is obsolete: true
Attachment #8611303 - Attachment is obsolete: true
Attachment #8611302 - Flags: review?(nalexander)
Added container fragment and placeholder code for split plane fragments
Final part of the patch: Split plane fragment, As discussed over irc, each split plane segments issues separate query localization strings for the sections.
I'm not going to get to this before Whistler, and having the flags in my queue is stressing me out. Let's revisit in July.
Is this something that might be feasible for 43?
Flags: needinfo?(vivekb.balakrishnan)
Flags: needinfo?(vivekb.balakrishnan)
Attachment #8616378 - Flags: review?(s.kaspari)
Agreed with Sebastian, we are targeting 43
Flags: needinfo?(jchaulk)
The patches do not compile using 'mach'. After a quick look it seems like home_history_split_plane_panel.xml accidentally ended up in the crashreporter's resource directory: mobile/android/base/crashreporter/res/layout/home_history_split_plane_panel.xml
Flags: needinfo?(vivekb.balakrishnan)
.
Flags: needinfo?(alam)
Comment on attachment 8616378 [details] [diff] [review] part1.patch Review of attachment 8616378 [details] [diff] [review]: ----------------------------------------------------------------- This split pane is so much more fun to use on tablets then just having a simple list! :) There are some NITs but it seems like most of them have already been in HistoryPanel before. So I guess there's no pressing need to get rid of them. However if you agree and if some further iterations are needed then feel free to fix them too, now that we split and move the code around. ::: mobile/android/base/home/HistoryBaseFragment.java @@ +44,5 @@ > + // For the time sections in history > + private static final long MS_PER_DAY = 86400000; > + private static final long MS_PER_WEEK = MS_PER_DAY * 7; > + > + // Logging tag name NIT: I feel like this comment is not adding much additional information. I usually tend to pick a very descriptive name for the class member and only add comments if additional clarification is needed. @@ +55,5 @@ > + protected static final String FORMAT_S1 = "%1$s"; > + protected static final String FORMAT_S2 = "%2$s"; > + > + // The button view for clearing browsing history. > + protected View mClearHistoryButton; NIT: Same here: You picked the perfect name for the button and it's absolutely clear what it should do. I don't think the comment is needed. @@ +245,5 @@ > + } > + > + protected static class HistoryCursorLoader extends SimpleCursorLoader { > + // Max number of history results > + private static final int HISTORY_LIMIT = 100; If we just have a simple history list - like before - then limiting the list makes sense. However now that we split them into specific groups this will hide some data in between. For example "Last 7 days" might be cut-off after 100 entries but we might show the full list of let's say 75 entries for 'May'. This creates some 'invisible' gaps. I wonder if this is a problem. Regardless of this I feel like 100 is a quite small number of items for a scrolling list in general.
Re-based against the latest central and comment nits corrected
Attachment #8616378 - Attachment is obsolete: true
Attachment #8616378 - Flags: review?(s.kaspari)
Flags: needinfo?(vivekb.balakrishnan)
Attachment #8636612 - Flags: review?(s.kaspari)
Re-base and reviewer changed in comment line
Attachment #8616379 - Attachment is obsolete: true
Attachment #8636613 - Flags: review?(s.kaspari)
Moved the layout to res/layout. @Sebastian: Can you please try now if it compiles for you.
Attachment #8616380 - Attachment is obsolete: true
Attachment #8636615 - Flags: review?(s.kaspari)
(In reply to :Sebastian Kaspari from comment #29) > Created attachment 8636514 [details] > history_tablet.png > > . I agree, but we should try to handle the split pane issue first. We can file a follow up related to bug 1091826 for the empty state. As for the touch targets, I think we'll need to make them the same size (and look similar) as bug 1129171 and also inherit the tail-less arrow. I don't have my tablet on my right now but I think we even enlarged it to match the height of the links on the right hand side. Can we see how that looks?
Flags: needinfo?(alam) → needinfo?(s.kaspari)
Patch updated with Antlam's UI changes Sample screenshots:
Attachment #8636615 - Attachment is obsolete: true
Attachment #8636615 - Flags: review?(s.kaspari)
Attachment #8636760 - Flags: review?(s.kaspari)
Attachment #8636760 - Flags: feedback?(alam)
Comment on attachment 8636612 [details] [diff] [review] part1.patch Review of attachment 8636612 [details] [diff] [review]: ----------------------------------------------------------------- LGTM! ::: mobile/android/base/home/HistoryListFragment.java @@ +204,5 @@ > > mContext = context; > > // Initialize map of history sections > + mMostRecentSections = new SparseArray<>(); I'm keen to see if this will compile on the builders as <> is a feature of Java 7.
Attachment #8636612 - Flags: review?(s.kaspari) → review+
Comment on attachment 8636613 [details] [diff] [review] part2.patch Review of attachment 8636613 [details] [diff] [review]: ----------------------------------------------------------------- I feel like the HistoryContainerPanel might be overkill. Already looking at patch 3: Do you think the HistorySplitPlaneFragment could handle both cases: There's always a history list and there's an optional range list. It's more or less two different layouts that need to be loaded depending on device. If there's a range list then clicks on it will change the history list. If there's no range list then there's only a history list. So yeah, do you think the functionality could be shrunk into a single Fragment using Range/History components? It resembles the behavior you'd implement with non-"support fragments" and resource qualifiers: I'd like to hear your opinion on that. But I also don't want to make everything more complicated just before the finish line! :) ::: mobile/android/base/home/HistoryContainerPanel.java @@ +17,5 @@ > + > +/** > + * A <code>HomeFragment</code> that, holds the History list fragment for the current device and orientation. > + */ > +public class HistoryContainerPanel extends HomeFragment { To be consistent with the other names, we should name this HistoryContainerFragment. @@ +18,5 @@ > +/** > + * A <code>HomeFragment</code> that, holds the History list fragment for the current device and orientation. > + */ > +public class HistoryContainerPanel extends HomeFragment { > + private static final String FRAGMENT_TAG = "backstack_tag"; This is a bit confusing name (backstack_tag) because the tag is not directly related to the backstack but identifying the fragment. @@ +72,5 @@ > + .commitAllowingStateLoss(); > + } > + > + private Fragment getFragmentForOrientation() { > + // TODO: Create splitpane here based on orientation for tablets. I see that this TODO is handled in patch 3. Feel free to squash them to a single commit to avoid reviewing intermediate states.
Attachment #8636613 - Flags: review?(s.kaspari) → feedback+
Comment on attachment 8636760 [details] [diff] [review] part3.patch Review of attachment 8636760 [details] [diff] [review]: ----------------------------------------------------------------- LGTM, just some nits. ::: mobile/android/base/home/HistorySplitPlaneFragment.java @@ +34,5 @@ > + * Fragment that displays other date ranges and tabs in two separate <code>ListView<code> instances. > + * <p/> > + * This is intended to be used in landscape mode on tablets. > + */ > +public class HistorySplitPlaneFragment extends HistoryBaseFragment { Should this be named Pane instead of Plane? ::: mobile/android/base/resources/layout/home_history_split_plane_panel.xml @@ +42,5 @@ > + </LinearLayout> > + > + <LinearLayout android: + android: + android: Does this LinearLayout serve any purpose? We could stretch the button to match_parent, couldn't we? ::: mobile/android/base/resources/values/dimens.xml @@ +215,5 @@ > <item name="match_parent" type="dimen">-1</item> > <item name="wrap_content" type="dimen">-2</item> > > + <item name="split_plane_left_pane_weight" format="float" type="dimen">0.32</item> > + <item name="split_plane_right_pane_weight" format="float" type="dimen">0.68</item> I'm curious to know how you came up with these numbers. I'd probably use a fixed size for the 'range' pane and let the 'history list' pane use whatever is left. ::: mobile/android/base/resources/values/styles.xml @@ +556,5 @@ > <item name="android:drawSelectorOnTop">true</item> > </style> > > + <style name="Widget.HistoryListView" parent="Widget.HomeListView"> > + <item name="android:childDivider">#E7ECF0</item> Now that we have at least two widgets using this color (with bookmarks maybe following too), let's define it in colors.xml
Attachment #8636760 - Flags: review?(s.kaspari) → review+
This is looking great! Let's just discuss the fragment 'fusion' mentioned above. Either here or on IRC. Let's also take care of filing follow-up bugs for things like: * Empty state for things like 'Older than 6 months' (see above) * Maybe we should move "Clear history" below the right pane instead of below both (debatable) * Let's try to use just the time limits instead of a hard limit to avoid history gaps * Let's do this split pane thing for bookmarks too! (As mentioned in the first bug)
Flags: needinfo?(s.kaspari)
Oh, and one small thing: Please use r=sebastian instead of r=s.kaspari :)
Comment on attachment 8636760 [details] [diff] [review] part3.patch The screenshot is looking good. + for progress! Can we use the same type spec as the device name? Also, what's the padding to the left currently spec'd at?
Flags: needinfo?(vivekb.balakrishnan)
Attachment #8636760 - Flags: feedback?(alam) → feedback+
Bug 1142171 - Pre: Refactor HistoryAdapter to a separate class and defined section ranges r?sebastian.
Attachment #8647236 - Flags: review?(s.kaspari)
Bug 1142171: Split history List view for tablet landscape mode r?sebastian.
Attachment #8647237 - Flags: review?(s.kaspari)
screenshot for updated layout: @antlam: I have used margin 16dp. should center the text?
Flags: needinfo?(vivekb.balakrishnan) → needinfo?(alam)
Looks good! Can we do 15dp? that would match our padding elsewhere. Vivek, could I get a build to test this on my device please? the screenshot looks a bit low res :) Thanks!
Flags: needinfo?(alam) → needinfo?(vivekb.balakrishnan)
Hi Anthony, Please find the apk at I have changed margin to 15dp and centered the text
Flags: needinfo?(vivekb.balakrishnan)
Thanks Vivek, I just checked it out!I think we need to keep these labels left aligned, with 15dp padding on the left and centered vertically (the arrow icon as well needs to be centered vertically). I notice the padding on top and beneath are not even in your build (tested on my N9). Finally, can we also follow the type specifications in the "Synced Tabs" panel? I.e. the states for "selected" and "unselected" (for the dates on the left) in your build are not the same as the "Synced Tabs" panel. I think "selected" should be Roboto Light, 14sp, #363B40 (Text and tabs tray grey in our palette). And "unselected" would be Roboto Light, 14sp, #BFBFBF (disabled grey I think). You can probably double check this from our work in the synced tabs panel split pane :) Thanks vivek! I think that should do it :)
Flags: needinfo?(vivekb.balakrishnan)
Comment on attachment 8647236 [details] MozReview Request: Bug 1142171 - Pre: Refactor HistoryAdapter to a separate class and defined section ranges r?sebastian. Ship It!
Comment on attachment 8647237 [details] MozReview Request: Bug 1142171: Split history List view for tablet landscape mode r?sebastian. Awesome refactoring! The code looks much simpler and is easier to follow. :) I added some comments/questions to the review but that's nothing that should stop this from landing, so r+. ::: mobile/android/base/home/HistoryItemAdapter.java:18 (Diff revision 1) > + * A Cursor adapter implementation that always iterate over the start to start + length - 1 items. Isn't this Adapter independent from any "start" and just always creates views for everything in the cursor? ::: mobile/android/base/home/HistoryItemAdapter.java:35 (Diff revision 1) > + // Return view from position relative to the start. Same question: What start? ::: mobile/android/base/home/HistoryPanel.java:127 (Diff revision 1) > + } I'd let the Android system make this decision using resource qualifiers: Naming both files the same, putting the default in res/layout and the split pane version into res/layout-sw600dp-land. ::: mobile/android/base/home/HistoryPanel.java:137 (Diff revision 1) > + if(mRangeList != null) { NIT: Space: if_( Also: If this is used more often in this class then I'd create a boolean like isSplitPane to make the code more readable. ::: mobile/android/base/resources/values/dimens.xml:227 (Diff revision 1) > + <item name="split_plane_right_pane_weight" format="float" type="dimen">0.68</item> I guess I've asked this before: How did you come up with these numbers? My instinct would be to use a fixed size for the left (range) pane and let the right pane use everything that's left.
Attachment #8647237 - Flags: review?(s.kaspari) → review+
Could I see a screenshot after the changes, Vivek? :)
Comment on attachment 8647237 [details] MozReview Request: Bug 1142171: Split history List view for tablet landscape mode r?sebastian. Bug 1142171: Split history List view for tablet landscape mode r?sebastian.
@Antlam : can you please try this apk
Flags: needinfo?(vivekb.balakrishnan)
(In reply to Vivek Balakrishnan[:vivek] from comment #52) > @Antlam : can you please try this apk >. > apk?dl=0 Thanks Vivek, I'll not be in the office next week so I'll have to give this build a try when I return. I'll try to locate a tablet where I'll be as well. Stay tuned!
Flags: needinfo?(alam)
Sorry for the delay Vivek, But, this looks great! Two points of feedback and then we can get it in! :) 1) Apply the same "About page header grey" to the backgrounds of the left column for "Today", "Yesterday", etc... 2) Keep the same font _weight_ and _size_ (Roboto light, 14sp ) for active and inactive (just like the "Device name" in the Synced tabs panel where only color changes) Thanks a lot vivek, appreciate it! this will be a great improvement
Flags: needinfo?(alam) → needinfo?(vivekb.balakrishnan)
Comment on attachment 8647236 [details] MozReview Request: Bug 1142171 - Pre: Refactor HistoryAdapter to a separate class and defined section ranges r?sebastian. Bug 1142171 - Pre: Refactor HistoryAdapter to a separate class and defined section ranges r?sebastian.
Bug 1142171: Split history List view for tablet landscape mode r?sebastian.
Attachment #8656161 - Flags: review?(s.kaspari)
@Antlam: I have addressed your feedback in the latest. Can you please let me know if any other task is pending. The apks are at
Flags: needinfo?(vivekb.balakrishnan) → needinfo?(alam)
@Sebastian: I had rebased the patch on top of latest fx-team and I would be grateful if you can give a quick re-review.
Flags: needinfo?(s.kaspari)
Looks good!
Flags: needinfo?(alam)
Comment on attachment 8656161 [details] MozReview Request: Bug 1142171: Split history List view for tablet landscape mode r?sebastian. Great! Tested it on my tablet too. Works great. We recently added code to hide "clear history" if a specific restriction is enabled. This code survived the rebase too. Let's ship it. :)
Attachment #8656161 - Flags: review?(s.kaspari) → review+
Status: ASSIGNED → RESOLVED
Closed: 6 years ago
status-firefox43: --- → fixed
Resolution: --- → FIXED
Target Milestone: --- → Firefox 43
Release Note Request (optional, but appreciated) [Why is this notable]: user-facing new feature, suggested by dev team [Suggested wording]: New split pane styling for History panel on tablets in landscape mode [Links (documentation, blog post, etc)]:
relnote-firefox: --- → 43+
All follow-ups we talked about are now filed and should be blocking this bug.
Flags: needinfo?(s.kaspari)
Flags: needinfo?(jchaulk)
Product: Firefox for Android → Firefox for Android Graveyard | https://bugzilla.mozilla.org/show_bug.cgi?id=1142171 | CC-MAIN-2021-39 | en | refinedweb |
How to use Multilingual App Toolkit in Universal Apps
- Posted in:
- internationalization
- .net
- windows phone
- windows rt
Everyone is excited about the new Universal Apps. I can now have a new type of project, called a Shared project, where I can put all the common files shared between a Windows 8.1 and Windows Phone 8.1 project. This is a better way around the “Add as a Link” option we had before. But universal apps is more than just a shared project. It seems that the APIs used by both Windows and Windows Phone are converging into one. Granted there still a lot of work to do and I’m not sure if there will be a 100% compatibility between the two frameworks, but this is a great step.
I’m going to talk about how to localize a universal app. In my article Internationalization of a Cross Platform Application I explain how to use the Multilingual App Toolkit in a PCL project to localize an application targeted for multiple platforms (Windows, Windows Phone, Android and iOS). But when I tried to apply the steps in the article to a Universal App I run into some problems. I will still base my localization on resource files, the thing is where do I put these? Should I put them in the new Shared project? or should I keep using PCL projects? Let’s first review our main goals:
- To have a single place where we can specify strings and have these strings shared by all the platform projects.
- Strings can be used in the UI as well as programmatically
- Use the Multilingual App Toolkit to handle all the translations
Resource files in Shared project
When I knew about the new shared project type I thought “great, now I can put my resource files in the shared project”. Well, it turns out you can, but this is not the best approach. To explain why let’s see how our goals stand when we use resource files in shared projects.
As mentioned before, universal apps are basically three projects: a project for Windows 8.1, a project for Windows Phone 8.1 and a Shared project. By putting resource files in the shared project they will be shared by both the Windows and Windows Phone projects. Our first goal is ok.
The convergence of the frameworks between Windows and Windows Phone is also applied to the use of resources. Windows apps (aka Windows Store or WinRT apps) use the .resw resource type. On the other hand, Windows Phone Silverlight apps (the “Silverlight” suffix was added to differentiate them from the new Windows Phone apps which use the WinPRT framework) use .resx resource files. Now, both Windows 8.1 and Windows Phone 8.1 use .resw files..resw files can be used in XAML by specifying the x:Uid attribute in XAML components (this was not possible with .resx files), but these resource files do not have a strong type associated to them (as in the case of .resx resource files). This means that we cannot use resource strings programmatically. You can create a strong type associated to .resw files by using ResW File Code Generator, but it turns out that this extension doesn’t work if the resource is in the shared project. So, our second goal doesn’t stand.
The Multilingual App Toolkit cannot be enabled for shared projects. You have to enable MAT in both Windows and Windows Phone projects. It turns out that the decision of the MAT team regarding universal app was that they “decided to enable MAT based on the specific project instead of the shared project” (see this blog post for details). This means that I would have to do translations twice, one for each project. When you enable MAT in both projects you’re solution will be something like this:
.xlf files are duplicated. So, yes we can use MAT on universal app (our third goal is ok) but since we can’t use it on the shared project our first goal doesn’t stand.
Finally, our goals stand as this:
- To have a single place where we can specify strings and have these strings shared by all the platform projects: No
- Strings can be used in the UI as well as programmatically: No
- Use the Multilingual App Toolkit to handle all the translations: Yes
In summary, having a resource file in the shared project means that I will not be able to use resource strings programmatically and also that I will have to deal with duplicate translations and manual steps to keep these translations up to date. So, resource files in shared projects: not the best approach.
Resource files in PCL project
Our second option is to put resource files in a PCL project. Let’s see how this options stands with our goals. You can perfectly add a PCL project to a universal app solution:
When you do this Visual Studio automatically sets the targets for the PCL project to “Windows 8.1” and “Windows Phone 8.1”:
I suggest to change the “Default namespace” of the PCL project to match the default namespace of the other projects as well. In the PCL project, create a folder structure that is compatible with the project’s default language, in my case “en-US”. Add a new resource (.resw) file to the folder. You should have something like this:
(note: you can change the PCL default language by editing the PCL project file. Look for the node DefaultLanguage)
It is required for the resource file to be inside a folder with a name that matches the project default language, otherwise MAT will not find any strings and the .xlf files will not be generated.
Since the targets for the PCL are “Windows 8.1” and “Windows Phone 8.1” the resource files you can add are of type .resw. We already explained that .resw resources do not have an associated strong type and we cannot use strings programmatically. To work around this we will use ResW File Code Generator: in the .resw file properties we will specify values for the properties “Custom Tool” and “Custom Tool Namespace” to be “ReswFileCodeGenerator” and the namespace of our project, respectively:
This will generate a strong type associated with the resource file at compile time.
You can follow the approach explained in How to use the Multilingual App Toolkit (MAT) in a Portable Class Library (PCL) project to see how to use MAT on a PCL:
- Enable MAT for the PCL project
- Add translation languages to the project (in my case I’m adding “es” and “it”)
Your PCL project should now look as this:
At this point, when you compile the PCL project, all the strings in the default resource file will be copied to the .xlf files by MAT. You can now start translating using MAT.
There are some steps we need to do in order to finish this:
- Make sure you add the PCL project as a reference to both Windows and Windows Phone projects
- In the shared folder, create a structure such as the following:
Basically you need to create a resource file for each language you support and this resource file needs to be inside a folder with the name of the locale. The .resw files in this shared folder structure can be empty. This is a requirement of both Windows and Windows Phone projects in order to know that the application supports all those languages. At this point you can start using resource strings in the UI as well as programmatically (see more details about how to use PCL resources in cross platform apps by reading the article Internationalization of a Cross Platform Application)
Let’s review if we have accomplished our goals:
- To have a single place where we can specify strings and have these strings shared by all the platform projects: Yes
- Strings can be used in the UI as well as programmatically: Yes
- Use the Multilingual App Toolkit to handle all the translations: Yes
Sample App
You can find a sample VS project here:
Conclusion
In summary, having our resources in a PCL project is still the best option. Shared projects is an excellent idea, but it still lacks support for some other features, as in this case, to be able to handle resource files using MAT and to have .resw files generate a strong type. Let’s hope that the guys in the MAT team provide a way to use MAT in shared projects in the future. In the meantime, let them know that we need this by voting on the user voice idea. | http://bloggiovannimodica.azurewebsites.net/?category=internationalization | CC-MAIN-2018-43 | en | refinedweb |
Ruthless self-denial is the non sun qua of creativity’-We never ever thought that we would be
proud to calculate the statistics of ‘rat race’ as to us, transforming the education was our only
most objective.
they least bother regarding number game, but really very serious regarding a game
programming assigned by a student ,as objective is very simple ,the support system to the
student must be accurate, the student should not suffer in any point.
That is why in our third year of ‘Reliable Tutor’,I can still able to recall that faint voice of
‘John’, he called us shivering ‘Pristley tomorrow is my last date of submitting assignment,
but concerned online tutor has refused to submit me the assignment, can you help?’ It was
really, really tough at that moment ,but our tutor, Shouvonik, spending his entire night
finished that assignment and rescued the student from a ‘critical fall’; we are happy with this
as we have justified our profession, and that is only our job.
they are very pleased when our first student who approached to us when he newly joined to
the under graduate program, and in his third year he has assigned to us his major project
spelling to us ‘I am completely tension free as I have given the responsibility to you’.
Expertise
Any kind of assignment helps for University students to PHD students with our best qualified
tutors. We are expert in the field of complete portfolio of assignment help as well as online
tutoring. Our quality team is monitoring 24*7 with our tutors to give the best satisfaction to
student. We take care each and every student till he completely satisfy with provided
solution.
Services
Computer Science Assignment Help
Matlab Assignment Help
Physics Assignment Help
Biology Assignment Help
English Assignment Help
Economics Assignment Help
Academic Assignment Help
HR Assignment Help
Programming Assignment Help
Engineering Assignment Help
Project Assistance
Business Writing
Management Writing
Thesis Writing
Exam Preparation
Online Tutoring
Workshop / Intern Ship
Industrial Training
Assignment help
You are frustrated with your assignment . Do not have time to do by own . Facing problems
in preparing Thesis or Dissertation ?? No need to worry about that. Reliabletutors.com is the
perfect place to help you.
They offer 24/7 online support to their customer to give the best satisfaction. Their skillful
experts are there to help us till we are not satisfied.
they have qualified experts in maximum subjects having minimum Master degree in
respective fields. They are well trained in online tutoring filed and know how to satisfy our
students. they are having experts in Academic, Management, Programming, Engineering,
Business studies and other subjects too.
We are an ongoing assignment help provider in India having world class resources which
make learning both fun and easy.
Assignment help areas:
Academic Subjects:
Engineering Subjects:
Programming Help:
Business Studies:
Business studies
References
Academic knwlege
Dissertation mentoring provided by us guarantee that your dissertation is exclusive and never being suffered by plagiarism. ready to be submitted. proper design and format and the given guideline point by point giving the birth of an ideal dissertation. output is a justified high marks gaining smart creature. world famous scientists also at a corner of student age gain assistance from their teacher. they offer a unique. every thesis writing goes through a life cycle and we guide our students in each stage of it. self-sufficient package to the students which starts parallel movement with the students from the nascent stage (topic selection). even . whether it is selection of topic or whether it is assigning the respective potential mentor drafting the proposal. mentor assigning till the project gets . we take your tension on us leaving you hackle free. it is always difficult to construct a dissertation. rest gets our nourishing. How Reliable Tutors handle your dissertations? We absolutely take care at the time of writing dissertations. actual style. Nothing wrong in it. all have gained high marks and satisfied the need of the students in India and abroad. Our personalized solving methods make student capable gain in-depth knowledge of subjects Thesis help For a student. Your job is to send the topic and instruction set. A story of Success their teachers and drafter till time have completed around 300 dissertations for the students. We offer the best solution in online assignment help to our students across the globe. .Type of company After lot of research in the field of e-learning.There is no exception of it. we established the company Reliable Tutors with best qualified tutors to satisfy our students. As you know. the thesis. A student in his student age at any point of time at least once takes support from his/her teacher . as simply this matter is unavoidable particularly for designing thesis that is why ‘mentor’ this terminology originated.
Engineering students submit their project/ thesis in the final year of their study.results. Thesis Writing Thesis is the passport of a Master’s student to enter into the world of their deserved profession. but in reality the nature and complexity of the task is very high. procedures and data collection). statistical analysis. When you are here. conclusion. measures. You can get this superb service very easily only by filling an online form.discussion.submitted for wining a high score. reviewing the literature. in a very short time will help you refocus and prepare significant progress on your PHD thesis. At Reliable Tutors. They have to represent various modules of their thesis in front of the examiner and this part is really delegate and sensitive as without the high score in the project/thesis they are not . Avail our dissertation help to seek professional writers working on your paper marking success. The steps involved in such tedious task include. Approval of the draft or document It seems very simple. problem statement. If you are confused about selecting dissertation topic then get help here on how to select topics and proceed right from the desk of our expertise. The process of thesis research involves this life cycle Proposal Drafting Approval Conducting the study process Writing the entire abstract and body. and it is tedious to accomplish each and every step with accuracy. you don’t have to be bothered as you would start making the ladder of trust and hope in us as soon as you approach us with your thesis writing problems. research question(s) and research hypothesis development. interpretation). identification of topic. Without it they are incomplete to their professional life. as it is a mandatory. data entry and screening. (data analysis preparation.recommendation. we understand this pain point and hence so much cautious . Engineering thesis We accept Engineering Dissertation and projects (major and minor both) as well. research design (Sampling.particular and specific towards the selection of the topic and following guideline hop by hop.
innovative. services include: Dissertation editing services Thesis editing services SPSS / SAS help services Formatting. Hence. topic selection for an engineering student is a touchy issue. but in reality the native or foreign professional world to them asks specific topic. technical students can educate themselves with various resources during their research paper writing. Engineering Dissertation Services: Semiconductor Devices and Circuits.eligible for GRE or entry in profession. particular and well-informed about various engineering subjects. without plagiarism and fed with self-sufficient idea thesis. They can choose any technical topic for their project/thesis. At Reliable Tutors. Analog Electronic Circuits Analog Integrated Circuits Analog VLSI Design Electronic Circuits Physics and Modeling of Semiconductor Devices Television and Video Engineering Electrical and Electronics . We specifically focus on it and strongly prepare them for defending Viva voce increasing their level of confidence (‘confidential defense’). Post doctoral . talented. Our writers who handle engineering projects are highly qualified. Reliable Tutors has in-house internal committee which consists of PhD holders for writing and as research advisors. Proof reading and Translating Rephrasing [Free of plagiarism] Dissertation writers and tutors at Reliable Tutors Our tutors are very much particular to engineer complete. Our unique methods helped hundreds of scholars to complete and submit their thesis successfully.
and have mentioned below step by step process how thing works: 1. 6. following the above mentioned process when payment is finished. Teachers mention the details of subject. find slot and schedule . from Reliable Tutor confirmation email goes to student mail box. teacher confirms the receiving of assignment/or share the lesson plan after Reliable Tutor getting an advance payment (usually 50% of the quote) in lieu of primary invoice. If all would tally. 4. 2. Create your own account. This payment part is committed either via Paypal or via credit card/online transaction 5. Students matches the quality issue and pricing part by chatting 3. After receiving an assignment. reliable Tutor sends the completed assignment by two way hand shaking method.D holding PhD with rich experience in research. or seeking the subject plan. Browse the topic by a search using a key word for example ‘Micro-programming ’. then generates secondary invoice for rest payment. Students Community How learning begins? 1. Students and Teachers meet online. and University of Birmingham. Specialization of/Work Culture in the training organization. 7. Student quotes the price and schedule in the next stage. The teacher and student once again chat at the day of schedule time ends either via Skype or Google Chat or by direct calling in accordance with both parties comfort-ability. 3. London School of Business. Send request message embedding the desire assignment as an attachment. 2. specialty and pricing for an assignment/subject in web. Some of our writers are trained at Harvard School. When Reliable Tutor confirms the completion of assignment.fellows and M.
If you are stuck with your project or wanna make a project for your future use just talk to us or chat with our representative. In few cases like Real Time System there is no difference between implementation and maintenance as maintenance is complimentary to implementation. once fails system is crashed hence here the life cycle of the project called ‘Spiral Model’ . documentation. We are here to assist you in any project where programming tool is no matter whether it is C or Lua .This is more delegate and difficult to handle . cover letter.A self sufficient complete project is that which when being studied by any other software engineer apart from the project owner can understand. PROJECT ASSISTANCE Any technical project consists of two things a) Abstract b) Detailed documentation. We usually provide the orthodox support to our students following the rule of software engineering. and then the original project life cycle begins.4. Only thing we can assure you is SATISFACTION insuring the score High. Wait for token message of acceptance from Reliable Tutor. power point/flash presentation etc. complete portfolio of project management like source codes.Our think tank is efficient enough to take care any technology existing on the earth.Enjoy your lesson. Once abstract being approved. receive the confirmation of acknowledging the assignment or lesson plan. This the complete life period and called by the language of software engineering ‘water fall model’ . 5. As we believe certain code snippet or flip is not a project. . A project is defined as a complete project when it can give the birth of its successor that is why ‘life cycle’ this term is introduced in project. Reliable Tutor’s team is ready to help you to solve your final year project. reuse and generate a new project. Finish (only 5 steps). we will guide you with our expertise and knowledge.
the result is undefined and difficult to predict. Multithreaded is the path of execution for a program to perform several tasks simultaneously within a program. a memory leak occurs. This can be partially remedied by the use of smart pointers. It is intended to let application developers "write once. Java is as of 2012 one of the most popular programming languages in use. Note that garbage collection does not prevent "logical" memory leaks.Technology Learnt Java is a programming language originally developed by James Gosling at Sun Microsystems (which has since merged into Oracle Corporation) and released in 1995 as a core component of Sun Microsystems' Java platform. In some languages. If the program does not deallocate an object. Java is a generalpurpose. Areas of Application World Wide Web Applets . operating system-specific procedures have to be called in order to work on multithreading.Java supports multithreaded. or explicitly allocated and deallocated from the heap. object-oriented language that is specifically designed to have as few implementation dependencies as possible. concurrent. as Java compilers are able to detect many error problem in program during the execution of respective program code. One of the ideas behind Java's automatic memory management model is that programmers can be spared the burden of having to perform manual memory management. The language derives much of itssyntax from C and C++ but has a simpler object model and fewer low-level facilities. . Java emphasis on checking for possible errors. particularly for client-server web applications. and the program is likely to become unstable and/or crash. but these add overhead and complexity. with a reported 10 million users. If the program attempts to access or deallocate memory that has already been deallocated. The java come with the concept of Multithreaded Program.e. i.class-based. In the latter case the responsibility of managing memory resides with the programmer. In other languages. run anywhere" (WORA). those where the memory is still referenced but never used. memory for the creation of objects is implicitly allocated on the stack. meaning that code that runs on one platform does not need to be recompiled to run on another. Java applications are typically compiled to bytecode (class file) that can run on any Java Virtual Machine (JVM) regardless of computer architecture.
Java is fast. From laptops to datacenters. Java is object-oriented. game consoles to scientific supercomputers. and business applications. compiler. Java is platform-independent and flexible in nature. It is the underlying technology that powers state-of-the-art programs including utilities.Java is secure. easy to write. interpreter and runtime environment are securable . that is used to build modular programs and reusable code in other application. and on billions of devices worldwide. Java works on distributed environment. Java emphasis on checking for possible errors. as Java compilers are able to detect many error problem in program during the execution of respective program code. secure. cell phones to the Internet. Robust means reliability. and reliable. Why do I need Java? There are lots of applications and websites that won't work unless you have Java installed. operating system-specific procedures have to be called in order to work on multithreading. One of the ideas behind Java's automatic memory management model is that programmers can be spared the burden .Java is robust.Java supports multithreaded. In other languages. The java come with the concept of Multithreaded Program. easy to design . games. Java is everywhere What is the advantages of java? Java is simple. The Java language. debug. Multithreaded is the path of execution for a program to perform several tasks simultaneously within a program. It is designed to work on distributed computing . Any network programs in Java is same as sending and receiving data to and from a file. and therefore easy to compile. including mobile and TV devices. Java runs on more than 850 million personal computers worldwide. and more are created every day. and learn than any other programming languages. The most significant feature of Java is to run a program easily from one computer system to another. Cross-Platform Application Development Other Network Applications What is Java technology and why do I need it? Java is a programming language and computing platform first released by Sun Microsystems in 1995.
a memory leak occurs. and the Java runtime is responsible for recovering the memory once objects are no longer in use. It should be "architecture-neutral and portable" 4. It should execute with "high performance" 5. memory for the creation of objects is implicitly allocated on the stack. If methods for a nonexistent object are called. or .of having to perform manual memory management. memory for the creation of objects is implicitly allocated on the stack. threaded. If the program does not deallocate an object.e. It should be "interpreted. or explicitly allocated and deallocated from the heap. In some languages. It should be "simple. In the latter case the responsibility of managing memory resides with the programmer.[28][29] One of the ideas behind Java's automatic memory management model is that programmers can be spared the burden of having to perform manual memory management. the unreachable memory becomes eligible to be freed automatically by the garbage collector. This can be partially remedied by the use of smart pointers. and dynamic" Java uses Automatic memory management Java uses an automatic garbage collector to manage memory in the object lifecycle. Principals There were five primary goals in the creation of the Java language: 1. Something similar to a memory leak may still occur if a programmer's code holds a reference to an object that is no longer needed. Note that garbage collection does not prevent "logical" memory leaks. It should be "robust and secure" 3. The programmer determines when objects are created. the result is undefined and difficult to predict. i. object-oriented and familiar" 2. and the program is likely to become unstable and/or crash. typically when objects that are no longer needed are stored in containers that are still in use. those where the memory is still referenced but never used. a "null pointer exception" is thrown. but these add overhead and complexity. In some languages. Once no references to an object remain. If the program attempts to access or deallocate memory that has already been deallocated.
It is guaranteed to be triggered if there is insufficient free memory on the heap to allocate a new object. Interpreter. Explicit memory management is not possible in Java. and the java doc documentation tool. it will occur when a program is idle. but these add overhead and complexity. It provides basic objects and interface to networking and security. Graphical User Interface Toolkits: The Swing and Java 2D toolkits provide us the feature of Graphical User Interfaces (GUIs). and documenting your applications. those where the memory is still referenced but never used. as commonly true for objects (but seeEscape analysis). as of Java 5. and much more. It gives a wide collection of useful classes. autoboxing enables programmers to proceed as if primitive types were instances of their wrapper class. to XML generation and database access. If the program attempts to access or deallocate memory that has already been deallocated. Ideally. where object addresses and unsigned integers (usually long integers) can be used interchangeably. In the latter case the responsibility of managing memory resides with the programmer.e. If the program does not deallocate an object. Application Programming Interface (API): The API provides the core functionality of the Java programming language. JDK Tools: The JDK tools provide compiling. Garbage collection may happen at any time. . This allows the garbage collector to relocate referenced objects and ensures type safety and security. Values of primitive types are either stored directly in fields (for objects) or on the stack (for methods) rather than on the heap. Because of this. Java does not support C/C++ style pointer arithmetic. debugging. Note that garbage collection does not prevent "logical" memory leaks. which is further used in your own applications. Deployment Technologies: The JDK software provides two type of deployment technology such as the Java Web Start software and Java Plug-In software for deploying your applications to end users. the result is undefined and difficult to predict. a memory leak occurs. The main tools used are the Javac compiler the java launcher. monitoring. and the program is likely to become unstable and/or crash. Java was not considered to be a pure object-oriented programming language. This was a conscious decision by Java's designers for performance reasons. As in C++ and some other object-oriented languages. variables of Java's primitive data types are not objects. This can be partially remedied by the use of smart pointers. running. this can cause a program to stall momentarily.explicitly allocated and deallocated from the heap.0. However. i.
JDBC API. Graphical User Interface Toolkits: The Swing and Java 2D toolkits provide us the feature of Graphical User Interfaces (GUIs).") API. monitoring. Java was built almost exclusively as an object-oriented language.Java contains multiple types of garbage collectors. Integrated Libraries: Integrated with various libraries such as the Java IDL API. debugging. with the exception of the primitive data types (integers. On full implementation of the Java platform gives you the following features: JDK Tools: The JDK tools provide compiling. Java RMI.N. Java uses similar commenting methods to C++. Interpreter. which are not classes for performance reasons. HotSpot uses the Concurrent Mark Sweep collector. and everything is an object. which combines the syntax for structured. All code is written inside a class. Java Technology Works Java is a high-level programming language and powerful software platform. By default. Unlike C++. there are also several other garbage collectors that can be used to manage the Heap.D. generic. Unlike C++. The main tools used are the Javac compiler the java launcher. which is further used in your own applications. and characters). It gives a wide collection of useful classes. floating-point numbers. There are three different styles of comments: a single line style marked with two slashes (//). and object-oriented programming. Application Programming Interface (API): The API provides the core functionality of the Java programming language. and much more. and the java doc documentation tool. Java Naming and Directory Interface TM ("J. Java does not support operator overloading or multiple inheritance for classes. boolean values. It provides basic objects and interface to networking and security. However. a multiple line style opened with /* and . running. to XML generation and database access.I. Deployment Technologies: The JDK software provides two type of deployment technology such as the Java Web Start software and Java Plug-In software for deploying your applications to end users. also known as the CMS Garbage Collector. This simplifies the language and aids in preventing potential errors and anti-pattern design. and Java Remote Method Invocation over Internet Inter-ORB Protocol Technology (Java RMI-IIOP Technology) enable database to access and changes of remote objects Syntax The syntax of Java is largely derived from C++. and documenting your applications.
Besides the fact that the operating system. the Android SDK uses Java to design applications for the Android platform. and so on) tell us that a program written in the Java programming language can be four times smaller as compare to the same program written in C++. and the Javadoc commenting style opened with /** and closed with */. method counts. The Javadoc style of commenting allows the user to run the Javadoc executable to compile documentation for the program. that APIs cannot be copyrighted (Scope)Java Technology Changes Our Life Easy to Start: Since Java programming language is completely based on object-oriented language. . a San Francisco jury found that if APIs could be copyrighted. Hon. it's easy very simple and easy to learn. built on the Linux 2. 2012. Inc. Easy to write code: As compared to program metrics (class counts. have chosen to use Java as a key pillar in the creation of the Android operating system.closed with */. was written largely in Java. then Google had infringed Oracle's copyrights by the use of Java in Android devices. William Alsup ruled on May 31.6 kernel. an open-source smartphone operating system. 2012. Oracle's stance in this case has raised questions about the legal status of the language. On May 7. However. Use by external companies(like google) Google and Android. especially for programmers already known with C or C++.
Write better code: The Java programming language encourages good coding practices. Platform Independencies: The program keep portable and platform independent by avoiding the use of libraries written in other languages. that is compiled into machine-independent byte codes and run consistently on any platform of java. The Java platform differs from other platforms. and wide-range. manages your development time upto twice as fast when writing in it. tested code and introduce fewer bugs. and Macintoshes OS. The Java platform has two components: The Java Virtual Machine(JVM) The Java Application Programming Interface (API) The Java Virtual Machine is the root for the Java platform and is integrated into various hardware-based platforms. An automatic version check initially weather users are always up to date with the latest version of your software. Linux. the Java Web Start software will automatically update their installation Java Platform Platform is cross-combination of hardware or software environment in which a program runs. . flexibility and API can reuse existing. easily extendible. Based on the concept of object orientation. and manages automatic garbage collection which helps you avoid memory leaks. that is only software-only platform which runs on other hardware-based platforms. We are already known with the most popular platform like Microsoft Windows. Develop programs and Time Safer: The Java programming language is easier and simpler than C++. Solaris OS. Distribute software makes work easy : Using Java Web Start software. users will be able to launch own applications with a single click on mouse. its Java Beans component architecture. as such. Write Once and Used in any Java Platform : Any Source code of Program are written in the Java programming language. If an update is available for it. The programs will also require fewer lines of code.
new changes in compiler and virtual machine brings performance close to that of native code without posing any threatening to portability security. However.class file contains byte codes ? the machine language of the Java Virtual Machine (JVM).java extension in the Java programming language. A .The API is a vast collection of various software components that provide you many useful functionality to the application.class files by the java compiler. . It is grouped into logical collection of related classes and interfaces. The java launcher tool runs your application with an instance of the Java Virtual Machine. these logical collection are known as packages. Schematic Flow of Java Software Development Life Cycle JVM works on different Operating System . The . Java work on platform-independent environment. There are some virtual machines.class files(bytecode) capable of running on various Operating System. The API and Java Virtual Machine insulate the program from hardware. such as the Java Hotspots virtual machine that boost up your application performance at runtime . This include various tasks such as Efficiency of Programme and recompiling (to native code) which is frequently used sections of code. All source code is written in text files (Notepad Editor) save with the . the Java platform is bit slower than native code. The source files are compiled into .
Java JVM. Java Preferred Over Other Languages The Java is a high-level programming language that can be supported by all of the following features: Simple Object oriented Distributed Architecture neutral Portable High performance Multithreaded Robust Dynamic Secure Java has advantages over other languages and environments that make it suitable for just about any programming task. . the same application is capable to run on multiple platforms.
Historically.). The goal of Java is to make all implementations of Java compatible. This implementation is based on the original implementation of Java by Sun. Implementations Oracle Corporation is the current owner of the official implementation of the Java SE platform. microbenchmarks show Java 7 is approximately 1. the addition of language features supporting better code analysis (such as inner classes. The Java Development Kit (JDK). Some platforms offer direct hardware support for Java.Performance Programs written in Java have a reputation for being slower and requiring more memory than those written in C. Sun's trademark license for usage of the Java brand insists that all implementations be . the StringBuffer class. Javadoc. Windows and Solaris. and ARM based processors can have hardware support for executing Java bytecode through their Jazelle option. The Oracle implementation are packaged into two different distributions. Because Java lacks any formal standardization recognized by Ecma International. This package is intended for end-users. OpenJDK is the official Java reference implementation. there are microcontrollers that can run Java in hardware instead of a software Java Virtual Machine. The Oracle implementation is available for Mac OS X. etc. The implementation started when Sun began releasing the Java source code under the GPL. OpenJDK is another notable Java SE implementation that is licensed under the GPL. and a debugger. ANSI. As of Java SE 7. However. and optimizations in the Java Virtual Machine itself. Java programs' execution speed improved significantly with the introduction of Just-in-time compilationin 1997/1998 for Java 1. or any other third-party standards organization. Currently (February 2012). Jar. ISO/IEC.1. such as HotSpot becoming the default for Sun's JVM in 2000. The Java Runtime Environment (JRE) which contains the parts of the Java SE platform required to run Java programs.5 times slower than C. the Oracle implementation is the de facto standard. optional assertions. is intended for software developers and includes development tools such as the Java compiler.
This resulted in a legal dispute with Microsoft after Sun claimed that the Microsoft implementation did not support RMI or JNI and had added platform-specific features of their own. 2011) Reason for choosing this company 1)WORKSHOP: Recent Workshop: A short story never ends but it messages to the reader to be curious and without being curious your knowledge is incomplete as curiosity is the basic condition to be an ideal student. Microsoft no longer shipsWindows with Java. 2006) Java SE 7 (July 28. 2002) J2SE 5. This environment enables portable server-side applications. 1998) J2SE 1.1 (February 19. 1997) J2SE 1. as well as a court order enforcing the terms of the license from Sun. 1996) JDK 1. As a result. Platform-independent Java is essential to Java EE. 2004) Java SE 6 (December 11. Versions Major release versions of Java. Sun sued in 1997. and an even more rigorous validation is required to certify an implementation.2 (December 8. along with their release dates: JDK 1. and in 2001 won a settlement of US$20 million.3 (May 8."compatible".4 (February 6. 2000) J2SE 1.0 (January 23. .0 (September 30.
UBUNTU. It is the bridge between a subject and knowledge seeker. there would be an entire city down to sea. openGL like add on apart from conventional J2ME and J2EE . every day a new programming language is getting birth.VLSI and Chip set programming(including MOSFET and Spice). workshop is that pilot. materialistic is. Our developers.LONO and JOLI like clouds.RT-LINUX.) 2)INDUSTRIAL TRAINING As we have started our journey.gcc/gnu).Workshop carries exactly that sense. perhaps.ANDROID like Embedded and Real time Operating Systems. Keeping this matter in our mind we have introduced another educational wing ‘an important feather in the crown’ that is to conduct workshop based on a new emerging technology.cross platform compilers (COSMIC-C. Jena. until and unless it is going through the‘pilot’ process. rather you have to be ‘Jack of all trades’.KEIL. the word ‘No’ turns to ‘on’.. as we do not have any intention to be the world’s number .MATLAB etc. the way technology is jetting . JAVA . Sixty to seventy years back it was unbelievable to the earth that once time would come when humanoid might replace a human in the world of employment. Any new technology can never be adopted evenly. Haskell. researchers and content managers are working ruthless for a better as ‘education is a contiguous learning system’ even we handle and fulfill the ‘on demand’ requirement of corporate by organizing customized workshops (for example Processing like on board programming tool etc. at least you must be a ‘new technology literate ‘and that is why attending workshop based on a niche technology is smarter for a technical student.And we have to be at par with this ‘Jet Age’ as now the protocol is either be learnt or to leave! In the technical world.NET. System programming(by ANSIC. Dick and Harry’. Today nothing is impossible. as we have a dream to reach to the remote corner of the world to transform the knowledge. it is very difficult to learn all! And it is the reality for any ‘Tom. In contrary to it. C language now belonging to ‘Jurassic Age’! Have you heard about Meta Shell Script? Do you program on board? Are you conversant with ‘Processing’?”Hey Mike can you speak on ‘Lua’?” No??Then why are you here? It means. CLOUDO . network.TEXUS etc). We are currently dealing with Python. Embedded/Native and Objective C like programming tools apart from the conventional languages like . CGI. perhaps for all to be master in each subject and world is not seeking that. Eclipse. Perl.
Mobile simulations. hence we are sailing well. 4. . This payment part is committed either via Paypal or via credit card/online transaction 5. MOSFET. we are comfortable by getting a plenty of blesses of our students and their relies. but we are trying our level best insuring to present more and more academic ventures for the benefit of the student and in a continuous process of upgrading our portal. This is our third year and we are still learning a lot from our ancestors and that learning taught us not to confine ourselves only to solve assignments or providing support to academic projects but also to be present in the student world more actively by the mean of workshops and boot camp training.online education hub. Our portal is still in nascent stage hence may be unable to communicate all to the outer world. Teachers mention the details of subject. from Reliable Tutor confirmation email goes to student mail box. specialty and pricing for an assignment/subject in web. Real Time Operating Systems. If all would tally. Network Protocol designing by Python/CGI/Lua etc. We are now limited to conduct boot camps only in Information emerging technologies like Embedded Robotics. Image Processing and signal processing by Matlab or tool like Objective C. Soon we will introduce boot camp projects in other ‘on demand’ domains like Health and Nutrition. teacher confirms the receiving of assignment/or share the lesson plan after Reliable Tutor getting an advance payment (usually 50% of the quote) in lieu of primary invoice. Student quotes the price and schedule in the next stage. that is why we are reliable tutors. After receiving an assignment. 3) Online tutoring Students and Teachers meet online. Alternative living strategy etc.You feel free to inquire as your feeds will enrich our output day by day. hence. and have mentioned below step by step process how thing works: 1. Students matches the quality issue and pricing part by chatting 3. VLSI with LASI. Clouds and Androids. 2. Disaster Management.
The java come with the concept of Multithreaded Program. reuse and generate a new project.6. complete portfolio of project management like source codes. then generates secondary invoice for rest payment. We are here to assist you in any project where programming tool is no matter whether it is C or Lua . A project is defined as a complete project when it can give the birth of its successor that is why ‘life cycle’ this term is introduced in project. If you are stuck with your project or wanna make a project for your future use just talk to us or chat with our representative. we will guide you with our expertise and knowledge. Reliable Tutor’s team is ready to help you to solve your final year project.This is more delegate and difficult to handle . When Reliable Tutor confirms the completion of assignment. as Java compilers are able to detect many error problem in program during the execution of respective program code. operating system-specific procedures have to be called in order . power point/flash presentation etc. 7. cover letter.Java supports multithreaded. reliable Tutor sends the completed assignment by two way hand shaking method. As we believe certain code snippet or flip is not a project.Our think tank is efficient enough to take care any technology existing on the earth. Only thing we can assure you is SATISFACTION insuring the score . documentation. PROJECT ASSISTANCE In few cases like Real Time System there is no difference between implementation and maintenance as maintenance is complimentary to implementation. In other languages. The teacher and student once again chat at the day of schedule time ends either via Skype or Google Chat or by direct calling in accordance with both parties comfort-ability. Multithreaded is the path of execution for a program to perform several tasks simultaneously within a program. We usually provide the orthodox support to our students following the rule of software engineering. once fails system is crashed hence here the life cycle of the project called ‘Spiral Model’ .A self sufficient complete project is that which when being studied by any other software engineer apart from the project owner can understand. following the above mentioned process when payment is finished. Java emphasis on checking for possible errors.
Java is platform-independent: One of the most significant advantages of Java is its ability to move easily from one computer system to another. i. Advantages of JAVA Java is simple: Java was designed to be easy to use and is therefore easy to write. If the program does not deallocate an object. debug. In the latter case the responsibility of managing memory resides with the programmer.to work on multithreading. . the result is undefined and difficult to predict. a memory leak occurs. This allows you to create modular programs and reusable code. In some languages. manipulating objects. but these add overhead and complexity. and learn than other programming languages. and making objects work together. The ability to run the same program on many different systems is crucial to World Wide Web software. Java is distributed: Distributed computing involves several computers on a network working together. and Java succeeds at this by being platform-independent at both the source and binary levels. compile. The reason that why Java is much simpler than C++ is because Java uses automatic memory allocation and garbage collection where else C++ requires the programmer to allocate memory and to collect garbage. memory for the creation of objects is implicitly allocated on the stack. and the program is likely to become unstable and/or crash. If the program attempts to access or deallocate memory that has already been deallocated.e. Java is designed to make distributed computing easy with the networking capability that is inherently integrated into it. Note that garbage collection does not prevent "logical" memory leaks. or explicitly allocated and deallocated from the heap. One of the ideas behind Java's automatic memory management model is that programmers can be spared the burden of having to perform manual memory management. Java is object-oriented: Java is object-oriented because programming in Java is centered on creating objects. those where the memory is still referenced but never used. This can be partially remedied by the use of smart pointers.
. Java is interpreted: An interpreter is needed in order to run Java programs. Java is secure: Java is one of the first programming languages to consider security as part of its design. Java is multithreaded: Multithreaded is the capability for a program to perform several tasks simultaneously within a program. the program need only be compiled once. compiler. and runtime environment were each developed with security in mind. communicating with each other to perform a joint task. while in other languages. and the bytecode generated by the Java compiler can run on any platform. In Java. interpreter. multithreaded programming has been smoothly integrated into it. Disadvantages of JAVA Performance: Java can be perceived as significantly slower and more memory-consuming than natively compiled languages such as C or C++. For example. The programs are compiled into Java Virtual Machine code called bytecode. Look and feel: The default look and feel of GUI applications written in Java using the Swing toolkit is very different from native applications.Writing network programs in Java is like sending and receiving data to and from a file. The bytecode is machine independent and is able to run on any machine that has a Java interpreter. Java puts a lot of emphasis on early checking for possible errors. The Java language. operating system-specific procedures have to be called in order to enable multithreading. the diagram below shows three programs running on three different systems. as Java compilers are able to detect many problems that would first show up during execution time in other languages. It is possible to specify a different look and feel through the pluggable look and feel system of Swing. Multithreading is a necessity in visual and network programming. With Java. Java is robust: Robust means reliable and no programming language can really assure reliability.
Java also was specifically designed to be simpler than C++ but it keeps evolving above that simplification. C++ Java backwards compatible.0 the procedural paradigm is better accommodated than in earlier versions of Java.Single-paradigm language: Java is predominantly a single-paradigm language. secure. Java was created initially to support network computing on embedded systems. none of which were design goals for C++. multi-threaded and distributed. You can get a better understanding of Java in the Java Programming WikiBook. C++ and Java share many common traits. However. but direct compatibility with C was not maintained. with the addition of static imports in Java 5. Java was designed to be extremely portable. The syntax of Java was chosen to be familiar to C programmers. Comparision of java with other languages Java This is a comparison of the Java programming language with the C++ programming language. backwards compatibility with including C previous versions Focus execution efficiency developer productivity Freedom trusts the programmer Memory arbitrary memory access memory access only through Management possible objects Compatibility imposes some constraints to the programmer .
Java runs on a virtual machine so with C++ you have greater power at the cost of portability. in Java it is package access. they are different. C++ allows namespace level constants. Foo<1>(3). int main() is a function by itself. C++ runs on the hardware. C++. but it creates an object if Foo is the name of a class template. . const in C++ indicates data to be 'read-only.Code Type Safety Programming Paradigm Operators Main Advantage concise expression type casting is restricted greatly explicit operation only compatible types can be cast procedural or object-oriented object-oriented operator overloading meaning of operators immutable powerful capabilities of feature-rich. C++ access to class members default to private.' and is applied to types. easy to use standard language library Differences between C++ and Java are: C++ parsing is somewhat more complicated than with Java. private) is done with labels and in groups. final in java indicates that the variable is not to be reassigned. but for complex classes. variables. All such Java declarations must be inside a class or interface. for example. C++ access specification (public. without a class. C++ classes declarations end in a semicolon. C++ doesn't support constructor delegation. and functions. For basic types such as const int vs final intthese are identical. is a sequence of comparisons if Foo is a variable.
However. C++ provides some low-level features which Java lacks. the programmer can simulate by-reference parameters with by-value parameters and indirection. Similarly. C++ allows a range of implicit conversions between native types. As in C. Java provides a strict floating-point model that guarantees consistent results across platforms. but object (non-primitive) parameters are reference values. In Java. C++ lacks language level support for garbage collection while Java has built-in garbage collection to handle memory deallocation. A consequence of this is that although loop conditions (if. Java enforces structured control flow. C++ supports goto statements. through the Java Native Interface. In Java. but its labeled break and labeled continue statements provide some structured goto-like functionality. This is handy if the code were a typo for if(a == 5). pointers can be used to manipulate specific memory locations. meaning indirection is built-in. with the goal of code being easier to understand. all parameters are passed by value. Java does not. For passing parameters to functions. code such as if(a = 5) will cause a compile error in Java because there is no implicit narrowing conversion from int to boolean. ranges and representations. though normally a more lenient mode of operation is used to allow optimal floating-point performance. and also allows the programmer to define implicit conversions involving compound types. there is significant overhead for each call. any other conversions require explicit cast syntax. However. . The rounding and precision of floating point values and operations in C++ is platform dependent. but the need for an explicit cast can add verbosity when statements such as if (x) are translated from Java to C++. or be configurable via compiler switches. In C++. which may even change between different versions of the same compiler. Java built-in types are of a specified size and range. Generally. while and the exit condition in for) in Java and C++ both expect a boolean expression. Java only permits widening conversions between native types to be implicit. a task necessary for writing lowlevel operating systemcomponents. C++ supports both true pass-byreference and pass-by-value. In fact. assembly code can still be accessed as libraries. whereas C++ types have a variety of possible sizes. many C++ compilers support inline assembler.
The synchronized keyword in Java provides simple and secure mutex locks to support multi-threaded applications. Java has generics. Java does not have pointers—it only has object references and array references. C++ has templates. which concatenate strings as well as performing addition. The only overloaded operators in Java are the "+" and "+=" operators. In C++ multiple inheritance and pure virtual functions makes it possible to define classes that function just as Java interfaces do. Java supports multiple inheritance of types. In C++ all types have value semantics. while Java references only access objects. Java has both language and standard library support for multi-threading. but a reference can be created to any object. Java explicitly distinguishes between interfaces and classes. but only single inheritance of implementation. and compound types have reference semantics only. C++ supports multiple inheritance of arbitrary classes. C++ features programmer-defined operator overloading. In Java. Java features standard API support for reflection and dynamic loading of arbitrary new code. In C++. neither of which allow direct access to memory addresses. While mutex lock mechanisms are available through libraries in C++. In C++ one can construct pointers to pointers. In Java. the lack of language semantics makes writing thread safe code more difficult and error prone Learning Outcome from training . but a class can implement multiple interfaces. native types have value semantics only. Both Java and C++ distinguish between native types (these are also known as "fundamental" or "built-in" types) and user-defined types (these are also known as "compound" types). The equivalent mechanism in Java uses object or interface references. In C++ pointers can point to functions or member functions (function pointers or functors). pointers can be manipulated directly as memory address values. which will allow the object to be manipulated via reference semantics. a class can derive from only one class.
Learning outcomes reflect the goals of the instructional designer. is it for development or to correct performance deficiencies? Identifying the instructional strategies .Such as looking at job descriptions. Note that learning outcomes are different from learning objectives. or concept learning. . In addition. Whereas objectives specify what the learner will be able to accomplish after the completion of training.The 6 week training has been a rewarding experience in many ways. These learning outcomes are important. by the end of this course participants will be able to: Deploy a Java web application to a server Understand the architecture of web-based systems Develop components of a web based application using the Java Enterprise Edition Develop with the Struts framework Integrate server side programs with enterprise data sources. For example. they are linked to the design of the training. We have gained a lot of things and essentials of java programming language. exploration.Such as coaching. for once they are identified. they can be used to develop instructional strategies and generate learning objectives. Examining the performance domain . or interviewing subject matter experts. Learning outcomes may developed by viewing them through three different perspectives: Examining the goals of training. observing expert performers.
Bibliography 1. The way of java By Gary Entsminger Websites. Teach yourself java in 24 hours By Rogers Cadenhead 3.com . Thinking in java By Bruce Eckel 2. | https://www.scribd.com/document/252709048/Amdfit-Report | CC-MAIN-2018-43 | en | refinedweb |
Platform Scripts
Elastic Beanstalk installs the shell script
get-config that you can use to get environment variables and other information in hooks that
run
on-instance in environments launched with your custom platform.
This tool is available at
/opt/elasticbeanstalk/bin/get-config. You can use it in the following ways:
get-config optionsettings– Returns a JSON object listing the configuration options set on the environment, organized by namespace.
$
/opt/elasticbeanstalk/bin/get-config optionsettings{"aws:elasticbeanstalk:container:php:phpini":{"memory_limit":"256M","max_execution_time":"60","display_errors":"Off","composer_options":"","allow_url_fopen":"On","zlib_output_compression":"Off","document_root":""},"aws:elasticbeanstalk:hostmanager":{"LogPublicationControl":"false"},"aws:elasticbeanstalk:application:environment":{"TESTPROPERTY":"testvalue"}}
To return a specific configuration option, use the
-noption to specify a namespace, and the
-ooption to specify an option name.
$
/opt/elasticbeanstalk/bin/get-config optionsettings -n256M
aws:elasticbeanstalk:container:php:phpini-o
memory_limit
get-config environment– Returns a JSON object containing a list of environment properties, including both user-configured properties and those provided by Elastic Beanstalk.
$
/opt/elasticbeanstalk/bin/get-config environment{"TESTPROPERTY":"testvalue","RDS_PORT":"3306","RDS_HOSTNAME":"anj9aw1b0tbj6b.cijbpanmxz5u.us-west-2.rds.amazonaws.com","RDS_USERNAME":"testusername","RDS_DB_NAME":"ebdb","RDS_PASSWORD":"testpassword1923851"}
For example, Elastic Beanstalk provides environment properties for connecting to an integrated RDS DB instance (RDS_HOSTNAME, etc.). These properties appear in the output of
get-config environmentbut not in the output of
get-config optionsettings, because they are not set by the user.
To return a specific environment property, use the
-koption to specify a property key.
$
/opt/elasticbeanstalk/bin/get-config environment -ktestvalue
TESTPROPERTY
You can test the previous commands by using SSH to connect to an instance in an Elastic Beanstalk environment running a Linux-based platform.
See the following files in the sample platform definition archive for an example of
get-config usage:
builder/platform-uploads/opt/elasticbeanstalk/hooks/configdeploy/enact/02-gen-envvars.sh– Gets environment properties.
builder/platform-uploads/opt/SampleNodePlatform/bin/createPM2ProcessFile.js– Parses the output.
Elastic Beanstalk installs the shell script
download-source-bundle that you can use to download your application source code during the
deployment of your custom platform. This tool is available at
/opt/elasticbeanstalk/bin/download-source-bundle. See the sample script
00-unzip.sh, which is in the
appdeploy/pre folder, for an example of how to use
download-source-bundle to download application source code to the
/opt/elasticbeanstalk/deploy/appsource
folder during deployment. | https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/custom-platforms-scripts.html | CC-MAIN-2018-43 | en | refinedweb |
Abstract
There are many implementations of a Python package repository and many tools that consume them. Of these, the canonical implementation that defines what the "simple" repository API looks like is the implementation that powers PyPI. This document will specify that API, documenting what the correct behavior for any implementation of the simple repository API.
Specification
A repository that implements the simple API is defined by its base url, this is the top level URL that all additional URLS are below. The API is named the "simple" repository due to fact that PyPI's base URL is.
Note
All subsequent URLs in this document will be relative to this base URL (so given PyPI's URL, an URL of /foo/ would be.
Within a repository, the root URL (/) MUST be a valid HTML5 page with a single anchor element per project in the repository. The text of the anchor tag MUST be the normalized name of the project and the href attribute MUST link to the URL for that particular project. As an example:
<!DOCTYPE html> <html> <body> <a href="/frob/">frob</a> <a href="/spamspamspam/">spamspamspam</a> </body> </html>
Below the root URL is another URL for each individual project contained within a repository. The format of this URL is /<project>/ where the <project> is replaced by the normalized name for that project, so a project named "HolyGrail" would have an URL like /holygrail/. This URL must respond with a valid HTML5 page with a single anchor element per file for the project. The text of the anchor tag MUST be the filename of the file and the href attribute MUST be an URL that links to the location of the file for download. The URL SHOULD include a hash in the form of an URL fragment with the following syntax: #<hashname>=<hashvalue>, where <hashname> is the lowercase name of the hash function (such as sha256) and <hashvalue> is the hex encoded digest.
In addition to the above, the following constraints are placed on the API:
All URLs which respond with an HTML5 page MUST end with a / and the repository SHOULD redirect the URLs without a / to add a / to the end.
URLs may be either absolute or relative as long as they point to the correct location.
There is no constraints on where the files must be hosted relative to the repository.
There may be any other HTML elements on the API pages as long as the required anchor elements exist.
Repositories MAY redirect unnormalized URLs to the canonical normalized URL (e.g. /Foobar/ may redirect to /foobar/), however clients MUST NOT rely on this redirection and MUST request the normalized URL..
If there is a GPG signature for a particular distribution file it MUST live alongside that file with the same name with a .asc appended to it. So if the file /packages/HolyGrail-1.0.tar.gz existed and had an associated signature, the signature would be located at /packages/HolyGrail-1.0.tar.gz.asc.
A repository MAY include a data-gpg-sig attribute on a file link with a value of either true or false to indicate whether or not there is a GPG signature. Repositories that do this SHOULD include it on every link.
A repository MAY include a data-requires-python attribute on a file link. This exposes the Requires-Python metadata field, specified in PEP 345, for the corresponding release. Where this is present, installer tools SHOULD ignore the download when installing to a Python version that doesn't satisfy the requirement. For example:
<a href="..." data-...</a>
In the attribute value, < and > have to be HTML encoded as < and >, respectively.
Normalized Names
This PEP references the concept of a "normalized" project name. As per PEP 426 the only valid characters in a name are the ASCII alphabet, ASCII numbers, ., -, and _. The name should be lowercased with all runs of the characters ., -, or _ replaced with a single - character. This can be implemented in Python with the re module:
import re def normalize(name): return re.sub(r"[-_.]+", "-", name).lower() | http://docs.activestate.com/activepython/3.6/peps/pep-0503.html | CC-MAIN-2018-43 | en | refinedweb |
NHibernate 1.2 is mostly source-compatible with NHibernate 1.0. However, it is not intended as a drop-in replacement for 1.0.
This document describes the changes between NHibernate 1.0 and NHibernate 1.2 that will affect existing applications, and mentions certain new features of NHibernate 1.2 that might be useful to existing applications.
Changes are classified into API changes (affecting source code), metadata changes (affecting the XML O/R mapping metadata), query language changes (affecting HQL queries), runtime behavior changes, and security-related changes.
Redundant query execution methods were deprecated in ISession interface. These methods are:
NHibernate 1.2 applications should use CreateQuery() for all query execution. Existing applications may continue to use the deprecated methods.
The overloaded forms of CreateSQLQuery() which took arrays have been deprecated. There is a new ISQLQuery interface (returned by CreateSQLQuery(String)) which provides equivalent functionality (and more). Existing applications may continue to use the deprecated methods.
The ILifecycle and IValidatable interfaces were deprecated in NHibernate 1.2 and moved to the NHibernate.Classic namespace. The Hibernate team does not consider it good practice to have domain model classes depend upon persistence-specific APIs. NHibernate 1.2 applications should use IInterceptor interface. Existing applications may continue to use ILifecycle and IValidatable.
Several new methods were added to the IInterceptor interface. Existing interceptors will need to be ugraded to provide empty implementations of the two new methods.
To avoid issues with interceptor migration (whether 1.0.x -> 1.2.x, or moving forward), just extend the new EmptyInterceptor class instead of writing your own empty implementation for all methods you don't need.
Both IUserType and ICompositeUserType had several methods added, to support new functionality of NHibernate 1.2. They were moved to the namespaceNHibernate.UserTypes. Existing user type classes will need to be upgraded to implement the new methods.
Note: NHibernate 1.2 provides IParameterizedType interface to allow better re-useability of user type implementations.
FetchMode.Lazy and FetchMode.Eager were deprecated. The more accurately named FetchMode.Select and FetchMode.Join have the same effect.
The NHibernate.Expression, NHibernate.Mapping, NHibernate.Persister and NHibernate.Collection namespaces feature heavy refactoring. Most NHibernate 1.0 applications do not depend upon these namespaces, and will not be affected. If your application does extend classes in these namespaces, you will need to carefully migrate the affected code.
Since it is best practice to map almost all classes and collections using lazy="true", that is now the default. Existing applications will need to explicitly specify lazy="false"on all non-lazy class and collection mappings. For the lazy classes to function correctly, all their public and protected members must be virtual (overridable). Since this is a very significant potential source of errors when developing on .NET, NHibernate 1.2 will check at configuration time that all lazy classes fulfill the requirements.
The outer-join attribute is deprecated. Use fetch="join" and fetch="select" instead of outer-join="true" and outer-join="false". Existing applications may continue to use theouter.
Update the XML schema reference in your hbm XML files. Change urn:nhibernate-mapping-2.0 to urn:nhibernate-mapping-2.2 in the hibernate-mapping element. If you get "XML validation error: Could not find schema information for the element 'urn:nhibernate-mapping-2.0:hibernate-mapping'", you forgot to change the namespace.
If you have a one-to-many association to a class that is part of a subclass hierarchy (i.e. using table-per-class-hierarchy strategy), you may need to add a where attribute to the collection element since NHibernate no longer adds the discriminator restriction automatically.
This is probably best explained in code. The mapping below will no longer work as intended:
<class name="Person"> ... <!-- Cat and Dog are subclasses of Animal, mapped using <subclass> --> <bag name="Cats"> <one-to-many </bag> <bag name="Dogs"> <one-to-many </bag> </class>
To make it work again, add explicit where attributes:
<class name="Person"> ... <bag name="Cats" where="discriminator = 'CAT'"> <one-to-many </bag> <bag name="Dogs" where="discriminator = 'DOG'"> <one-to-many </bag> </class>
In NHibernate 1.0 a session acquired a database connection when needed and then held onto to it until closed. As of 1.2, however, the session will release the connection after the database transaction completes. If you are not using NHibernate transactions, the session assumes it is in auto-commit mode, and will release the connection after every operation. The session will automatically re-acquire connection the next time it is needed.
This behavior can be overridden, but typically it is best to not override this default (unless you are using NHibernate with distributed transactions, in which case the default behavior is inappropriate). If your application depends on some quirk of the old behavior (like having the same connection available beyond transaction boundaries, etc) then you may need to tweak this; but you should view this as a problem with your application logic and fix that. Or, if you believe that you can "read data without or outside of a transaction", you will likely face problems in the future versions of NHibernate. Of course, there can be no data access outside of a transaction, be it read or write access, and NHibernate will make it much more difficult to write bad code that relies on auto-commit side effects. See section "Connection Release Modes" in the documentation for more details.
The version property of a transient entity will be set to 1 when the entity is persisted (NHibernate 1.0 set the version number to 0). This was done to allow using a non-nullable type for the version property (such as Int32 or Int64), so that 0 could be used as unsaved-value for the property.
Previously, calling ISession.Get() could return an uninitialized proxy if the session contained the proxy as a result of some earlier operations. In NHibernate 1.2, Get() will initialize the proxy in this case before returning it.
ISession.Transaction property gives access to the current transaction associated with a session. Unlike previous NHibernate versions, as soon as this transaction is committed, a new transaction is associated with the session. Thus, ISession.Transaction.WasCommitted and WasRolledBack will always return false.
To be able to check the status of a particular transaction, assign it to a local variable:
ITransaction myTransaction = ISession.Transaction; ISession.Transaction.Commit(); // ISession.Transaction.WasCommitted is false here, // myTransaction.WasCommitted is true.
NHibernate 1.2 now uses Assembly.Load() instead of Assembly.LoadWithPartialName() to load driver assemblies. This means that it will no longer look for the highest-versioned assembly in the Global Assembly Cache (GAC), which was sometimes undesirable. Instead, it is now your responsibility to either put the provider assembly into the application directory, or add a qualifyAssembly element to the application configuration file, specifying the full name of the assembly.
For example, if you are using MySQL Connector/.NET, you should either put MySql.Data.dll into the application directory (or some other directory from whereAssembly.Load() can pick it up), or put it in the GAC and add a qualifyAssembly element to the configuration file:
<qualifyAssembly partialName="MySql.Data" fullName="MySql.Data, Version=..., PublicKeyToken=..."/>
In alignment with Hibernate, the count, sum and avg functions now default to return types as specified by the JPA specification. This can result in InvalidCastException 's at runtime if you used aggregation in HQL queries.
The new type rules are as follows:
If you cannot change to the new type handling the following code can be used to provide "classic" NHibernate behavior for HQL aggregation.
Configuration classicCfg = new Configuration(); classicCfg.AddSqlFunction( "count", new ClassicCountFunction()); classicCfg.AddSqlFunction( "avg", new ClassicAvgFunction()); classicCfg.AddSqlFunction( "sum", new ClassicSumFunction()); ISessionFactory classicSf = classicCfg.BuildSessionFactory();
A Disjunction with no added conditions will always evaluate to false. This is a change from 1.0 and Hibernate, where an empty disjunction evaluates to true, but we feel it is more correct.
NHibernate now uses a publicly available strong name key pair (NHibernate.snk) to strong-name binary .NET assemblies. If you relied on the key being kept private for security, you should switch to other means of assuring assembly integrity, such as using a cryptographic hash.
The original key pair used to sign NHibernate 1.0.x assemblies is still kept private.
Several assemblies have AllowPartiallyTrustedCallersAttribute (APTCA) applied to them, to make it easier to use NHibernate under Medium Trust Level. This attribute may potentially introduce security issues. To recompile NHibernate without APTCA, use this NAnt command:
nant -D:assembly.allow-partially-trusted-callers=false build | http://nhibernate.info/doc/reference2-0en/from-1-0-to-1-2.html | CC-MAIN-2018-43 | en | refinedweb |
Representing polymorphic objects in a Database
The Problem
This post is really about type safety in general, something near and dear to my heart since it gets me so amped. While I normally develop in Python, it feels extremely luxurious to program in a language like Swift where the type system is so strict. If we have an object and we know its type and we know that’s it’s not None or Null, we’re free to act upon it without examining any of its data. This benefit is expanded to polymorphic entities where objects are subclasses of a parent class. Since all objects inherit from a shared class, all operations supported by the parent class are supported against the object.
Now, in some cases, this concept makes sense to apply to models that are saved into some persistence layer (a database). But then things just get weird.
SQLAlchemy, which I’ve been using at work, has its own method of storing polymorphic entities by writing each child entity to a separate table. Without considering too much of the merits of an implementation like this, it seems overly complex and too much happening at the persistence layer.
Recently I implemented my own version of polymorphic representation in a database, and I really liked it, so I wanted to go ahead and share…
But First: Representing Types in General
Before jumping ahead, one library I’ve been using a lot lately is the Schematics library. In essence, you can define a reasonably complex object structure, throw some data into the structure, and from there you can immediately validate that the input data matches the object’s type system. This can be useful if you’re reading or writing data to an external API or database. For a quick example:
import datetime from schematics.models import Model from schematics.types import ( DateTimeType, EmailType, IntType, StringType, UUIDType, ) from schematics.types.compound import ListType, ModelType class SomeOtherEntity(Model): uuid = UUIDType() description = StringType(min_length=1, required=True) class ArbitraryEntity(Model): uuid = UUIDType() some_int = IntType() child_entities = ListType(ModelType(SomeOtherEntity), required=True) created_by_email = EmailType() created_at = DateTimeType(default=datetime.datetime.utcnow)
So now with an object structure defined, we can either create the object from input data, or we can construct the an object ourselves and serialize it so that it can be written to a database or returned in an API:
assert isinstance(input_primitive_data, dict) arbitrary_entity = ArbitraryEntity(input_primitive_data) arbitrary_entity.validate() # will throw an exception if data is invalid serializable_data = arbitrary_entity.to_primitive() assert serializable_data == input_primitive_data
Abstraction Layer in Front of Database
If you follow my writings vigorously, which you probably don’t, then you know that it’s a good idea to add an abstractoin layer between your application and whatever persistence layer it uses. Your application shouldn’t know about what version of SQL you’re using or if you’re even using SQL at all, and if you wanted to change your persistence layer then you should only need to make isolated changes. The same concept applies to 3rd party libraries or 3rd party interfaces to separate API’s. So the strict types above can be used as return types in these abstraction layers.
The point is simply: Whatever module interfaces with services that are not directly tied to your application should return these objects or something like it. They are pure objects that don’t know about anything else and can be serialized into primitive types which are universally understood.
Polymorphism in the Database
Now, to expand upon the previous ideas with a basic modeling concept: if an object looks like a duck, quacks like a duck, and does everything else like a duck, it’s a duck. Therefore, two distinct types will never be exactly the same, and this means that types can be inferred. So, it would be possible to create a table whose columns are made up of the union of all of our class’s and its subclass’s attributes. If each subclass has non-nullable fields, then given a database row we can determine its type based on which fields are populated or an exception can be thrown if the input row does not conform to any particular type.
Now, combine everything I’ve said and accept it as gospel. We can express those concepts in the code below, and we can add a mapper class that converts a row retrieved from the database into a particular type. The type is inferred by returning the first entity that correctly validates from the input row (but no more than one entity should correctly validate). I should point out that this is kind of slow, but at least the slow operations are happening in memory and are comparitively much faster than a database query.
def get_subclasses(cls): """ Returns all of the subclasses of an input class. """ subclasses = [] + cls.__subclasses__() for subclass in subclasses: subclasses.extend(get_subclasses(subclass)) return subclasses class _IncompleteParentEntity(Model): uuid = UUIDType(required=True) description = StringType(min_length=1, required=True) created_at = DateTimeType(default=datetime.datetime.utcnow) class LobbdawgEntity(object): def __init__(self): raise Exception("Don't instantiate this class") @staticmethod def inferred_from_data(primitive_dict): for sub_cls in get_subclasses(_IncompleteParentEntity): try: instance = sub_cls(primitive_dict) instance.validate() break except (ModelConversionError, ModelValidationError): continue else: raise ModelValidationError("Ambiguous type based on input data") return instance class LobbdawgEntity1(_IncompleteParentEntity): arbitrary_attribute = IntType(required=True) class LobbdawgEntity2(_IncompleteParentEntity): arbitrary_int_array = ListType(IntType, required=True) class DbRowToEntityMapper(object): attrs = ( 'created_at', 'description', 'uuid', 'arbitrary_attribute', 'arbitrary_int_array', ) @classmethod def to_entity(cls, row): primitive_dict = {} for attr in cls.attrs: value = getattr(row, attr) if value: primitive_dict[attr] = value return LobbdawgEntity.inferred_from_data(primitive_dict)
Some Moar Thoughts on Inheritance
Somewhat tangent to the idea of representing multiple subclasses in a database, a few other thoughts:
A parent class with “Base” as a prefix in the name is a stupid name. This was one of my takeaways from Jeremiah “Boardgame Bruce” Lee. If you have a base class that’s not abstract, there’s nothing that inherently makes it “base” because all classes can be inherited from (one of the beauties of object oriented programming). If a class is “abstract,” however, this actually means something and denotes that a child class will work as intended if it implements the abstract methods and properties. This is similar to an interface or a protocol but can additionally provide default behavior.
In this case, schematics uses meta classes, so without some rigorous works I can’t actually make the parent class abstract. I find it expressive to name it “Incomplete” and use an underscore to denote that it is not meant to be a public facing class. | http://scottlobdell.me/2015/08/representing-polymorphic-objects-database/ | CC-MAIN-2018-43 | en | refinedweb |
I'm getting a
ClassCastException (java.lang.Double cannot be cast to java.lang.Long) when retrieving multiple instances of a class in the datastore. The class has many values that are doubles and many that are longs. I'd like to view what is in the datastore and compare with the class properties to see if there is a mismatch. I tried the
representationsOfProperty method found near the bottom of, but my queries return
null.
I have a class defined similar to the following:
@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Container
{
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Long containerID = null;
@Persistent
private Long extensionID = null;
@Persistent
private String homeUrl;
@Persistent
private Double containerScore;
}
I copied the code from the GAE page linked above. The only change I made was to convert 'key' to "key" since a string is requested and what is shown in the example isn't a character.
Collection<String> representationsOfProperty(DatastoreService ds,
String kind,
String property)
{
// Start with unrestricted non-keys-only property query
Query q = new Query(Entities.PROPERTY_METADATA_KIND);
// Limit to specified kind and property
q.setFilter(new FilterPredicate("__key__", Query.FilterOperator.EQUAL, Entities.createPropertyKey(kind, property)));
// Get query result
PreparedQuery pq = ds.prepare(q);
Entity propInfo = pq.asSingleEntity();
if( null == propInfo )
{
Collection<String> strs = new ArrayList<String>();
strs.add( "[ERROR: Invalid Query: " + pq.toString() + "]" );
return strs;
}
// Return collection of property representations
return (Collection<String>) propInfo.getProperty("property_representation");
}
I call that method with the following code:
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
String prop = "containerID";
Collection<String> reps = representationsOfProperty( datastore, Container.class.toString(), prop );
Unfortunately,
propInfo is always
null. Any ideas on what I could try? Am I doing something wrong?
I just created a sample project to reproduce your issue. JDO is saving the entities in the Datastore, but not naming the primary key property according to the member variables of the
PersistenceCapable class. Check your datastore viewer and grab a random
Container entity to see what's happening.
If you need to do metadata queries on the id property in this manner, you should be aware that the ID/Name property is part of the key. Check this interesting talk to learn more about how the Datastore internals work (it's based on BigTable). | http://www.dlxedu.com/askdetail/3/2e973ff5243bdac476f623586f36954d.html | CC-MAIN-2018-43 | en | refinedweb |
With the oop way, i get a 0 value with echo (in controller), while the test app still shows the correct value:
require_once $_SERVER ['DOCUMENT_ROOT'] . "/testing/IPTest.php"; echo \IPv4\checkIPAddressIsInRange();
No way is working: Neither session or include/require_once nor the oop one. WTF is going on, something must be completely fu***d up..
The crazy thing is that the test app works without any problems:
<.", "; echo var_dump($test); $test = $ipAddressIsInRange; echo ", without session: ".$test.", "; echo var_dump($test); ?>
...with that IPTest:
<?php namespace IPv4; if(true) { error_reporting(E_ALL & ~E_NOTICE); ini_set ( 'display_startup_errors', 1 ); ini_set ( 'display_errors', 1 ); } if(!session_id() || session_id() == null || session_id() == '') { session_start(); } require_once $_SERVER ['DOCUMENT_ROOT'] . "/testing/ipv4-subnet-calculator/src/SubnetCalculator.php"; //] = "77.239.32.0/19"; $range [1] = "46.255.168.0/21"; $range [2] = "37.35.112.0/21"; $range [3] = "185.74.112.0/22";; } $ipAddressIsInRange = checkIPAddressIsInRange(); // Use caching or not... if(false) { if(!isset($_SESSION['ipAddressIsInRange2'])) { $_SESSION['ipAddressIsInRange2'] = $ipAddressIsInRange; } } else { $_SESSION['ipAddressIsInRange2'] = $ipAddressIsInRange; } ?>
Regards, Jan
I don't think you even understand much about object oriented concepts... I have never needed to use the global keyword inside of a class and I have definitely never put code like you are outside of the class when it could be used in a class method instead. You seem to be stuck in a procedural mindset. Perhaps you should watch one of these video series to catch up...
Yes, at least not a lot about the syntax in PHP... with PHP, for me it's an advantage when i don't need to use OOP... and, as far as possible, i also try to avoid functions in that language...;)
a "global" (with the include/procedural way) does also not help here so it seems:
public function index() { require_once $_SERVER ['DOCUMENT_ROOT'] . "/testing/IPTest.php"; global $ipAddressIsInRange; ... ... ...
Regards, Jan
Now i will try to use PHP "scriptlets" in Smarty template... escaped out of OO context!!
The other "solution" is to place the google analytics/statcounter.com tracking code in a site in an iframe...
The most idiotic and not elegant solutions are mostly working in IT, that's well-known to me! ;)
Regards, Jan
In WordPress "functions.php" i use that code, zero problems:
require_once ABSPATH.'/testing/IPTest.php'; $_SESSION['ipAddressIsInRange'] = IPv4\checkIPAddressIsInRange();
..but it's not in an OO context. Same as my test application. So the problem must be OO.
In WordPress "functions.php" i use that code, zero problems:
Of course you're not going to have problems; WordPress is mostly procedural. Are you unwilling to adapt to newer programming practices or something? OOP makes for much easier to maintain code, as well as reusable code.
It's ok. You're only about 20 years behind the times. Blame the modern framework for your lack of oop understanding... you might as well skip a modern framework and stick to your outdated procedural code and think you're smarter. WordPress is anything but modern/current as far as php goes. It's a relic.
OOP != OOP, i don't hope that is too complicated to unterstand.
Java and, for example, C# is REAL OOP... C++ and Java are not, it's just wannabe... that just my humble my opinion, maybe i'm completely wrong.
In Java, there is almost no other way than to use OOP. You can't programm ALL in a static way, completely impossible..
In Java i have a lot of experience in OOD & OOP. But the syntax and the concept of PHP or C++ OOP is all very different. In Java, i have a good OO knowledge, including the "advanced" things like design patterns, null interfaces, weak and strong references, serialization, reflection, etc. pp.
"...and think you're smarter."
No, but maybe my apps and websites are faster...;)
"WordPress is anything but modern/current as far as php goes."
Now i use WordPress only as a backend, that's the reason for my Laravel-frontend-Problems... but i don't have the time to read book for hundreds of hours about PHP OOP and Laravel...
Because of that: "learning by doing"...
P.S.: Now i've solved the problem with a laravel-independent PHP script, that will be called by SJAX GET request, and it returns 0 or 1. content-type ist text/plan, really simple.
If 1 then -> ip address is in range -> do nothing... If 0 then -> ip address is not in range -> javascript block x will be executed
Thanks to everyone and best regards, Jan
Please sign in or create an account to participate in this conversation. | https://laracasts.com/discuss/channels/laravel/cant-use-sessions-in-laravel-controller?page=2 | CC-MAIN-2018-43 | en | refinedweb |
Talk:Proposed features/IndoorOSM
Contents
- 1 Indoor vs outdoor tags
- 2 Namespaces like building:*, buildingpart:* and level:*
- 3 Building level connectors
- 4 building:levels
- 5 Default values
- 6 door=*
- 7 member roles
- 8 indoor=yes
- 9 Building-relation
- 10 Determining building level numbers
- 11 Data model
- 12 ground floor
- 13 Building outline
- 14 Overuse of relations
- 15 Building entrance/exit.
In my opinion you shouldn't mix up Tags needed for outdoor 3d rendering like windows, roof, facade, height and building:levels with indoor tags. Therefore I recommend to create two seperate proposal pages. --Saerdnaer 15:18, 1 December 2011 (UTC)
- Why not? From a use-case point of view it makes perfect sense - especially when looking at 3D rendering. You create a building model, and you want to render both the outside and inside of this building, so I would do exactly that and mix the tags. --Maru39 10:55, 2 December 2011 (UTC)
- I also do not see a strong need for a separation of Indoors and Outdoors in our model proposal. Currently, we mainly use existing tags and ideas, so regarding the outdoor appearance, the model does not provide much innovative stuff, doesn't it? --Gomar1985 14:50, 4 December 2011 (UTC)
Namespaces like building:*, buildingpart:* and level:*
I would only use namespaces if there is no other way, as for example there is already another tag with that name. OSM tags are not like XML where you need an prefix, if you want to extend a schema in the right way. --Saerdnaer 15:18, 1 December 2011 (UTC)
- Good point. Initially, I wanted to create some kind of hierarchy with this approach. But you might be right - I've changed the model (and the examples) accordingly. But what about the tag buildingpart:name? When I use name instead, the current OSM maps will look strange --Gomar1985 14:47, 4 December 2011 (UTC)
Building level connectors
You will need to be able to map connectors (escalators, elevators) between levels, and also indicate a connector direction (escalator goes FROM level x TO level y). For elevators there should be a way to indicate connection between levels, and also lack there of (some elevators might go from level 1 to level 10, but not stop on level 2 to 9). --Maru39 11:01, 2 December 2011 (UTC)
- This proposal didn't mention escalators and elevators yet. There are at least 3 options I'm aware of. In the following example an elevator stopping only on floor 1, 5 and 10 is use to demonstrate the differences:
- Multiple nodes, each with a level=* tag and equal coordinates connected throuth an way with highway=elevator (Indoor1, Screencast 9:20)
- one node with vway=yes and vway:highway=elevator which is a member in an relation with an levels=1;5;10 (Level Map)
- one node with vway=yes highway=elevator and levels=1;5;10 (Indoor2)
- I currently prefer the last option for mapping, but the first one for data processing. --Saerdnaer 13:29, 2 December 2011 (UTC)
- That is correct - I did not yet mentioned vertical connectors. I will do that in the following days. Yet, I'm not quite sure how to realize it in a proper way in our model --Gomar1985 14:48, 4 December 2011 (UTC)
- What about one node with vway=yes and vway:highway=elevator which is member of level=1 relation, and also member of level=5 relation and also member of level=10 relation.--Jakubt (talk) 03:20, 7 February 2014 (UTC)
building:levels
As far I see in your example building:levels is the total number of levels in this building. Other definitions say that it's only the number of levels above ground. So please clarify what it's value means in your proposal and how renderers should act, if there is no height=* Tag on that building. --Saerdnaer 19:32, 7 December 2011 (UTC)
- You are right. building:levels should contain the total amount of buildings (with no regard if they are above or below ground). Also the model assumes that level0 is the ground floor, so if height=* is not provided, a 3D renderer should approximate the height by some average value for a level (e.g. 4 meters) multiplied by the amount of levels. For a 2D rendered (birds perspective) this key is not relevant --Gomar1985 19:07, 12 December 2011 (UTC)
Definition of Height
I think there is an issue in the proposal in the way the height key is used. The reference building consists of two parts that are rectangular boxes. What about if you have a building that consists of one box with two towers on top? The height attribute would relate to the height including those towers. The area around the towers would be rendered falsely. I think a height attribute should only be used on rooms and corridors, as even one level might have different heights (two tower example could be such a building). 3D renderers have to calculate the height or use predefined models (the outer shell could be used to define such a model). --andreas.balzer 16:35, 25. Feb 2012
Default values
I think there should be a way to define a default value set for a building for example window size, breast, level height etc. There should also be some global defaults defined in this proposal, which renderers can use if there are no values. --Saerdnaer 19:32, 7 December 2011 (UTC)
- Good point. For doors it is "easy" to define a default value for the width and height, but what is the default width of a window? Window breast and window height also should be more easy --Gomar1985 19:07, 12 December 2011 (UTC)
door=*
Why don't we reuse entrance=*? --Saerdnaer 19:32, 7 December 2011 (UTC)
- Well. From a semantic point of view, entrance indicates that a door is just an entrance to a room, but no exit (in direction to the corridor for example). That is the reason, why I have choosen door=* --Gomar1985 19:07, 12 December 2011 (UTC)
In my opinion the indoor proposal shouldn't specify how a door is tagged other than using a door=* key. I suggest moving discussions on how to tag doors, windows, etc to different pages.
- I have a suggestion on doors User:Andreas.balzer/door-proposal-version2.
- Windows: User:Andreas.balzer/window
- Blinds: User:Andreas.balzer/blinds
- Rollershutters: User:Andreas.balzer/rollingshutter
-- andreas.balzer 13:55, 25 Feb 2012 (UTC)
member roles
Please state how far roles are mandatory or optional. --Saerdnaer 19:32, 7 December 2011 (UTC)
indoor=yes
Why an additional Tag? I in my opinion rooms, corridors and levels can be only inside a building. --Saerdnaer 19:32, 7 December 2011 (UTC)
- Actually I think we need an indoor tag, or at least an outdoor tag. What about buildings that have some kind of garden without roof in the middle? -- andreas.balzer 16:37, 25. Feb 2012 (UTC)
Building-relation
So the main relation for a building should be type=building, building=yes. Currently buildings are only mapped as multipolygon with type=multipolygon, building=yes. Why create an additional relation, wouldn't it be better to integrate the buildingparts into the multipolygon? Then maps for outdoor-uses can just show the multipolygon-relation, whereas indoor-maps can show more details. -- Skunk 15:21, 16 January 2012 (UTC)
- As I understand it, the type=building relation would have to contain multipolygons instead of simple outlines in more complicated situations. --LM 1 22:19, 13 February 2012 (UTC)
Determining building level numbers
"The ground level is always level_0". What is "the ground level"? In some buildings, mostly big ones like malls but also smaller ones with inclined surroundings this is often not clear because there are entrances from the outside "ground" which lead to different (inside) levels.
This also doesn't work for buildings where there are no classical levels (there are ramps with lots of different entrance levels). The latter is not very common, I agree. To get this done well we'd need a real 3D model at least for some cases. Or maybe allow fractional building levels (0.5, 1.5 for your usual split level building). --Dieterdreist 13:13, 20 January 2012 (UTC)
- I don't think that determining the level "0" is much of a problem. If the signs etc. inside the building designate any of the levels connected to the outside ground as the "ground level", use that one. Otherwise, you choose at will. --Tordanik 14:01, 2 February 2012 (UTC)
- Why not using 000.00 numbers for levels? The first three digits represent the usual levels, the first after the decimal seperator represents mezzanine levels and the last digit could represent connectors between two mezzanine or full levels, e.g. to build complex 3D constructions that have curved walls. -- andreas.balzer 14:00, 25 Feb 2012
I'd like to propose using a different name for the tag "level" in the level relation. It could be called "zlevel" and this might reduce some confusion. I understand the current level tag to be used as an ordering integer for the floors. It is not intended for labels. In the United States the ground floor is typically called "1". This is the name of the level. It is perfectly OK for the zlevel to be 0 and the name to be "1". Likewise, the Mezzanine may be called "M" or "Mezzanine" and have zlevel=1. I would also leave the option using non-integer values for the zlevel. This may be desirable if a new level is added between existing levels. --Sutter 4:59, 12 April 2012 (UTC)
Data model
I am glad to see this proposal, indoor mapping is really needed. A few remarks to the data model:
Choosing to map what is not there (empty space of rooms/hallways) rather than what is there (actual walls) has some advantages, but brings problems as well. The good part is that by mapping the shape of the rooms it will always be proportional - needed for rendering. Also some spaces are clearly separated, but there is no door between - just open space.
It cannot be assumed though that anything between the outer line and rooms are walls (some rooms go over several floors). This is very common in modern public buildings (most likely to be mapped) and should be solved properly. They are sort of vertical connections, only there is no connections, unless one can fly.
- What about an area with a key expressing that there is no floor, e.g. OpenArea=1;2;3 where 1;2;3 represent the levels of the connected area. I wouldn't use vway combinations as they represent a different meaning. In addition I'd suggest a tag indicating that a specific area cannot be accessed, something like nonWalkable=yes.. --andreas.balzer 14:06, 25. Feb 2012
So walls should probably get marked to. That would need duplication of all room outlines or mapping rooms as multi-polygons (needed anyway, some rooms have holes - corridor around the whole building for the simplest example).
Building
Having the whole building in one relation is definitely a good idea. The roles of its members should probably be only "level" to allow fractional levels (not as rare as it might seem). Also vertical connections should be directly part of this relation, since they do not belong to any particular floor
- I agree with the proposal to use "level" as the role instead of "level_*" The level integer value is stored separately as a property in the level relation. If this same data appears in two places it is inviting an inconsistency, for example if a user edits one location and forgets to edit the other. --Sutter 5:19, 12 April 2012 (UTC)
Floors
In the proposal all members except the outlines (shell) are buildingpart. That seems like a wasted field. I believe a set of values representing general purpose (rooms, connecting areas, common space, semi-outside like balcony or arcade...) can be found. This would be useful for routing to prefer hallways instead of walk-through rooms.
The doors in the example building are only part of the hallway, not of the rooms. That seems very wrong (even if your routing is working with it). My suggestion would be to connect the room outline with the hallway outline with a short (wall's thickness) way, this would than be tagged as door. It also solves problems with door tagging - see this.
- I actually have been trying to update the door proposal (User:Andreas.balzer/door-proposal-version2). Depending on how this IndoorOSM proposal changes I would adapt the updated version. --User:Andreas.balzer 04:10, 29 January 2012
Vertical connections
As stated above they should belong more to the building that to the floor. There should be two things distinguished the space of the whole staircase and the actual stairs. I suggest the staircase/elevator shaft/escalator area is a special relation - member of building. Only the small parts (entrance places) would belong to individual levels, the connecting elements would be part of staircase relation and connect to entrance points. (see image). Elevators would probably have only entrance points mapped with simple connection between accessible levels.(Similar for fireman poles and ladders - near zero horizontal area)
This could perhaps be used to map multi-level rooms mentioned above.
--LM 1 02:01, 22 January 2012 (UTC)
- There are some very interesting thoughts on how staircases could be mapped and rendered (Stairs and DE:Stairs_modelling as well as Proposed_features/Steps_features). It would be nice to see those integrated somehow. --andreas.balzer 04:06, 29 January 2012 (UTC)
ground floor
> The ground level is always level_0
Shouldn't be like that. Some countries use 1 as a ground floor and 0 as ground floor will break level numbering. Ground floor should be explicitely marked as such, so any numbering scheme may be used for floors. However if we consider buildings which lack floor 13 for example (hotels), we may need two parallel numbering schemes - physical floor numbers (may be 0-based) and "human-readable" level number for each floor.
- Yes, while 0-based ground floor numbering makes the most sense mathematically, there should be a place for arbitrary numbering (including M for medium floors, missing numbers (0,13...)) - one that would correspond to elevator labels - this ought to be language based (level:name:en). Our school has stupidly different numbers in Czech and in English (0-based×1-based) --LM 1 20:51, 26 January 2012 (UTC)
Building outline
I haven't had the chance to look detailed into the proposal (I'll do that later today). However I wonder whether there might be an issue regarding building outlines. As far as I understand it the proposal assumes all walls to be 90 degrees to the ground. Actually a building level might have an overlapping level above or below it. In those cases the area between the ground of the level and the ground of the next level has to be specified more detailed. Is it a straight or rounded connection, are there overlapping parts? In addition the facade image has to be splitted into images per level. Currently there is no editor support for it but it has to be added to the data set as well as to editors anyway.. --andreas.balzer 04:42, 29 January 2012 (UTC)
Overuse of relations
This proposal shares the tendency of some alternative indoor proposals to overuse relations. Not every relationship in a data model has to be mapped onto an OSM relation, and considering the problems that human mappers have with handling relations, I suggest that they should be avoided where reasonably possible.
Many buildings can be represented without any relations at all:
- The "is in building x" relationship is usually implicitly expressed by the feature being geometrically contained within the building area outline.
- The "is on level y" relationship can be expressed as a level=<number> tag on the feature.
Building attributes then go onto the outer way of the building (or multipolygon relation). --Tordanik 14:23, 2 February 2012 (UTC)
- Since using the relations plugin in OSM, I believe that human users problems with relations are caused by poor editor support of relations. They also make filtering easier. I am shortly in OSM, but relations just make sense.
- Something being in a building should not be implied at this level of detail, it can easily be under the building or over it. Not all buildings are strictly rectangular with no holes in them and the more public/important/worth mapping the more likely to have some complicated shape.
- Also the level relation seems to be useful. You cannot put a clear level label on any feature connecting more floors starting with stairs and ending with big rooms.
- And having a different representation of simple houses and complex buildings seems just stupid and more work for everyone. Easy should not compromise the quality. --LM 1 22:40, 13 February 2012 (UTC)
- Relations make sense when used well, but unfortunately it is very tempting to go overboard with them. As for your specific concerns:
- It will be relatively rare to have two buildings or other leveled structures overlapping in such a way that it is not clear which a feature with a level tag belongs to. Tunnels or bridges crossing the building outline will not be a problem, because these will not have level tags and therefore will not mistakenly be interpreted as features within the building. Hence, "usually" implied. In the other cases, just use one, non-nested relation for the entire building.
- The level tag, in the context of an approach as the one outlined by myself here, would not be intended for labels. It would be used for simple, ordered numeric values that could also be used to define ranges, e.g. for stairs or multi-level rooms. Labels would be something to be defined on the building as a whole, usually just by defining a labeling scheme (most buildings are using one of a few popular variants).
- That being said, easy inevitably needs compromise quality if we cannot have both. This is a crowd sourcing project, so making it easy to add and edit data is one of the core ideas behind the whole thing. I also fail to see how using different representations for simple and complex buildings necessarily means more work for everyone. From my perspective, it looks as if it would be slightly more work for users of the data, but probably less work for mappers? --Tordanik 20:07, 15 February 2012 (UTC)
- We would probably have a different view on how many relations are needed for it to be overboard. I am fine with quite a lot of them (not infinitely). By saying that "Easy should not compromise the quality" I meant that if choosing, I would usually pick more complicated, higher quality. This proposal seems like a reasonable compromise. (even more detailed would contain 3D outlines with individual node's coordinates tagged, general floor plans that could be inherited for all the levels and changed... - that would (as I see it) bring more complexity than useful information). What you suggested emphasises easiness too much at the cost of detail/quality (my view).
- Different tagging of buildings based on complexity brings work for mappers - they have to learn two types of tagging, decide which one to use, remap what is done too simply... This does not mean that there should not be a way to map less detail and add more later/someone else. Altogether the proposed solutions seems easier to work with for me (so it does not compromise easiness or quality in this case). --LM 1 11:11, 9 March 2012 (UTC)
Building entrance/exit.
It is very unclear how the etrances from the building should be tagged. Here are the (sometimes contraversial) pieces of mosaique:
- It is mentioned that they are nodes having role entrance_exit in the main relation.
- In the example it is shown that they have role entrance.
- The markup for notes themseves is unclear, however possibly they are marked as door=*
- It is not clear if they should be members of ground level floor or not. You mention that door are part of the level relation, but in your example the is no node present.
- What if the node is marked as door=yes and it is on the edge of the room area? Is it automatically dor to that room? In your article you suggest that entrances to rooms are part of the room relation, however in wiki you model room as area (and in some of the examples it seems that it is sufficient if several nonclosed ways which for together closed loop are in lever relation next to each other).
- You introduce new door=* to already existing group consisting of entrance=*, barrier=door and door=*. I suggest rather reuse them. The most relevant in this case is widely used entrance=* which is in fact the lowest level of information wh need (point of entry/exit). I would use the door=* scheme in addition in casa that we need to mark other properties of this entrance and when the entrance is not gate, gap in wall or something else. Althought you expressed semantic reservations to use entrance=* in discussion above, in your work you have originally prposed building:entrance=* yourself so it sould not be that bad after all ;)
If you do not mind I would like to correct the proposal to solve the ambiguities mentioned. --Jakubt (talk) 02:55, 7 February 2014 (UTC) | https://wiki.openstreetmap.org/wiki/Talk:Proposed_features/IndoorOSM | CC-MAIN-2018-43 | en | refinedweb |
here's my code:
#include <iostream> using namespace std; void func(int num) { num = num + 1; cout << num; } int main() { int num2 = 5; cout << num2; func(num2); cout << num2; func(num2); cout << endl << endl; system("PAUSE"); }
when the program runs, it yields an output screen that looks like this,
5656
press any key to continue...
as it should, however I'm wondering if there's a way to pass the variable "num2" on to the function "func()", change the data in "num2", and then return back to the main function with the newly updated "num2" variable. ultimately what I would like the program to do is increase "num2" by 1 every time "func()" is called.
EXAMPLE... what I want my output screen to look like is this,
5667
press any key to continue...
I know that I could just increase the value of "num2" inside of the main function. more or less, this is just a sample code of the full thing that I'm trying to accomplish, so please don't provide this as a solution.
I've alreadey considered making the function return the value of "num" and using the statement "num2 = func(num2);", so please don't provide that as an answer. I'll use that if there's no other way, however it just seemed possible to do it other ways.
correct me if I'm wrong, but I think you can do it with pointers. I don't know how but I sure that's how you would do it. given that passing a variable to a function realy just passes it's data to the function, I figured that you could pass the pointer for a variable to the function and allow the function to manipulate that variable.
thanks for the help... if there's no solution, just tell me and I'll use my other solution. I've been programming for a while, so don't worry about saying anything I won't understand. | https://www.daniweb.com/programming/software-development/threads/327027/how-to-manipulate-variables-with-functions | CC-MAIN-2018-43 | en | refinedweb |
Hey everybody,
I know that this is certainly not the most efficient solution for this, but I am a beginner and am struggling through it. Right now I have it where all of the words that are passed through the function are title cased. However, whenever I try to return (or even console.log) titleCaseArray, I get "cannot read property “0” of undefined. Anybody know why that is?
Thanks,
David
Your code so far
function titleCase(str) { var arrayOfStrings = str.toLowerCase().split(" "); var titleCaseArray = []; for (i = 0; i <= str.length; i++) { var firstLetter = arrayOfStrings[i][0]; var restOfWord = arrayOfStrings[i].slice(1, arrayOfStrings[i].length); var bigCase = firstLetter.toUpperCase() + restOfWord; titleCaseArray.push(bigCase); } return titleCaseArray; } titleCase("I'm a little tea pot");
Your browser information:
Your Browser User Agent is:
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.73 Safari/537.36.
Link to the challenge: | https://www.freecodecamp.org/forum/t/title-case-a-sentence-cannot-read-property-0-of-undefined/175762 | CC-MAIN-2018-43 | en | refinedweb |
[Blog
Blog
public delegate int ChangeInt(int x);
// Define a method to which the delegate can point
static.
Using an Anonymous Method
With C# 2.0, anonymous methods allow you to write a method and initialize a delegate in place:
ChangeInt myDelegate = new ChangeInt(
delegate(int x)
{
return x * 2;
}
);
Console.WriteLine(“{0}”, myDelegate(5));
Using a Lambda Expression));
Using a Lambda with Two Arguments));
Statement Lambda Expressions.
Lambda Expressions that Return Void
public
public delegate void OutputHelloToConsole();
static void Main(string[] args)
{
OutputHelloToConsole o = () =>
{
Console.WriteLine(“Hello, World”);
};
o();
}
The Func Delegate Types Action Delegate Types”); });
}
}
Expression Trees
Lambda expressions can also be used as expression trees. This is an interesting topic, but is not part of this discussion on writing pure functional transformations.
[Blog Map] [Table of Contents] [Next Topic] … 🙂# 🙂 ?" 😉 ‘statement lambdas’ is ‘blocks’. ‘P’ 🙂
I generally pronounce "=>" as "goes to", but I also like "maps to" and "evaluates to".
@chadmyers: Remind me never to involve myself in any Ruby circles. 😛
@chadmyers, the post on closures is now written:
-Eric
If you are using Linq to SQL, instead of writing regular Linq Queries, you should be using Compiled Queries. 🙂.));
Thanks.
Thanks
Al true;?
-Eric ‘lazy’. ‘materialize’ the paragraphs I’m interested in, and contents of the paragraphs into a List<T>. Then subsequent iterations are over the much shorter List<T> instead of over the whole document.
-Eric?
Thanks for the very clear explanation!
What I am additionally looking for is the c# specification that explains why the following code, taken from your example above, works:
static List<T> MyWhereMethod<T>(IEnumerable<T> source,
Func<T, bool> predicate) {…}
…
int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 };
List<int> filteredList = MyWhereMethod(source,
i => i >= 5);
How does the resolving work for the function-call with signature List<int> MyWhereMethod(IEnumerable<int>, Func<T, bool>)?
There isn’t such a signature in this namespace, at least not literally. Contrary to my expectations the compiler apparently is smarter than I thought and resolves to the given MyWhereMethod<T>.
Why is that?
@Benjamin,
The syntax that you’re asking about is how you write an anonymous method in C# 2.0. Because ChangeInt takes a delegate as an argument, it is valid to use the delegate keyword to write an anonymous method in-line, and pass it to the method. Lambda expressions are simply more terse syntax for writing an anonymous method.
@Carl,
This works because of the type inference that comes into play with generic methods. (Generic methods are those that are defined with a type parameter, i.e. List<T> MyWhereMethod<T>(IEnumerable<T> source, Func<T, bool> predicate). Type inference for generic methods is defined in section 7.4.2 of the C# 3.0 specification. The C# compiler goes through a specific set of steps when determining which method can bind to a method call, and which binding will have the highest priority, and will get the binding. Because the name is MyWhereMethod in the method call, and that is the name of the method, that method call will go through the type inference algorithm to decide whether the compiler can bind to the generic method. The first step in deciding whether the compiler can bind to the method is to infer the type of the generic parameter. The source argument is an array of integer, which implements IEnumerable<int>, so the compiler can infer the type of int for T, and see if the method binds properly. It then infers the type of i in the lambda expression as int, and infers the return type of List<int>, which exactly matches the value to the left of the equals sign. When the compiler infers T as int, because everything compiles properly, the compiler can then bind the method call to the generic method.
-Eric
Thanks for trying to explain, though this confuses me. You wrote: "Because ChangeInt takes a delegate as an argument". But I see that it takes an int, named x:
public delegate int ChangeInt(int x);
As far as I understand, you have a delegate named ChangeInt, to which you pass yet another delegate, that has a anonymous method:
ChangeInt myDelegate = new ChangeInt(delegate(int x)
{
return x * 2;
}
What does "initialize a delegate in place" mean? I thought you already defined a delegate (ChangeInt) and initialized it with this line: new ChangeInt.
Hi Benjamin,
Sorry, I didn’t take the proper time to write the last answer. Here is how this works:
// the following is the *definition* of a delegate type
public delegate int ChangeInt(int x);
// the following is a *declaration* of a delegate
ChangeInt myDelegate = new ChangeInt(
delegate(int x)
{
return x * 2;
}
);
In a declaration, when newing up the instance of a delegate, you can pass the name of a method that has the correct signature, which is how the example immediately preceding the one that we’re discussing works. Or when newing up the instance of a delegate, you can write an anonymous method right there, in place. This uses the delegate keyword, where you declare the types of the arguments and the body of the method immediately following ‘delegate’.
Does that make sense?
-Eric
I think I do. In the second example there is not yet a definition of a delegate, but you make one with
ChangeInt myDelegate = new ChangeInt(delegate(int x) {return x * 2;});
If that’s correct, than I understand. Thank you very much for taking the time Eric!
While fiddling with code, I noticed you can also write this:
public delegate int ChangeInt(int x);
ChangeInt myDelegate = delegate(int x) { return x * 2; };}
It produces the same output, no errors. Is there any difference between the two?
Hi Benjamin,
No, there is no difference between the two. The compiler can initialize the delegate with the anonymous method that you create with the delegate keyword. This is similar to code that you could write like this:
ChangeInt myDelegate = (int x) => { return x * 2; };
or
ChangeInt myDelegate => x => x * 2;
For what its worth, I never use the delegate keyword, as you can always use the lambda expression syntax. After you become accustomed to lambda expression syntax, it becomes more natural, in my opinion.
-Eric
Excellent article! You made it so easy to understand. Thank you so much!
Thanks Eric for the Nice Article.
Thanks for the article, it helped clear a few things up for me!
I have a question though and I may be completely missing something here, but take the following code from the article:
int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 };
foreach (int i in source.Where(x => x > 5))
Console.WriteLine(i);
Is there an advantage to using Lambda to extract data from the array rather than LINQ?
Hi Andrew,
Query expressions are directly translated to equivalent expressions using lambda expressions. The nomenclature is that when you express them using lambda expressions, they are written in ‘method syntax’.
For example, another way to write the query that you referred to is like this:
int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 };
var q = source.Where(x => x > 5);
foreach (int i in q)
Console.WriteLine(i);
This is exactly the same as if you write this:
int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 };
var q = from x in source
where x > 5
select x;
foreach (int i in q)
Console.WriteLine(i);
The second form is translated to the first by the compiler.
I’ve written a few things that discuss this:
For what it’s worth, I have gravitated completely to using ‘method syntax’. There are queries that you can write in method syntax that you can’t write using query expressions, but the reverse is not true, so I personally find it more convenient to consistently use method syntax.
-Eric
Thanks a lot EricWhite for your efforts. Your tutorial is so simple yet so authoritative. Its a breeze to learn lambadas/FP through your tutorial(s). Would you care to write some day on Expression trees using lambadas as mentioned. In the mean time can you suggest some resources which are as good as yours for learning Expression trees through FP.
-Panks
Hi Panks, I’m glad it’s useful. The SharePoint 2010 managed client side object model (CSOM) includes an interesting use of lambda expressions that are processed by expression trees. I’m planning on writing a blog post/MSDN article that explains that use of lambda expressions. It would be fun to also write a more general explanation of expression trees.
-Eric
I loved reading this. Now I know lambda.
Thanks everyone
Really good article to understand Lamda Expression
@Eric: Brilliant Article
Although I have a question: AS if can you please let me know ,wat are the scenarios where we should use each of the following : anonymous delegates vs. functional calls vs. lambda expression to optimize the performance of the application.
What is the advantage of LAMBDA Expression over standard SQL
I see what it does but I really don't know why we are all still coding? 30 years on and the code gets more complex to do the same old things. One day someone will design th "codeless development system"
Interesting article though, I will need to put some in a project now as it won't be fashionable if you don't put the latest techy stuff in(just kidding)
P
Cheers
Hi,
I was reading your article and I would like to appreciate you for making it very simple and understandable. This article gives me a basic idea of lambda expression in c# and it will help me a lot. This link……/Lambda%20Expression%20in%20c
I have found another nice post over internet. It is also helpful to complete my task.
Thank you very much!.
dabbu-csharphelp.blogspot.in/…/lambda-expression.html
I hope this blog is also useful to those users who wants to know about lambda expressio that how to find records from list using lambda expression.
thanks to sharing this useful article.
Lambda expressions take the relatively simply, and add a layer of complexity. They offer nothing that cannot be done in a simpler, more direct way. The emperor is naked.
The code containing the "lambda expression":
int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 };
var q = source.Where(x => x > 5);
foreach (int i in q)
Console.WriteLine(i);
Is the same as:
int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 };
foreach (int i in source)
if (i > 5)
Console.WriteLine(i);
Which is simpler? Which executes more quickly? Exactly.
Sometimes, simpler is better. Especially when it comes to maintaining a huge code base. "Cool" does not equal "better" in the real world.
Good to see that such type of articles are there for us(The beginers) 🙂 | https://blogs.msdn.microsoft.com/ericwhite/2006/10/03/lambda-expressions/ | CC-MAIN-2016-50 | en | refinedweb |
Windows PowerShell
Updated: August 10, 2011
Applies To: Operations Manager 2007 R2
Microsoft Operations Manager 2007 R2 now includes the ability to run Windows PowerShell scripts from within management packs by using new module types provided in the Windows Core Library management pack. This section covers the capabilities, usage, and troubleshooting of those Windows PowerShell modules.
What is Windows PowerShell?
Windows PowerShell is a command-line shell and scripting language that can be used to automate many tasks. Windows PowerShell includes small utility programs, called cmdlets, that can either be run directly from the command shell prompt or called from within a batch file or script. Cmdlets can be used by themselves, or they can be combined with other cmdlets to perform complex administrative tasks. Unlike traditional command-line environments that work by returning text results to the end user or routing (“piping”) text to different command-line utilities, Windows PowerShell manipulates .NET Framework objects directly. This provides a more robust and efficient mechanism for interacting with the system.
Windows PowerShell Hosting in Operations Manager
In previous versions of Operations Manager, it is possible to run Windows PowerShell scripts from management packs by calling the Windows PowerShell executable directly, which often resulted in unacceptable resource utilization. Operations Manager 2007 R2 now provides modules for running Windows PowerShell scripts from within management pack workflows. These scripts are run via hosted Windows PowerShell runspaces. Existing Monitoring Host processes require far less resources than running scripts out of process by using the Windows PowerShell executable.
The Windows PowerShell hosting functionality is available in many workflow types, including discoveries, rules, monitors, agent tasks, diagnostics and recoveries. To enable use this new functionality, a number of new public module types, defined in the Windows Core Library management pack, are provided with Operations Manager 2007 R2 for use by advanced management pack authors. These modules include:
- Microsoft.Windows.TimedPowerShell.DiscoveryProvider
- Microsoft.Windows.PowerShellDiscoveryProbe
- Microsoft.Windows.PowerShellPropertyBagProbe
- Microsoft.Windows.PowerShellTriggerOnlyProbe
- Microsoft.Windows.PowerShellProbe
- Microsoft.Windows.PowerShellWriteAction
- Microsoft.Windows.PowerShellPropertyBagWriteAction
Windows PowerShell Module Inputs
Windows PowerShell modules have a base set of common inputs. This section provides general descriptions of these inputs. For more specific details about syntax and examples, refer to the module documentation.
Windows PowerShell modules recognize the following common parameters:
ScriptName
This parameter is used as an identifier for event logging and tracing purposes. This value is a logic name only and not a file name. Windows PowerShell scripts used by the modules are never stored to the local file system as stand-alone files.
ScriptBody
This parameter contains the actual Windows PowerShell script to be run by the module.
SnapIns
This optional parameter can be used to pass a list of one or more snap-ins (which are used to register sets of cmdlets and providers with Windows PowerShell) that must be loaded within the runspace for the given script. This method of loading snap-ins is preferred over loading the snap-ins from within the Windows PowerShell script because it allows the modules to optimize loading and reuse these snap-ins.
Parameters
Parameters are used to pass information such as static values or variables from runtime into Windows PowerShell scripts, where they can be accessed as variables.
Parameters are defined within the management pack as Name/Value pairs. Each Name/Value pair in the collection is internally added to the
$args string array variable in the same order in which they are listed in the collection.
For example, consider the following parameters in this XML code snippet:
There are two ways to access these parameter Name/Value pairs in script. The first way is to access the
$args string array directly. In the following sample code, the script is accessing the
$args elements in order to assign their values to named variables.
The second and easier way to access parameter Name/Value pairs in the script, is to use the
Param function. The
Param function takes the named variables as arguments. The named variables must be listed in the same order as the list of Name/Value pairs in the collection. The
Param function must be the first line in your script. In the following code sample, the script is assigning the
$args elements to named variables by simply calling the
Param function.
Since Windows PowerShell scripts can access the variables to use the values, it is possible to test the script from a Windows PowerShell command prompt by simply setting the variables and running the script.
The follow table lists examples of possible parameter cases and the behavior for each at script runtime. Note that the variables in the Variable name column are available only if you use one of the above mentioned parameter access methods and explicitly declare their names.
In the following example, two parameters – a string and an integer – are passed to the Windows PowerShell script:
<Task ID="SamplePowerShellTask" Accessibility="Public" Enabled="true" Target="SCLibrary!Microsoft.SystemCenter.HealthService" Timeout="300" Remotable="false"> <Category>Maintenance</Category> <ProbeAction ID="PA" TypeID="Microsoft.Windows.PowerShellProbe"> <ScriptName>PowerShell Parameter Test Script</ScriptName> <ScriptBody><![CDATA[ Param($stringArg, $intArg) ]]></ScriptBody> <Parameters> <Parameter> <Name>stringArg</Name> <Value> <![CDATA[This is my string arg with formatting]]></Value> </Parameter> <Parameter> <Name>intArg</Name> <Value>5</Value> </Parameter> </Parameters> <TimeoutSeconds>60</TimeoutSeconds> </ProbeAction> </Task>
You can also pass parameters as a single XML data item, which the script can retrieve by using XPath queries. For example, given the following script definition for the module:
…the parameter values could extracted using the following command:
…which would produce the following output:
PowerShell Script Output
Windows PowerShell modules can output discovery data, property bags, or serialized .NET objects, depending on the type of module. In both cases, the results will be returned by the script by using the Windows PowerShell Pipeline.Output object.
In the case of a .NET object, the returned object will be interpreted by the Windows PowerShell module into an Operations Manager data type. A single data item which contains a collection of each of the objects returned from the Windows PowerShell script is returned upon completion of the script.
Scalar types are returned as property elements. Complex types are returned as <Object> elements, and any public properties returned as subelements. For example, the following System.String object:
…will return the following XML to Operations Manager:
Complex types returned by a Windows PowerShell script are presented back to the Operations Manager module as an <Object> element, with any properties on the original complex type being presented as subelements of the <Object> element. For example, this .NET object:
namespace Sample { class SampleComplexType { public string SampleString { get { return “Sample”; } } public int SampleInt { get { return 1; } } public SampleComplexType2 SampleSubType { get { return subtype; } } public subtype = new SampleComplexType2(); } class SampleComplexType2 { public SampleComplexType2() {} public string SampleString2 { get { return “Sample2”; } } } }
…is returned to Operations Manager with the following XML:
<Object type="Sample.SampleComplexType"> <Property name="SampleString" type="System.String">Sample</Property> <Property name="SampleInt" type="System.Int32">1</Property> <Object name="SampleSubType" type="System.String"> <Property name="SampleString2" type="System.String">Sample2</Property> </Object> </Object>
Scripting Considerations for Operations Manager
This section covers special considerations for Windows PowerShell scripts hosted from within Operations Manager 2007 R2 modules.
Application Isolation and Performance
By default, each script instance will be hosted in a separate runspace in the default application domain. This behavior can be overridden by setting the Isolation registry key to a value of 1.
Application isolation can enhance system stability by preventing simultaneously executed Windows PowerShell scripts and cmdlets – most of which were designed to be called from a single-threaded application – from interfering with each other, but can also cause a severe performance degradation.
To increase performance while running in Isolation mode, AppDomains will be pooled to alleviate the overheard required to instantiate them. Runspaces will not be shared or reused, but they will be cached on each module type..
Hosting-related Registration Keys
Some default aspects of script execution and behavior in Operations Manager-hosted Windows PowerShell scripts can be customized by setting registry keys. These values can be found in the following node in the registry:
The following table shows the registry keys used to control script execution behavior for Windows PowerShell scripts run from an Operations Manager module:
Other Scripting Considerations
Because Windows PowerShell scripts executing from within Operations Manager modules are running in the context of a service, any method or function calls that prompt for user input will throw “not implemented” exceptions. These application programming interfaces (APIs) include:
- PromptForChoice
- PromptForCredential
- ReadLine
- ReadLineAsSecureString
Any method or function calls that are used to write output will be redirected by the Operations Manager host into trace logs that can be used for debugging purposes. For more focused debugging, this output can also be echoed to the ModuleDebug and DbgOut trace logs if the TraceEnabled override is set for the host workflow.
The table below lists the trace level used for each Write API for Windows PowerShell script tracing only (the trace level for Module Debug is always ModuleDebug).
See Also
ReferenceWindows PowerShell
Windows PowerShell Snap-ins | https://msdn.microsoft.com/en-us/library/ee809360.aspx | CC-MAIN-2016-50 | en | refinedweb |
Forum:Help Bring Dawn Back
From Uncyclopedia, the content-free encyclopedia
Welcome to the *OFFICIAL* "Help Save Dawn" thread.
Introduction/Rant/Rules
Okay. Here's the problem. Dawn is a very well-known Pokemon article with many references and a long history on Uncyclopedia. However, it's been huffed (and after I took on the mantle of restoring it to its former glory, CVP'd) and the mantle is too much for me to bear alone, mostly due to the fact that everyone has differing opinions on how the article should ideally be. I think I've really come far, but I just can't think of how to add extra "perfect Uncyclopedia article" sparkle to the article (which, as you've all made perfectly clear, is the only way this article will be saved). Therefore, I'm enlisting help.
Update: The Pokemon version has been moved. In accordance with advice below, I'm making an entirely different Dawn article. And requesting that the Pokemon Dawn be entirely edit-blocked. (Rules updated on 20:06, 8 October 2007 (UTC))
Official Rules for Helping
1. If you want to contribute something along the lines of generic Pokemon crap, do so here. I have created a special version of the page identical to the first version I submitted to Pee Review in order to keep the Uncyclopedia Dawn in-joke/meme (which is roughly "she's the sexiest girl ever") from nuking my page spontaneously.
2. You must have good ideas. Anything that is not a good idea will be nuked.
3. NO ANONYMOUS IP EDITS. I cannot stress this enough. Anonymous edits tend to be bullsh*t, and one of them was the cause for the Dawn CVP. If you want to help, log in first.
4. Do NOT create a major overhaul without a good reason. Even if you have a good reason (and I mean "This page does NOT exist" good) don't do anything without going to the talk page first. (Man, I'm so happy that page isn't a red link anymore...*happy sob*
5. I have the final word. It's on MY user page, after all.
6. There is no category and no userbox for you all. This is out of the goodness of your hearts. (I'd make a category and userbox, but lately my userboxes are getting nuked for no apparent reason, and I don't like boxless categories when we're talking about userpages.)
7. Sign Up Below Or Die. I have an army of Starcraft units (and a Grue) at my disposal, and will not hesitate to use them.
--User:Banjo2e/SIGGY 04:17, 29 September 2007 (UTC)
Helpers
--Narf, the Wonder Puppy/I support Global Warming and I'm 100% proud of it! 05:51, 29 September 2007 (UTC)
Well I don't like dying, it's like, when I get there all God does is make fun of my pants.
Additional Discussion Begins Here
- I already gave it a Pee Review, but sure, I'll help out... After finishing several others. Beans!--Narf, the Wonder Puppy/I support Global Warming and I'm 100% proud of it! 05:51, 29 September 2007 (UTC)
- /me dies. Urk. --Whhhy?Whut?How? *Back from the dead* 10:14, 29 September 2007 (UTC)
- I have to state that the current state of events are, frankly, disturbing. Whenever the topic Bring Dawn back and the topic Vampire template are next to each other or in close proximity I tend to find this quite suspicious, but who to blame ? high school chicks or evil vampire overlords ? --Vosnul 10:58, 29 September 2007 (UTC)
- High school chicks? Dawn is in elementary school! Those tricky ten year olds... Fresh Stain Serq Fet of Pokemon (At your service) 14:25, 29 September 2007 (UTC)
- Actually, she's an adult actress. You know, Uncyclopedia-wise. --User:Banjo2e/SIGGY 17:08, 29 September 2007 (UTC)
- Surely vampires would not want to bring dawn back, what with the hating sunlight thing and all? --Whhhy?Whut?How? *Back from the dead* 20:53, 29 September 2007 (UTC)
- Dawn should die. Also, starcraft units suck against Dune units, and I have complete and utter control over grues. --Lt. High Gen. Grue The Few The Proud, The Marines 03:41, 30 September 2007 (UTC)
- If this is aboutthe Dawn Astroid Orbiter, which dosen't exist, that none of you should know about I will call the CIA. (It was public, but we haven't had the CIA in Uncyclopedia for about 2 seconds. They're 1 second late.) --Lt. High Gen. Grue The Few The Proud, The Marines 03:43, 30 September 2007 (UTC)
- I've said it before, I'll say it again just to be annoying: Concept, concept, concept. It needs one. Badly. – Sir Skullthumper, MD (criticize • writings • SU&W) 03:59 Sep 30, 2007
- The best help I can give is this: READ THIS LINK. I read it all the time, just for ideas. It really, really helps. Also there's this. Both of those are very helpful when you're writing. If you follow what those tell you, I guarantee that the page will at least be decent. P.M., WotM, & GUN, Sir Led Balloon
(Tick Tock) (Contribs) 04:22, Sep 30
- So tell us, if this is ever taken off of CVP, exactly what format will you follow? What will the plot be? It better not just center around a "super-hot ten-year-old" either. Try incorporating other uses of the word "Dawn" into the article, like the sunrise, or the Hammer of Dawn from Gears of War. The article shouldn't be limited to one thing. Conniving 02:53, 7 October 2007 (UTC)
- *Sigh.* You just had to bump this, didn't you. Well then, I'd say that I'd have written a page named Dawn about sunrise, perhaps with a few subtle references to Pokemon. But, the page would still not be about pokemon, it'd be about sunrise. Now, the only reason I say this is because I never watched the show beyond the first few episodes(the ones about the "first generation" games) and I've only played the 1st generation games. Still, if you know about pokemon and think you can pull off a poke-centric page that is original and humorous, then by all means do. As I said above, read HTBFANJS. It'll make you write:11, Oct 7
New Comment Section
In accordance with the advice of a smart guy I have performed a major overhaul. Dawn is now going to be a completely different page. Dawn (Pokemon) is going to stay how it is (and I mean it; I formally request that once it's in the main namespace it gets completely edit-blocked) and so is the entirely-editable Sexy Version. However, the main Dawn article is now going to be new and shiny. However, if the Pokemon Dawn article dies, I'm going to nuke you all with my army of Starcraft units.
Input would be appreciated. Thanks. --User:Banjo2e/SIGGY 20:06, 8 October 2007 (UTC)
- What about Dawn cleaning fluid? Where's the love? Unsolicited conversation Extravagant beauty PEEING 00:31, 9 October 2007 (UTC)
- I thought about it right after I had to save and leave to do important stuff. Don't worry, it won't be neglected. And even if it were, it's still under the Pokemon version of Dawn. Both of them. So it doesn't really matter that muchly. Or maybe it does. I don't know. I'm just ranting for no apparent reason. --User:Banjo2e/SIGGY 12:46, 9 October 2007 (UTC)
ERROR 403 - REQUEST DENIED!. We are not going to do another Pokemon character that doesn't cover What is funny and what is not. --Jtaylor1 14:17, 14 October 2007 (UTC)
- Uh... you're a little late... by a few months... Unsolicited conversation Extravagant beauty PEEING 16:50, 14 October 2007 (UTC)
- I'm not an expert on the subject matter, but
does this mean the project is officially dead? Pentium5dot1 06:09, 17 October 2007 (UTC)Um, oops - I didn't realize that Banjo2e got a username change to Administrator. Hence the links in this topic need fixing. Pentium5dot1 06:27, 17 October 2007 (UTC) | http://uncyclopedia.wikia.com/wiki/Forum:Help_Bring_Dawn_Back | CC-MAIN-2016-50 | en | refinedweb |
If a user experiences a crash they will be prompted to submit a raw crash report, which is generated by Breakpad. The raw crash report is received by Socorro which creates a processed crash report. The processed crash report is based on the raw crash report but also has a signature, classifications, and a number of improved fields (e.g. OS, product, version). Many of the fields in both the raw crash report and the processed crash report are viewable and searchable on crash-stats. Although there are two distinct crash reports, the raw and the processed, people typically talk about a single "crash report" because crash-stats mostly presents them in a combined way.
Each crash report contains a wealth of data about the crash circumstances. Despite this, many crash reports lack sufficient data for a developer to understand why the crash occurred. As well as providing a general overview, this page aims to highlight parts of a crash report that may provide non-obvious insights.
Note that most crash report fields are visible, but a few privacy-sensitive parts of it are only available to users who are logged in and have "minidump access". A relatively small number of users have minidump access, and they are required to follow certain rules. If you need access, file a bug like this one.
Each crash report has the following tabs: Details, Metadata, Modules, Raw Dump, Extensions, and (optional) Correlations.
Details tab
The Details tab is the first place to look because it contains the most important pieces of information.
Primary fields
The first part of the Details tab shows a table containing the most important crash report fields. It includes such things as when the crash occurred, in which product and version, the crash kind, and various details about the OS and configuration of the machine on which the crash occurred. The following screenshot shows some of these fields.
All fields have a tool-tip. For many fields, the tool-tip describes its meaning. For all fields, the tool-tip indicates the key to use when you want to do searches involving this field. (The field name is usually but not always similar to the search key. E.g. the field "Adapter Device ID" has the search key "adapter_device_id".) These descriptions are shown in the SuperSearchFields API and can be modified by crash-stats superusers.
The fields present in this tab vary depending on the crash kind. Not all fields are always present.
The start of the "Signature" field tells you what kind of crash it is. Some special-purpose annotations are used to indicate particular kinds of crashes.
Abort: A controlled abort, e.g. via
NS_RUNTIMEABORT. (Controlled aborts that occur via
MOZ_CRASHor
MOZ_RELEASE_ASSERTcurrently don't get an
Abortannotation, but they do get a "MOZ_CRASH Reason" field.)
OOM | <size>, where
<size>is one of
large,
small,
unknown: an out-of-memory (OOM) abort. The
<size>annotation is determined by the "OOM Allocation Size" field; if that field is missing
<size>will be
unknown.
hang: a hang prior to shutdown.
shutdownhang: a hang during shutdown.
IPCError-browser: a problem involving IPC. If the parent Firefox process detects that the child process has sent broken or unprocessable IPDL data, or is not shutting down in a timely manner, it kills the child process with a crash report. These crashes will now have a signature that indicates why the process was killed, rather than the child stack at the moment.
When no special-purpose annotation is present and the signature begins with a stack frame, it's usually a vanilla uncontrolled crash. The crash cause can be determined from the "Crash Reason" field. Most commonly it's a bad memory access. In that case, on Windows you can tell from the reason field if the crash occurred while reading, writing or executing memory (e.g.
EXCEPTION_VIOLATION_ACCESS_READ indicates a bad memory read). On Mac and Linux the reason will be SIGSEGV or SIGBUS and you cannot tell from this field what kind of memory access it was.
See this file for a detailed explanation of the crash report signature generation procedure, and for information on how modify this procedure.
There are no fields that uniquely identify the user that a crash report came from, but if you want to know if multiple crashes come from a single user the "Install Time" field is a good choice. Use it in conjunction with other fields that don't change, such as those describing the OS or graphics card, for additional confidence.
For bad memory accesses, the "Crash Address" field can give additional indications what went wrong.
- 0x0 is probably a null pointer deference[*].
- Small addresses like 0x8 can indicate an object access (e.g.
this->mFoo) via a null
thispointer.
- Addresses like 0xfffffffffd8 might be stack accesses, depending on the platform[*].
- Addresses like 0x80cdefd3 might be heap accesses, depending on the platform.
- Addresses may be poisoned: 0xe4 indicates the address comes from memory that has been allocated by jemalloc but not yet initialized; 0xe5 indicates the address comes from memory freed by jemalloc. The JS engine also has multiple poison values defined in
js/src/jsutil.h.
[*] Note that due to the way addressing works on x86-64, if the crash address is 0x0 for a Linux/OS X crash report, or 0xffffffffffffffff for a Windows crash report, it's highly likely that the value is incorrect. (There is a bug report open for this problem.) You can sanity-check these crashes by looking at the raw dump or minidump in the Raw Dump tab (see below).
Some fields, such as "URL" and "Email Address", are privacy-sensitive and are only visible to users with minidump access.
The Windows-only "Total Virtual Memory" field indicates if the Firefox build and OS are 32-bit or 64-bit.
- A value of 2 GiB indicates 32-bit Firefox on 32-bit Windows.
- A value of 3 or 4 GiB indicates 32-bit Firefox on 64-bit Windows (a.k.a. "WoW64"). Such a user could switch to 64-bit Firefox.
- A value much larger than 4 GiB (e.g. 128 TiB) indicates 64-bit Firefox. (The "Build Architecture" field should be "amd64" in this case.)
Some crash reports have a field "ContainsMemoryReport", which indicates that the crash report contains a memory report. This memory report will have been made some time before the crash, at a time when available memory was low. The memory report can be obtained in the Raw Dump tab (see below).
Bug-related information
The second part of the Details tab shows bug-related information, as the following screenshot shows.
The "Report this bug in" links can be used to easily file bug reports. Each one links to a Bugzilla bug report creation page that has various fields pre-filled, such as the crash signature.
The "Related Bugs" section shows related bug reports, as determined by the crash signature.
Stack traces
The third part of the Details tab shows the stack trace and thread number of the crashing thread, as the following screenshot shows.
Each stack frame has a link to the source code, when possible. If a crash is new, the regressing changeset can often be identified by looking for recent changes in the blame annotations for one or more of the top stack frames. Blame annotations are also good for identifying who might know about the code in question.
Sometimes the highlighted source code is puzzling, e.g. the identified line may not touch memory even though the crash is memory-related. This can be caused by compiler optimizations. It's often better to look at the disassembly (e.g. in a minidump) to understand exactly what code is being executed.
Stack frame entries take on a variety of forms.
- The simplest are functions names, such as
NS_InitXPCOM2.
- Name/address pairs such as
nss3.dll@0x1eb720are within system libraries.
- Names such as
F1398665248_____________________________('F' followed by many numbers then many underscores) are in Flash.
- Addresses such as
@0xe1a850acmay indicate an address that wasn't part of any legitimate code. If an address such as this occurs in the first stack frame, the crash may be exploitable.
Stack traces for other threads can be viewed by clicking on the small "Show other threads" link.
If the crash report is for a hang, the crashing thread will be the "watchdog" thread, which exists purely to detect hangs; its top stack frame will be something like
mozilla::`anonymous namespace'::RunWatchdog. In that case you should look at the other threads' stack traces to determine the problem; many of them will be waiting on some kind of response, as shown by a top stack frame containing a function like
NtWaitForSingleObject or
ZwWaitForMultipleObjects.
Metadata tab
The Metadata tab is similar to the first part of the Details tab, containing a table with various fields. These are the fields from the raw crash report, ordered alphabetically by field name, but with privacy-sensitive fields shown only to users with minidump access. There is some overlap with the fields shown in the Details tab.
Modules tab
The modules tab shows all the system libraries loaded at the time of the crash, as the following screenshot shows.
On Windows these are mostly DLLs, on Mac they are mostly
.dylib files, and on Linux they are mostly
.so files.
This information is most useful for Windows crashes, because DLLs loaded by antivirus software or malware often cause Firefox to crash. Correlations between loaded modules and crash signatures can be seen in the "Correlations" tab (see below).
This page says that files lacking version/debug identifier/debug filename are likely to be malware.
Raw Dump tab
The first part of the Raw Dump tab shows the raw crash report, in JSON format. Once again, privacy-sensitive fields are shown only to users with minidump access.
For users with minidump access, the second part of the Raw Dump tab has some links, as the following screenshot shows.
These links are to the following items.
- A minidump. Minidumps can be extremely useful in understanding a crash report; see this page for an explanation how to use them.
- The aforementioned JSON raw crash report.
- The memory report contained within the crash report. Only crash reports with the
ContainsMemoryReportfield set will have this link.
- The unredacted crash report, which has additional information.
Extensions tab
The Extensions tab shows which extensions are installed and enabled.
Usually it just shows an ID rather than the proper extension name.
Note that several extensions ship by default with Firefox and so will be present in almost all crash reports. (The exact set of default extensions depends on the release channel.) The least obvious of these has an Id of
{972ce4c6-7e08-4474-a285-3208198ce6fd}, which is the default Firefox theme. Some (but not all) of the other extensions shipped by default have the following Ids:
webcompat@mozilla.org,
e10srollout@mozilla.org,
firefox@getpocket.com,
flyweb@mozilla.org,
loop@mozilla.org.
If an extension only has a hexadecimal identifier, a Google search of that identifier is usually enough to identify the extension's name.
This information is useful because some crashes are caused by extensions. Correlations between extensions and crash signatures can be seen in the "Correlations" tab (see below).
Correlations tab
This tab is only shown when crash-stats identifies correlations between a crash and modules or extensions that are present, which happens occasionally.
See also
- A talk about understanding crash reports, by David Baron, from March 2016.
- A guide to searching crash reports | https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Crash_reporting/Understanding_crash_reports | CC-MAIN-2016-50 | en | refinedweb |
>>."
I'm addicted (Score:5, Interesting)
I love ZFS, if one can love a file system. Even for home use. It requires a little bit nicer hardware than a typical NAS, but the data integrity is worth it. I'm old enough to have been burned by random disk corruption, flaky disk controllers, and bad cables.
Re:I'm addicted (Score:5, Funny)
I love ZFS too, but I'd fucking kill for and open ReiserFS...
Re:I'm addicted (Score:5, Funny)
I think that anything having to do with ReiserFS is a dead end.
Re:I'm addicted (Score:4, Funny)
OK stop already, you guys are driving this joke into the woods.
Re: (Score:3)
Re: (Score:2)
I love ZFS too, but I'd fucking kill for and open ReiserFS...
I heard that the act of using ReiserFS might be a criminal offense.
Something about making oneself an accomplice after the fact... I don't know; it's a bit murky
Re: (Score:3)
Re: (Score:3)
I guess nobody got the joke.
Re:I'm addicted (Score:4, Insightful)
Re: (Score:2)
FreeBSD. I'm sure that makes me more retarded. Or retardeder in your people's language.: Data integrity (Score:5, Interesting)
ECC RAM is an important part here, due to how scrubbing works in ZFS. The background disk scrubbing can check every block on the filesystem to see if it still matches its checksum, and it tries to repair issues found too. But if your memory is prone to flipping a bit, that can result in scrubbing actually destroying data that was perfectly fine until then. The worst case impact could even destroy the whole pool like that. It's a controversial issue; the odds of a massive pool failure and associated doom and gloom are seen as overblown by many people too. There's a quick summary of a community opinion survey at ZFS and ECC RAM [mikemccandless.com], but sadly the mailing list links are broken and only lead to Oracle's crap now.
Re: (Score:2)
What are the chances of the exact same sector being corrupt on at least three disks in a raidz2 vdev? This doesn't seem like a plausible scenario.
Re: Data integrity (Score:4, Informative)
That's what you have backups for.
Re: (Score:2)
That depends on the reason for the failure. If it's because there's a little bit of dust on the platter, or a manufacturing defect in the substrate, then it's very unlikely. If it's because of a bug in the controller or a poor design on the head manipulation arm, then it's very likely.
This is why the recommendation if you care about reliability more than performance is to use drives from different manufacturers in the array. It's also why it costs a lot more if you buy disks from NetApp than if you buy)
Re: (Score:2)
Re: (Score:3)
Re: (Score:2)
And, of course, very importantly, the ability to add drives to a RAID-Z array [superuser.com] after it has been created.
Re: (Score:2)
Why would ZFS need defrag support? UFS never had defrag support and the only times that ever became a problem was when the disk was running out of room. Which is bad for performance reasons anyways.
Re:all i want is BP-rewrite (Score:5, Informative)
Re: (Score:3)
So you propose that we kill array performance for a bit to de-fragment? Do you have any idea how long it takes to defragment multiple terabytes of data? On a multi-user multitasking OS access is more random anyhow, so its not like your contiguous files are likely to be read sequentially anyhow.
No, for a mission critical system that actually has a workload, its probably much easier/better to just maintain free space.
Re: (Score:3)
Ideally, in something like ZFS you'd want background defragmentation. When you a file that hadn't been modified for a while into ARC, you'd make a note. When it's about to be flushed unmodified, if there is some spare write capacity you'd write the entire file out contiguously and then update the block pointers to use the new version.
That said, defragmentation is intrinsically incompatible with deduplication, as it is not possible to have multiple files that all refer to some of same blocks all being con.
Still CDDL... (Score:5, Informative)
Oh well. I'd somehow hoped "truly open source" meant BSD license, or LGPL.
Re: (Score:3, Informative)
Re: (Score:3)
CDDL is basically LGPL on a per-file basis.
Perhaps the intent of the licenses is similar, but there's more to a license than that. Unfortunately, being licensed under the CDDL causes a lot more license incompatibility restrictions than either the LGPL or BSD license do. If it were under one of those, there'd be hope for seeing it as an included filesystem in the Linux kernel. But since it's under the CDDL, that can't happen.
The developers are, of course, welcome to use whatever license they like. Just pointing out that the CDDL is *not* basicall
Re: lic
Re: (Score:3)
In fairness its GPL that has the incompatibility problem not CDDL.
CDDL is compatible BSD, Apache2, LGPL, etc.
GPLv2 is incompatbile with CDDL, Apache2, GPLv3, LGPLv3, etc.
Even if the license were not CDDL, it would have to be released under a license that came with a patent clause, which means GPLv3, LGPLv3, Apache2 or similar all of which are incompatible with GPLv2 which Linux is licensed under.
CDDL isn't the problem.
Re: (Score:2)
Which would require a from-scratch cleanroom rewrite, probably.
They could probably work on that, but if the current license isn't causing to much trouble, they probably have more important things to work on.
Patents? (Score:4, Insightful)
Not to rain on anybody's parade,but will the commercial holders of ZFS allow this? Or will they unleash some unholy patent suit to keep it from happening?
Re: (Score:3)
Re:Patents? (Score:5, Informative)
If you're successful, Larry will come a callin' (Score:3, Funny)
As long as Oracle's patents are valid, can anyone seriously believe this will go anywhere?
His fleet of boats isn't going to pay for itself.
Re: (Score:3)
You mean that fleet of losing boats? Last time I checked it was 7-1 NZ with first to 9 winning.
Re: (Score:2)
Re:If you're successful, Larry will come a callin' (Score:5, Informative)
Re: (Score:2)
Oracle released ZFS under a BSD compatible license. Anyone is allowed to do whatever to the opensource code.
GP was talking about patents. If they had released it under (L)GPLv3 or Apache2, users would be safe from patents suits.
Re: (Score:3)
Re:If you're successful, Larry will come a callin' (Score:5, Funny)
Collecting money from opensource-companys? Daryl McBride will turn in his grave if Larry is even stupid enough to try it...
Eh? I don't think that the Mormons bury their living, no matter how ghoulish are the corporations that they helm.
I'm afraid Daryl McBride will be quite operational when your friends' commits arrive...
Re: (Score:2)
Eh? You mean Darl McBride and not Daryl McBride? I usually do not nitpick on small stuff like this but this pig vomit should be remembered by his correct name. We don't want to assign blame for what he did to some other innocent person.
Advatages of ZFS over BTRFS? (Score:3, Insightful)
Re: (Score:2)
btrfs is still considered experimental by the devs zfs is used in production.
Past that btrfs does not seem to support any sort of ssd caching wich is realy a requirement for any modern fs.
Re: (Score:2): (Score:2)
Re: Advatages of ZFS over BTRFS? (Score:2)
It is called ZIL - zero insertion log IIRC
Re: (Score:2)
Re: (Score:2)
There are two uses for SSDs in a ZFS pool. The first is L2ARC. The ARC (adaptive replacement cache) is a combination of LRU / LFU cache that keeps blocks in memory (and also does some prefetching). With L2ARC, you have a second layer of cache in an SSD. This speeds up reads a lot. Data that is either recently or frequently used will end up in the L2ARC and so these reads will be satisfied from the flash without touching the disk. The bigger the L2ARC, the better, although practically if it's close to: (Score:2)
The one negative to ZFS (if you can call it that) is that it makes you aware of inevitable failures (scrubs catch them). I'll lose about 1 or 2 files per year (out of many many terrabytes) just due to lousy luck
What? Interesting.... I never lost a file on ZFS... ever; and I was doing 12TB arrays, for VMDK storage; these were generally RAIDZ2 with 5 SATA disks, running ~50 VMs. Then in ~2011, concatenated mirrored sets of drives; large number of Ultra320 SCSI spindles in a direct attach SCSI
Re: (Score:2)
Re: (Score:2)
It sounds like he disabled/reduced ZFS's default to keep extra copies of meta-data.
That would seem to require altering the source code. At least in the Solaris X86 ZFS implementation; there is no zpool or zfs dataset option to turn off metadata redundancy.... of course it would be a bad idea.
Re: (Score:2)
I corrupted some files by the following:
This is a home setup, all parts are generic cheapo desktop grade components, except slightly upgraded rocket raid cards in dumb mode for additional sata ports:
4 HDDs, 2 vdevs that 2 drive mirrors (RAID 1+0 with 4 drives essentially)
1 drive in a 2 drive mirror fails, no hot spare.
When inserting a replacement drive for the failed drive, the SATA cable to the remaining drive in the mirror was jiggled and the controller considered it disconnected.
The pool instantly went
Re: (Score:3)
You can't expect much better than what it did considering an entire vddv (both drives in the mirror) went off line as data was being written to them.
I do expect better, because ZFS is supposed to handle this situation, where a volume goes down with in-flight operations; the filesystem by design is supposed to be able to re-Import the pool after system restart and recover cleanly....
That shouldn't of happened; it sounds like either the hard drive acknowledged a cache FLUSH, before data had been w
Re: (Score:2)
Doesn't look like he had a ZIL from the description of the hardware. So it's totally understandable that he might have corruption.
Re: (Score:3)
I had an upgrade path similar to yours, starting with RAIDZ and moving the a group of mirrors. I try not to let any pool get too big, so there are maybe 20 drives/pool. It's always the small files that are lost (see post above) I think each server does about 6 PB/year each direction on these highly-accessed files, so I think it's reasonable to drop ~1MB of non-critical files (they basically store notes of data analysis).
So far I've never had a problem with VM images, but now we're mitigating that by addin
Re: (Score:2)
Apparently "never lost data" must mean never lost an entire filesystem -- that's not my definition. Usually file loss is user error.
ZFS does support snapshots, and Nexenta / FreeNAS / etc have snapshot options, and replication options (zfs send | zfs recv) available, for sure.
It's a highly resilient filesystem, but owning and using a highly resilient filesystem is not a replacement for having the proper backups.
Re: :Advatages of ZFS over BTRFS? (Score:5, Interesting)
This is correct.
It is statistically assured that you will lose some data with anything less than obscene redundancy. I've run the numbers and we've settled on what's acceptable to us: we have offline backups far more frequently than 2 times/year for everything, so dropping about 2 files/year that are completely unrecoverable without backups isn't a big deal.
These systems are running a moderate number of very large static files, mixed with a very large number of very small files. The small files are SQLite-style records, and we churn through them very rapidly. I don't know exactly why, but it is always these small files that we lose: there is clearly a bias towards things that are written frequently. The analyst in me is quick to point out that implies failures in ZFS itself, beyond just the disks and "bit rot", but the accelerated failure isn't enough to worry about. So our non-failure rate is easily 6-nines or better per year on the live storage system, but it's still a bit uncomfortable to know that some data is going to be gone, despite that.
With a minimal amount of effort you can get hardware and software which is not longer the biggest threat to your data. I am personally the most likely source of a catastrophic failure: operator error is more likely than an obscure hardware failure. ZFS has allowed me to reduce that operator error (snapshots, piping filesystems, nested datasets with inheritance), and simultaneously it's outperforming other options on both speeds and security. Overall, I'm extremely pleased.
Re: (Score:2)
It means the files were lost from the filesystem, and he was notified and recovered them from the backups. Which is a hell of a lot more than what other filesystems would do for you. One of the benefits of ZFS is that it makes it a lot easier to monitor for bit rot.
Re: (Score:3)
Re: (Score:3)
I'm sure I'll be corrected if I'm wrong, but does it offer any advantage over BTRFS? I'm not trying to start a flame war; I'm honestly asking.
BTRFS is still highly experimental. I had production ZFS systems back in 2008. A mature ZFS implementation is a lot less likely to lose your data with filesystem code at fault (assuming you choose appropriate hardware and appropriate RAIDZ levels with redundancy).
Re: (Score:2)
Re:Advatages of ZFS over BTRFS? (Score:5, Insightful)
Nice FUD there. You picked the btrfs-progs, which are the userspace tools, not the actual btrfs filesystem driver. [kernel.org]
Re: (Score:3)
BTRFS has a large number of features that are still in the "being implemented", or "planning" stages. In contrast, those features are already present, well tested, and in production for half a decade on ZFS. Many touted "future" features (such as encryption) of BTRFS are documented as "maybe in the future, if the planets are right, we'll implement this. But not anytime soon"
Comparing the two is like making up an imaginary timeline where ReiserFS 3 was 4-5 years old and in wide deployment while ext2 was bein
Re: (Score:2)
ZFS is tested and has beed used in huge amount of different environments with very posive feedback for well over a decade. I do not know any catastrophic failures (though there must be).
BTRFS requires latest version of Linux kernel and itself to work. I have no clue about testing (removing disks on the fly, etc.) and definitely it is not widely deployed, not yet proven to work (few anecdotes do not count).
BTRFS seems to be only slightly more robust than it was five years ago - during this time I have lost t
Re: (Score:3)
I'm playing around with btrfs at the moment, and I've spotted some inconsistencies in the document you mentioned.
* Subvolumes can be moved and renamed under btrfs. I do this on a daily basis.
* btrfs can do read-only snapshots. Mind you, it does have to be specified.
* As far as I can tell, "df" does work fine with btrfs. The document implies it does not.
I am still quite new to btrfs, so I'm learning much at the moment. There may be more points that I've missed.
It seems, though, your document is a bit out
Re: (Score:3)
Gotcha. So btrfs and df play up only under a raid1 situation. That explains why I didn't notice any problem.
As for snapshots, I've set up an automated snapshot system using btrfs. Main volume is mounted to
/snapshots. One subvolume is created in there, and is then separately mounted to /data . Snapshots are created under the /snapshot directory, while /data is the path used by applications. I've created a nightly script which renames all previous snapshots, and then creates a new snapshot. It all wor
Re: (Score:3)
That's never been true, you always had the option of detaching it or outright deleting just one disk, you just had to make sure you did it in a careful manner so as not to delete things you didn't want to delete.
Also resizing a volume on a disk is a risky operation to engage in. If it's something that you really need to do, the correct way is to back up the data to a separate disk and restore it to a new volume. Resizing volumes is not exactly in keeping with the philosophy that led to ZFS being created.
Re: (Score:2)
Re: (Score:2)
Once a zfs filesystem is created that's it. No resize support
Minor correction: Once a ZFS pool is created, that's it. Filesystems are dynamically sized. You can also add disks to a pool, but not to a RAID set. You can also replace disks in a RAID set with larger ones and have the pool grow to fill them. You can't, however, replace them with smaller ones.
Re: (Score:3)
Limited number of drive slots + moving to a smaller, but faster platter in one or more of those slots.
Re: (Score:2)
Still no encryption... *sigh* (Score:3)
I wish they had encryption... *sigh*
No, I don't want workarounds, I want it to be built in to ZFS like in Solaris 11.
Re: (Score:2)
There are no satisfactory workarounds, and never will be. The crypto needs to be handled within ZFS or it becomes an over complicated and inefficient mess. (As you are probably aware.) Consider a ZFS mirror on top of two disks encrypted by the OS; even though the data is identical, it now needs to be encrypted twice on write, and decrypted twice on scrub. For ditto blocks, multiply the amount of crypto work by another two or three. There are now (at least) two keys to manage and still no fine granularity
How does ZFS compare to btrfs? (Score:2)
How does ZFS compare to btrfs? Several intentionally unnamed and unlinked commentaries on ZFS apparent current omission from Mac OSX refer to btrfs to be the more GPL-compliant alternative to ZFS. I need more information, as I do not think btrfs has the same aggressive checksumming and automatic volume size feature that ZFS does.
Thanks.
Re: (Score:2): (Score:2)
Re: e
Re: (Score:3, Funny)
You don't have a multi-petabyte array with mission criitical data at home?
Re: (Score:2)
Re: (Score:3). There are applications that run well on Windows, especially on the Server side of things so I wouldn't call it dead quite yet. Besides, with Server 2012 we now have Storage Spac.
Re: (Score:2) th
Re: (Score:3).
Not according to this document; the runtime components are not redistributable. This is an Anti-WINE license measure: [microsoft.com] the filesystem driver all rolled into one
... but spread all across the kernel, in order to get proper performance.
Could get pretty close with some good hacks though, such as FUSE.
This is actually reverse-engineerable. FUSE isn't an option, since pages which get memory mapped and dirtied are not propagated up via invalidation events. This is the same problem the Heidemann stacking framework has if you stack FS A on top of FS B, and then expose both of them as visible in the mount hierarchy namespace. Yo
Re: (Score:3)
(You seem to write well so you'll probably appreciate being reminded it's "garner" not "garnish")
Re: (Score:2)
WTF are you smoking. POSIX compatibility is easy to achieve, and you can get it on Windows by installing the optional SFU package. Too bad POSIX says nothing about file system driver interfaces - that's entirely kernel-dependent, and even varies between BSDs.
Re:Cool, but.. (Score:5, Insightful)
Everything else is already handled with LVM and software RAID.
You have a great sense of humor, keep it up.
Re:Cool, but.. (Score:4, Informative)
Re: (Score:2)
Re: (Score:2)
Re: (Score:2)
Selective encryption means that you have to be incredibly careful that sensitive data never hits a non-encrypted portion of the disk. So, I'd say that the full disk encryption is the cleaner option.
Re: (Score:2)
Full disk encryption isn't a fad; it's the only way to this job well. Selective encryption makes people relax because it gives a false sense of security, but there are so many holes that you're still quite vulnerable. In some ways it's worst than no encryption at all, because people at least know they have to be careful about their system then.
The first giant issue is that operating systems and programs like editors will write work in progress data to disk outside of the encrypted area, such as temporary
Re: (Score:3)
Temporary files and swap aren't a problem...
Swap can and should be stored on a separate partition, and encrypted using a randomly generated key so its completely lost after a reboot.
On a properly configured system, only a very small number of locations will be writable by the user, typically the user's home directory and a temporary area... The temporary area can be stored in ram/swap since it doesn't matter if its contents are lost and home can be encrypted.
It's trivial to add a hardware key logger to virt
Re: (Score:2)
If someone has physical access to a system for long enough, of course any security can be bypassed and the system must be considered tampered. But a fully encrypted system cannot be compromised in only a minute or two of access; one with an unencrypted boot drive certainly can be. And time to exploit impacts how vulnerable you are in very common real world situations.
A regular full disk encryption candidate is a laptop you leave home with. I will sometimes leave my laptop sitting at a table with someone | https://hardware.slashdot.org/story/13/09/17/233207/openzfs-project-launches-uniting-zfs-developers?sdsrc=prevbtmprev | CC-MAIN-2016-50 | en | refinedweb |
Using Custom Behaviors with the BizTalk WCF Adapters, Part 1
Microsoft Corporation
January 2009
Customization of message processing in Microsoft® BizTalk® Server 2006 R2 can be extended through the use of Windows Communication Foundation (WCF) custom behaviors. This article is the first of two parts discussing how the use of WCF custom behaviors within BizTalk Server gives increased control over the message transmission process.
You can download this article from.
You can download part 2 of this article from.
One of the advantages of using Windows Communication Foundation (WCF) as a message communication mechanism is the opportunity to extend the functionality of its services by using custom code. There are different points within the flow of a WCF message to intercept the message and execute custom processing before the message reaches its final destination. WCF custom behavior extensions are one such type of interception mechanism, and can be used to extend WCF service or client functionality at different levels of granularity. In this paper we will discuss the different types of WCF behaviors and where you can interject their processing within the WCF architecture. We will discuss how the BizTalk WCF-Custom and WCF-CustomIsolated adapters enable you to use a WCF custom behavior extension.
The ability to easily implement custom processing in a call to a WCF service is one of the main reasons why WCF is such a rich programming paradigm compared to other ways of communication between Web applications. This custom processing can take almost any form as dictated by extensibility requirements within a Web application. For instance, behaviors can supplement normal message processing, modify the message during processing, scrutinize certain configuration criteria and take appropriate action, validate identities of the caller and pass the message on if it is successful, and so on. It is truly a custom processing mechanism, so you can implement whatever extensibility you feel your application needs.
Behavior extensions are one of the components that differentiate WCF from other Web services technologies in the market. By using this feature, developers can add custom extensions that inspect and validate service configuration or modify run-time behavior in WCF client and service applications. Custom behavior extensions can exist at both the WCF service and client levels. Configuring a behavior on the call stack to a WCF service has no influence on the communication binding used to make the call. In fact, behaviors are typically invisible to the client because they are not displayed in the metadata that a service publishes. The client typically has no idea that the extensions are running during a call to a WCF operation.
Upon initial inspection, a WCF custom behavior is very much like a traditional BizTalk pipeline. Both leverage the basic concept of message interception to interrupt the flow of a message to its destination, execute some custom message processing on the message, and forward it on to its destination. This interception can occur both before (bound to a receive location) or after (bound to a send port) a message has been processed by BizTalk Server. How this interception occurs within pipelines and custom behaviors differs not only in implementation but also from within the point of interception. Here are just a few of the differences:
- Pipelines can be used by an orchestration. WCF behaviors can be called only by the adapter.
- Pipelines are an older technology limited to BizTalk Server. WCF behaviors can be used by BizTalk Server, and can also be used in other pure WCF scenarios.
- Pipelines live within set pipeline stages, such as Decode and Validate. WCF behaviors can be plugged into the message flow at any of its four interception entry points (described in the following section).
- Pipelines are purely runtime in their functionality. While WCF behaviors are also runtime, they can also enforce relational or data constraints upon the values set during configuration from within the BizTalk Server Administration console.
- Pipelines can operate on a BizTalk message context. WCF behaviors operate on a WCF context.
There are four levels within the WCF service architecture at which you can apply a custom behavior. At each level, the methods in which you define the interception behavior are different depending upon their ordering in the service functionality hierarchy. These levels of interception are Service, Endpoint, Contract, and Operation. The highest level of interception is that of the service itself, where the capabilities of the entire service can be extended. Unlike the other three types of behaviors, a Service-level custom behavior applies only to WCF service applications and not to WCF client applications. Custom behaviors at the Service level apply to all of the endpoints exposed by the service. However, because a service can expose multiple endpoints, you may want to extend only some of them and not others. This gives us the next level of interception at the individual Endpoint level. This allows interception for certain endpoints within the service and not for others. Endpoints expose contracts, and custom behaviors can also be applied at the individual Contract level. A WCF contract is a group of related one- or two-way message exchange operations. If you require access to the lowest level of a WCF call, you can use custom behaviors at the Operation level.
Within BizTalk Server, the only two WCF adapters that allow you to configure and use custom WCF bindings are the WCF-Custom and WCF-CustomIsolated adapters. These two adapters differ primarily in their hosting locations. WCF-Custom is hosted within the BizTalk Server process, while WCF-CustomIsolated runs within the Internet Information Services (IIS) process. Both of these adapters provide a user interface (UI) to allow you to select either an Endpoint behavior or a Service behavior. There is not BizTalk Server UI support to configure custom WCF behaviors written to run at either the Contract or Operation level.
One of the featured deliverables for the R2 release of BizTalk Server is the set of WCF adapters. These adapters allow BizTalk Server to call existing WCF applications from an orchestration, or to expose an orchestration as a WCF service to be called by a client. Orchestrations are not required for WCF adapters to interact with WCF because you can use pure WCF messaging with a receive location and a send port. However, with the BizTalk WCF Service Publishing Wizard you typically will expose an orchestration with a WCF adapter.
By configuring a WCF adapter to use a WCF custom behavior, the behavior functionality will be invoked when the call comes into the BizTalk adapter. If the behavior’s processing of the message does not result in a positive response, the message is not allowed to be posted to a receive location. The message thus gets rejected at the transport level and is not preserved. For instance, you could check the identity of the caller posting the message to the BizTalk receive location against a list of allowed groups. The administrator can configure the group names in the property pages of the WCF behavior tab. The behavior custom code can read those groups and check access against the groups with which the identity is associated. The identity of the logged-in user is sent as part of the WCF call in the SOAP headers. That identity can be authenticated at either the transport layer or the message layer depending on the configuration. If that identity is in one of the allowed groups, the call is allowed to pass through to the receive location.
WCF custom behaviors are connected to BizTalk Server though the WCF Adapters configuration options in the BizTalk Server Administration console.
To allow the custom behavior to be visible to the WCF adapter’s configuration, you must add an entry similar to the following in the <extensions> section of the machine.config file:
<system.serviceModel> <extensions> <behaviorExtensions> <add name="BizTalkAuth" type="Microsoft.Samples.BizTalk.Adapters.WCFAuthorization.BizTalkWCFAuthElement, WCFAuthorization, Version=1.0.0.0, Culture=neutral, PublicKeyToken=85b32fccee4970f5"/> </behaviorExtensions> <extensions> <system.serviceModel
The name BizTalkAuth is given in the preceding section and will be used to subsequently identify the service extension inside the WCF adapter’s property pages. The type is a combination of the namespace of the behavior assembly (Microsoft.Samples.BizTalk.Adapters.Authorization), and the class (BiztalkWCFAuthElement) that derives from BehaviorExtensionElement. This is a class that represents a configuration element and its subelements that define behavior extensions to allow service behaviors to be customized. WCFAuthorization is the name of the assembly along with its public key token, as they exist in the GAC.
We have discussed what a WCF custom behavior is and how it can be used under BizTalk Server. A WCF behavior can intercept the message flow at different levels. There are similarities and differences between a WCF behavior and a BizTalk pipeline, and we compared the two technologies. We looked at how BizTalk Server uses a WCF custom behavior by the WCF adapters. WCF behaviors are an extensibility option for BizTalk applications to do custom processing of a WCF message before it gets to the actual adapter. Whatever custom authorization scheme works for your application, you can model it through a custom behavior. In the next part of this article, we will show you how to write a custom behavior and configure it to work under BizTalk Server. This behavior uses a custom authorization scheme to decide if the incoming WCF message should be passed to the adapter, and then to BizTalk Server, for processing, or rejected before it even gets to the adapter. | https://msdn.microsoft.com/en-us/library/cc952299.aspx | CC-MAIN-2016-50 | en | refinedweb |
As a UX developer at Safari Books Online, I need to be familiar with all aspects of our front-end architecture. A big part of that is Backbone.js. My JavaScript experience is jQuery plugins and scripts so I’ve needed to play catchup on this Backbone thing. I learn best by pulling up my sleeves and diving into a project. I decided I’d like to work with some kind of API and ended up choosing the Google Books API.
The end result is backbone_books. You can jump to the demo here. Or check out the code on Github here.
The Backbone components include;
- A book model for storing book data returned in JSON format from the Google Books api
- A book collection for storing a collection of book models
- A “my library” collection hooked up to the backbone.localstorage adapter for storing a collection of book models in localstorage
- A router for mapping URL’s (the category links) to a search view for querying the Google Books api
- 4 views for displaying the data; an ‘all books view’, a book view, details view and a search view.
Organization
It’s organized with require.js. Each Backbone component is a self-contained ‘module’ that includes only the other components they require. This way you avoid the traditional tangle of ‘script’ tags that load every js file on every page. The file structure for the project looks like this:
index.html
css
img
js
app
collections
models
routers
templates
utils
views
_init.js
libs
backbone
backbone.localstorage
require.min
require.text
app.js
There is just one javascript include in index.html:
This lets require load js/app.js as the primary entry point. App.js sets the root directory for my modules and maps third party libraries to ‘namespaced’ module IDs. These get loaded asynchronously in the order of their dependencies.
In my app/ folder I’ve got all the main Backbone components organized nicely into their own folders.
At the bottom of app.js, it loads _init.js inside the app folder.
_init initializes the router and starts the Backbone history for bookmarkable url’s.
The router maps hash urls with query parameters (‘:query’) to functions that start new searches. The “query” parameters can be named anything. If some of the searches look mostly the same it’s because they are. The Google API docs ask for example that you search for authors by prepending “:inauthor” to the search term. Other parameters I need to pass include the maximum books I want to show per query, the search term (obviously), and the index. For example new searches begin at a ‘0’ index – if I want to search again for more books and I’m showing ten books, the index should start at ’11’. This is tracked in the search view.
The index page kicks it off by mapping the page with no hash urls to a new search. The search view initializes some topics and listens to form submissions on the search form. This kicks off a search on its value and does an ajax query on the Google Books API.
The ajax response data gets added into a new model then into a collection.
Once I have a book collection with a bunch of models, I need to display them. So I instantiate the “AllBooksView” and pass it the collection.
I pass each book model to its own view for rendering (BookView). This is because I want to bind it to a click event that passes it’s specific model data to the details view. This way the details view can grab its volume ID from the model which I need to query the Google Books API for its full detail data.
The book view (which created the book thumbnails) listens to clicks and passes its model to a details view.
Views can be assigned an ‘el’ which attaches the view to that html in the DOM (similar to document.getElementById(‘#search_form’)). Otherwise, views can be assigned a ‘tagName’ – in which case it creates the HTML and prepends itself to it. In the BookView’s case, it’s created inside an “li” html list. If you look in the AllBooksView, the tagName is “ul”, so new books are appended to the “ul” created by the AllBooksViews.
BookView instantiates the DetailView on the #book-details html element already in the dom and calls it’s render method.
The details view checks if the model is in localstorage by looping through the localstorage keys and looking for its volume id (namespaced to ‘myBooks’).
If the book exists in local storage, fetch it from there and display it — otherwise do an API query.
Once the book details are displayed, you can either remove it from localstorage or save it to localstorage.
It’s not the prettiest code. I’ve intentionally included only snippets and linked to the full modules so as to illustrate the overall process rather then get you bogged down in the details. Some of that extra code is silly show/hide animations. Other stuff is for defining JSON objects to prevent errors or silly things like checking the window.location.hash for a router URL. Debugging I check console.log() a lot and these things arise out of that.
Backbone is great fun. I got a lot of good information from Addy Osmani’s book. If you’re new to Backbone and want to learn it I recommend reading up on it and then start something from scratch, check the console.log(), check the backbone docs, underscore.js has some really useful methods (and is required by backbone) — go slow and things should start to make sense. | https://www.safaribooksonline.com/blog/2013/11/16/getting-familiar-with-backbone-js/ | CC-MAIN-2016-50 | en | refinedweb |
0
hi every 1 i am new and Ihope that you would help me I have to write a program that will allow you to enter if you enter the password without using strcmp function and here is my try
#include <iostream> #include <cstdio> using namespace std; bool password(); int main() { if( password()) cout<< "logged on"<<"\n"; else cout<< "access deniled"<<"\n"; return 0; } bool password() { char s[80]={"pass"}; cout<< "enter password"<<"\n"; gets(s); if( s=="pass") { cout<<"invalid password"<<"\n"; return false; } return true; }
Code tags added. -Narue
plz answer me as herry as u can
thanx | https://www.daniweb.com/programming/software-development/threads/21332/plzzzzzzzzzzzzz-help-me | CC-MAIN-2016-50 | en | refinedweb |
Hello.
im a student working in C++ and im fairly new to both C++ and i guess this community.(i was reccomended to come here if i had problems) im just doing some simple exercises or s it seemed. here is the question.
Write a C++ program with a case structure. The program reads in a character from the user, then translates it into a different character according to the following rules:
i. characters X, Y, Z will be translated to characters x, y, z respectively ii. the space character ' ' will be translated to underscore '_' iii. digits 0, 1, 2, .., 9 will all be translated to the question mark '?'
iv. all other characters remain unchanged.
The program then displays the translated character.
simple? well i guess, i was able to do most of it but im stuck on Q2 and Q4. i cant find a way to enter spacebar through the case(ive tested other characters to give out the underscore and i have tried some 'getline' stuff) and i am lost upon the last bit. I'm sure it ustilises the 'default' part of the code. bleh maybe i explained incorrectly.
btw im not a slacker asking for easy answers heres what ive done
#include<iostream> using namespace std; int main(){ string type2; char type; char c; cout<<"please enter one of the valid characters "; cin>>type; switch(type) {case 'X': type2="x"; break; case 'Y': type2="y"; break; case 'Z': type2="z"; break; case '0': case '1': case '2': case '3': case '4': case'5': case'6': case'7': case'8': case '9': type2="?"; break; default : type2= ; } cout<<type2<<endl; system("pause"); return 0; }
anyways anyhelp is much appreciated. telling me what im supposed to do or simply pointing me in correct direction would be great.(my textbooks fail at this) and yes i have watched through several 'youtube' style tuts and googled lots but to no sucess.
thnx, Leone, novice c++ student.
Edited 3 Years Ago by Nick Evan: Fixed formatting | https://www.daniweb.com/programming/software-development/threads/308895/39-simple-39-coding-problems-using-case-switch-under-certain-inputs-assistance-please | CC-MAIN-2016-50 | en | refinedweb |
JSORB - Javascript Object Request Broker
use JSORB; use JSORB::Server::Simple; use JSORB::Dispatcher::Path; use JSORB::Reflector::Package; use JSORB::Client::Compiler::Javascript; # create some code to expose over RPC { package Math::Simple; use Moose; sub add { $_[0] + $_[1] } } # Set up a simple JSORB server JSORB::Server::Simple->new( port => 8080, dispatcher => JSORB::Dispatcher::Path->new( namespace => JSORB::Reflector::Package->new( # tell JSORB to introspect the package introspector => Math::Simple->meta, # add some type information # about the procedure procedure_list => [ { name => 'add', spec => [ ('Int', 'Int') => 'Int' ] } ] )->namespace ) )->run; ## Now you can ... ## go to the URL directly¶ms=[2,2] # and get back a response { "jsonrpc" : "2.0", "result" : 2 } ## compile your own Javascript client ## library for use in a web page ... my $c = JSORB::Client::Compiler::Javascript->new; $c->compile( namespace => $namespace, to => [ 'webroot', 'js', 'MathSimple.js' ] ); # and in your JS var math = new Math.Simple ( '' ); math.add( 2, 2, function (result) { alert(result) } ); ## or use the more low level ## JSORB client library directly var c = new JSORB.Client ({ base_url : '', }) c.call({ method : '/math/simple/add', params : [ 2, 2 ] }, function (result) { alert(result) });
__ __ /\ \ /\_\ ____ ___ _ __ \ \ \____ \/\ \ /',__\ / __`\ /\`'__\ \ \ '__`\ \ \ \ /\__, `\/\ \L\ \\ \ \/ \ \ \L\ \ _\ \ \ \/\____/\ \____/ \ \_\ \ \_,__/ /\ \_\ \ \/___/ \/___/ \/_/ \/___/ \ \____/ \/___/
This is a VERY VERY early release of this module, and while it is quite functional, this module should in no way be seen as complete. You are more then welcome to experiment and play around with this module, but don't come crying to me if it accidently deletes your MP3 collection, kills the neighbors dog and causes the large hadron collider to create a black hole that swallows up all of existence tearing you molecule from molecule along the event horizon for all eternity.
The goal of this module is to provide a cleaner and more formalized way to do AJAX programming using JSON-RPC in the flavor of Object Request Brokers.
Currently this is more focused on RPC calls between Perl on the server side and Javascript on the client side. Eventually we will have a Perl client and possibly some servers written in other languages as well.
The documentation is very sparse and I apologize for that, but the test suite has a lot of good stuff to read and there is a couple neat things in the example directory. If you want to know more about the Javascript end there are tests for that as well. As this module matures more the docs will improve, but as mentioned above, it is still pretty new and we have big plans for its. | http://search.cpan.org/dist/JSORB/lib/JSORB.pm | CC-MAIN-2016-50 | en | refinedweb |
Documentation
First steps
First, install the DUB package manager to let it handle downloading and building of vibe.d and derived applications. On non-Windows systems, a number of additional dependencies needs to be installed. See the project description on GitHub for details.
Manual building (e.g. using RDMD) is a possible alternative, but you have to make sure that external libraries are linked in (such as libevent) and that a version identifier for the used driver is passed to the compiler (e.g.
-version=VibeLibeventDriver). Take a look at vibe.d's dub.json to determine how to build on a certain platform, or, alterntaively, run DUB with the
-v switch to see the actual compiler command line.
The easiest way to get started is to. As the next step, you can go ahead and edit the
source/app.d file. If you want to publish your project, you should also edit the
dub.json/
dub.sdl file and properly fill in all fields, including a "license" field..
Recommended project structure
The recommended directory structure for a project, which the "dub init" command establishes, is separated into three base folders:
appname/ source/ app.d public/ images/ styles/ style.css views/ layout.dt index.dt dub.json
For a simple web application, the 'app.d' file could look similar to this one:
import vibe.d; void index(HTTPServerRequest req, HTTPServerResponse res) { res.render!("index.dt", req); } shared static this() { auto router = new URLRouter; router.get("/", &index); auto settings = new HTTPServerSettings; settings.port = 8080; listenHTTP(settings, router); }
The 'views' sub folder is automatically searched for templates instantiated with
render. The two templates in the example structure might look like this:
doctype html html head title Example page body block body
extends layout block body h1 Example page - Home p Hello, World!
This structure makes use of the blocks/extensions feature of the Diet template compiler. For more advanced template features see the Diet template documentation.
Finally, the "dub.json" lets the vibe.d package manager automatically download and compile dependency libraries. This file will also provide the description that is needed to later put your own library into the public extension registry.
{ "name": "appname", "description": "My fabulous new app", "copyright": "Copyright (C) 2000 Me. All rights reserved.", "license": "AGPL-3.0", "homepage": "", "authors": ["Hans Wurst"], "dependencies": { "vibe-d": "~>0.7.23" }, "versions": ["VibeDefaultMain"] }
DUB also provides support for a new alternative syntax using SDLang, which supports comments and is considerably more compact. The filename to use is "dub.sdl" in this case:
name "appname" description "My fabulous new app" copyright "Copyright (C) 2000 Me. All rights reserved." license "AGPL-3.0" homepage "" authors "Hans Wurst" dependency "vibe-d" version="~>0.7.23" versions "VibeDefaultMain"
Example projects
A library of example projects is maintained in the Git repository. Most things not covered in this document can be found there in the form of code:Example projects
To run the examples locally, you can either download the repository as a zip file, or use GIT to get the examples:
git clone
To run the "http_server" example, type:
dub run --root=vibe.d/examples/http_server
HTTP
Server configuration
The HTTP server supports a number of configuration options to customize its behavior. By default, the server will listen on all local network adapters on port 80 and will perform complete request parsing. The following list gives an overview of the most common settings:
port
- The port on which the HTTP server shall listen
bindAddresses
- A list of all interfaces on which the server shall listen. IPv4 and IPv6 addresses, as well as domain names are supported.
options
- Controls optional features of the web server. Certain options can be disabled to increase speed or to decrease memory usage. By default, the following options are enabled: parseURL, parseQueryString, parseFormBody, parseJsonBody, parseMultiPartBody, parseCookies. Enabled options are ORed together.
errorPageHandler
- Provides a way to customize error pages. For example:
void errorPage(HTTPServerRequest req, HTTPServerResponse res, HTTPServerErrorInfo error) { res.render!("error.dt", req, error); } shared static this() { auto settings = new HTTPServerSettings; settings.errorPageHandler = toDelegate(&errorPage); // ... }Inside of the error.dt template, the variables req, code and msg are available in this example.
sslContext
- Lets the server operate as an HTTPS server. You should probably also set the port to 443 in case this field is set.
Routing
The
URLRouter
class provides a convenient way to let different functions handle different URLs. It supports static path matching, variable placeholders and wild-cards. Any matched variable will be available as an entry in the
params dictionary.
In addition to the path, the HTTP method is also used for matching requests. Each HTTP method has a corresponding method in the
URLRouter
class (e.g.
get or
post). The following example will route all GET requests matching the path scheme
"/users/*" to the
userInfo handler and serve all other GET requests using the files in the public folder, see
serveStaticFiles./")); // To reduce code redundancy, you can also // use method chaining: router .get("/users/:user", &userInfo) .post("/adduser", &addUser) .get("*", serveStaticFiles("./public/")); listenHTTP(new HTTPServerSettings, router); }
Diet templates
Vibe.d supports HTML templates with a syntax mostly compatible tojade templates. They provide a concise way to dynamically generate the HTML code of the final web pages. D expressions and statements can be embedded and the full vibe.d API is available within templates.
Templates should reside somewhere inside the 'views' folder of a project. They are then rendered using the
render
function, which takes the template file name as the first template argument, followed by a list of variables that should be available to the template. Finally, it takes a
HTTPServerResponse
to render into.
The following example shows a number of features of the Diet template compiler. A full reference of the template syntax is found on theDiet templates page.
doctype html html head title My page: #{pageTitle} body h1= pageTitle p This is the content of this page. The | title "#{pageTitle}" is inserted dynamically. | We can also use loops and other D statements: block placeholder p - foreach(i, ch; pageTitle) | #{i+1}. character: #{ch} p.special.small This paragraph has the 'special' | and 'small' CSS classes p#footer This paragraph has the id 'footer'. #somediv. I'm a multiline text inside the div #somediv
Error pages
There are three ways in which an error page is sent back to the client:
- An exception is thrown from the request handler or while parsing the request. By default, a 500 "Internal Server Error" is returned. By throwing a
HTTPStatusException, the status code can be customized.
- The request handler does not write a response. In this case the server automatically returns a 404 "Not Found" error.
- The request handler manually sets an error status to HTTPServerResponse.statusCode and writes a body. In this case, the error page will be written exactly as specified.
The
HTTPServerSettings
can be used to provide a custom error page handler. If one is provided, it is called for any of the first two conditions and must render an error page to the response object. If no handler is given, a simple plain-text error page is generated. See the HTTP server configuration section for an example.
Authentication
Currently, HTTP-Basic-Auth and HTTP-Digest-Auth authentication methods are implemented. Higher level mechanisms such as OAuth will be provided using extension libraries.
A simple way to plug authentication into a web application is to use the fall-through feature of the
URLRouter. If the user is properly authenticated, the
performBasicAuth
function will not do anything and the URLRouter will continue to match the request to all following routes. If, however, there is no authentication or if the username/password pair is not valid, it will throw a
HTTPStatusException
exception which generates a 403 error page so that the user is prompted with a password dialog on the browser side. The routing stops in this case.
Note that it is generally recommended to make use of the high level web framework when developing web application front ends. See the "web" example project for a way to implement session based authentication in such a setting.
import vibe.d; bool checkPassword(string user, string password) { return user == "admin" && password == "secret"; } shared static this() { auto router = new URLRouter; // the following two routes are accessible without authentication: router.get("/", staticTemplate!"index.dt"); router.get("/about", staticTemplate!"about.dt"); // now any request is matched and checked for authentication: router.any("*", performBasicAuth("Site Realm", toDelegate(&checkPassword))); // the following routes can only be reached if authenticated: router.get("/profile", staticTemplate!"profile.dt"); router.get("/internal", staticTemplate!"internal.dt"); // ... }
Sessions
Cookie based HTTP sessions are supported directly by the HTTP server. To be able to use them, you first have to set a
SessionStore
in the
HTTPServerSettings
. Sessions are then established by calling
HTTPServerResponse.startSession
and stopped using
HTTPServerResponse.terminateSession
. The returned
Session
object behaves as a key value store taking strings as keys and values.
import vibe.d; void login(HTTPServerRequest req, HTTPServerResponse res) { enforceHTTP("username" in req.form && "password" in req.form, HTTPStatus.badRequest, "Missing username/password field."); // todo: verify user/password here auto session = res.startSession(); session.set("username", req.form["username"]); session.set("password", req.form["password"]); res.redirect("/home"); } void logout(HTTPServerRequest req, HTTPServerResponse res) { if (res.session) res.terminateSession(); res.redirect("/"); } void checkLogin(HTTPServerRequest req, HTTPServerResponse res) { // force a redirect to / for unauthenticated users if (!req.session) res.redirect("/"); } shared static this() { auto router = new URLRouter; router.get("/", staticTemplate!"index.dt"); router.post("/login", &login); router.post("/logout", &logout); // restrict all following routes to authenticated users: router.any("*", &checkLogin); router.get("/home", staticTemplate!"home.dt"); auto settings = new HTTPServerSettings; settings.sessionStore = new MemorySessionStore; // ... }
Client requests
Client request are done using the
requestHTTP function.
import vibe.vibe; void main() { requestHTTP("", (scope req) { // could add headers here before sending, // write a POST body, or do similar things. }, (scope res) { logInfo("Response: %s", res.bodyReader.readAllUTF8()); } ); }
A connection pool is used internally in conjunction with persistent HTTP connections (keep-alive) for maximum thoughput.
Web framework
Based on the low-level HTTP/HTML foundation, the high-level web application framework allows for faster and more solid web application development. It uses a class based declarative approach to avoid the boilerplate code that would otherwise usually be needed. Static typing is exploited as much as possible to avoid conversion errors, or errors accessing wrong runtime keys (such as a non-existent or mistyped form field).
The framework comes in two flavors, one for front end development, targeted at generating HTML pages and processing form requests, and one for REST based back end development, providing a transparent JSON/REST based RPC mechanism (client and server). Both of these components share the same basis and use the same approach to map class methods to routes of the
URLRouter.
For the usual case, both, the HTTP method and the matching path are inferred from the class method's name. In particular, the name is mapped to a certain HTTP method according to its prefix and the rest of the name is converted to a path name in a configurable style. On top of that, it is possible to use the
@path and
@method attributes to override these defaults.
Web interface generator
The front end web interface generator automatically maps incoming query or POST form fields to method parameters, performing the necessary conversion and validation automatically. On top of that, it offers several convenience functions for rendering Diet templates, handling sessions and performing redirects - without directly accessing the underlying
HTTPServerRequest or
HTTPServerResponse object. This enables a completely statically checked and clean code style in most cases.
For those situations where more control is required, it is possible to simply declare parameters of type
HTTPServerRequest or
HTTPServerResponse to give a method full access. Note that this is in contrast to the REST interface generator covered below, which cannot give access to the request/response without losing the ability to generate the client side of the REST protocol. It does, however, provide a way to get around this, using the
@before attribute.
import vibe.http.router; import vibe.http.server; import vibe.web.web; shared static this() { auto router = new URLRouter; router.registerWebInterface(new WebInterface); auto settings = new HTTPServerSettings; settings.port = 8080; settings.sessionStore = new MemorySessionStore; listenHTTP(settings, router); } class WebInterface { private { // stored in the session store SessionVar!(bool, "authenticated") ms_authenticated; } // GET / void index() { bool authenticated = ms_authenticated; render!("index.dt", authenticated); } // POST /login (username and password are automatically read as form fields) void postLogin(string username, string password) { enforceHTTP(username == "user" && password == "secret", HTTPStatus.forbidden, "Invalid user name or password."); ms_authenticated = true; redirect("/"); } // POST /logout @method(HTTPMethod.POST) @path("logout") void postLogout() { ms_authenticated = false; terminateSession(); redirect("/"); } }
doctype 5 html head title Welcome body h1 Welcome - if (authenticated) form(action="logout", method="POST") button(type="submit") Log out - else h2 Log in form(action="login", method="POST") p User name: input(type="text", name="username") p Password: input(type="password", name="password") button(type="submit")
Localization
Using GNU gettext compatible .po translation files, it's possible to localize Diet templates at compile time. This just requires putting the translation files with the naming scheme
<name>.<language>.po into a path that is registered in the
"stringImportPaths" field of the dub.json.
<language> must be a language identifier of the form
en_US.
import vibe.web.web; struct TranslationContext { alias languages = TypeTuple!("en_US", "de_DE"); mixin translationModule!"example"; } @translationContext!TranslationContext class WebInterface { void index() { render!("index.dt"); } }
doctype 5 html head title& Welcome body h1& Welcome p& home.welcome.text
msgid "Welcome" msgstr "Welcome" msgid "home.welcome-text" msgstr "Hello, this is a translation example."
msgid "Welcome" msgstr "Willkommen" msgid "home.welcome-text" msgstr "Hallo, dies ist ein Übersetzungs-Beispiel."
REST interface generator
Similar to the browser oriented web interface generator, there is a machine communication oriented JSON/REST based interface generator. Method parameters are mapped to JSON fields and get serialized according to the usual serialization rules. In addition to the interface generator, there is also a client generator, which automatically implements a class that emits the proper REST calls to access the REST interface.
import vibe.core.core; import vibe.core.log; import vibe.http.router; import vibe.http.server; import vibe.web.rest; struct Weather { string text; double temperature; // °C } interface MyAPI { // GET /weather -> responds {"text": "...", "temperature": ...} Weather getWeather(); // PUT /location -> accepts {"location": "..."} @property void location(string location); // GET /location -> responds "..." @property string location(); } class MyAPIImplementation : MyAPI { private { string m_location; } Weather getWeather() { return Weather("sunny", 25); } @property void location(string location) { m_location = location; } @property string location() { return m_location; } } shared static this() { auto router = new URLRouter; router.registerRestInterface(new MyAPIImplementation); auto settings = new HTTPServerSettings; settings.port = 8080; listenHTTP(settings, router); // create a client to talk to the API implementation over the REST interface runTask({ auto client = new RestInterfaceClient!MyAPI(""); auto weather = client.getWeather(); logInfo("Weather: %s, %s °C", weather.text, weather.temperature); client.location = "Paris"; logInfo("Location: %s", client.location); }); }
Database support
MongoDB
A nativeMongoDB
driver is part of the distribution supporting the standard set of database operations. Data is exchanged using the
Bson
struct.
For an comprehensive documentation of MongoDB's operations see theMongoDB manual . TheAPI reference contains the documentation for the driver.
import vibe.d; MongoClient client; void test() { auto coll = client.getCollection("test.collection"); foreach (doc; coll.find(["name": "Peter"])) logInfo("Found entry: %s", doc.toJson()); } shared static this() { client = connectMongoDB("127.0.0.1"); }
Redis
A client for the structured storage serverRedis
is included in vibe.d. Commands and operations on Redis data types are implemented as instance methods of the client and of the
RedisDatabase class. The methods are named after their corresponding Redis command documented in thecommand reference
.
On top of the low level interface, two high level modules,
types and
idioms are available to solve common tasks in a more convenient and type safe way. In addition to that, a Redis based HTTP session store is also included.
Raw TCP
Low level TCP connections are handled using the
TCPConnection
class, which implements the
ConnectionStream
interface. Connections can be established by either listening on a specific port for incoming connections or by actively connecting to a remote server.
Server
Listening for TCP connections is done using the
listenTCP
function. An implementation of a very simple echo server could look like this:
import vibe.d; shared static this() { listenTCP(7, (conn){ conn.write(conn) }); }
Calling
listenTCP
like this will listen on all local network devices. To listen only on a specific device, the bind address can be given as an additional parameter:
import vibe.d; shared static this() { listenTCP(7, conn => conn.write(conn), "127.0.0.1"); }
The address can be given as either an IPv4 or an IPv6 address string.
Client
Connecting to a TCP server is done with the
connectTCP
function. The following example gets the current time using theDaytime Protocol
.
import vibe.d; shared static this() { auto conn = connectTCP("time-c.nist.gov", 13); logInfo("The time is: %s", conn.readAllUTF8()); }
Raw UDP
In addition to stream based TCP connections, packet based UDP communication is also supported. To open a UDP socket, use the
listenUDP
function with the appropriate port. It will return a
UDPConnection
instance, which can then be used to send and receive individual packets.
import vibe.appmain; import vibe.core.core; import vibe.core.log; import vibe.core.net; import core.time; shared static this() { runTask({ auto udp_listener = listenUDP(1234); while (true) { auto pack = udp_listener.recv(); logInfo("Got packet: %s", cast(string)pack); } }); runTask({ auto udp_sender = listenUDP(0); udp_sender.connect("127.0.0.1", 1234); while (true) { sleep(dur!"msecs"(500)); logInfo("Sending packet..."); udp_sender.send(cast(ubyte[])"Hello, World!"); } }); }
Advanced topics
Publishing on the DUB registry
TheDUB registry contains packages that use the same package management as vibe.d. Many of them extend and supplement vibe.d's functionality. The packages are automatically downloaded if the corresponding entry in the "dependencies" section of the project's dub.json file is present.
If you have written an extension library yourself, you can register it in the DUB registry so others can easily make use of it. For this to work, you will first have to write a proper dub.json, which has to reside in the root directory of your project (the project should adhere to the structure mentioned in the first steps). The project currently also has to be hosted either on GitHub or on BitBucket. See for more information.
{ "name": "vibelog", "description": "A light-weight embeddable blog implementation", "homepage": "", "license": "AGPL-3.0", "authors": [ "Sönke Ludwig" ], "dependencies": { "vibe-d": "~>0.7.23" } }
You can then register your project oncode.dlang.org and as soon as you then add a newgit tag with the name matching the current version prefixed with "v" ("v0.0.1" for the example here), it should appear there. Note that the update can take up to 30 minutes. Anyone can then add an entry similar to the following to their project to make use of the library:
{ ... "dependencies": { "vibelog": ">=0.0.1" } }
The main function
To simplify development of server-like applications that are command line based and run an event loop, vibe.d includes a default application entry point (
main()). To use it, define the version
VibeDefaultMain when building the project. This can be done by simply adding the following entry to your package description file:
"versions": ["VibeDefaultMain"]
When writing a pure command line client application, maybe something like wget, it may not be desirable to start an explicit event loop, but instead exit right after the work is done. Some applications might also need more control over how the application gets initialized and at which point the event loop is started. To support such usage scenarios, you can implement your own program entry function instead.
Note: Projects that have their own program entry point currently, due to a transition process, also need to define a
VibeCustomMain version instead of
VibeDefaultMain. This requirement will be lifted in a later version of vibe.d.
import vibe.vibe; void main() { // returns false if a help screen has been requested and displayed (--help) if (!finalizeCommandLineOptions()) return; lowerPrivileges(); runEventLoop(); }
import vibe.vibe; void main() { auto f = openFile("test.html", FileMode.CreateTrunc); f.write(download("")); }
Privilege lowering
For server applications it may be desirable to start the application as root so that it can listen on privileged ports or open system log files for writing. After these setup tasks, such applications impose a security risk because a hole in the application that allows to somehow execute malicious commands on the server will give the attacker full access to the system. For this reason vibe.d supports privilege lowering, where the user id and group id of the process are changed to an unprivileged user after the startup process, right before the event loop is started.
Privilege lowering can be configured in the configuration file /etc/vibe/vibe.conf (on Windows vibe.conf must be in the application's root directory instead). The two fields "user" and "group" have to be set to the the name or numeric ID of the unprivileged user/group.
{ "user": "www-data", "group": "www-data" }
Compile time configuration
There is a number of features that can be controlled via "versions". To defined a certain version, add the corresponding entry to the
"versions" in your dub.json:
{ ... "versions": ["VibeManualMemoryManagement", "VibeDefaultMain"], ... }
Handling segmentation-faults on Linux
While access violations on Windows usually trigger an exception with a convenient stack trace, on other operating systems D applications just terminate and possibly cause a core dump file to be written. However, there is a module hidden in the D runtime that enables such a stack trace also on Linux. Simply run the following code at program initialization:
import etc.linux.memoryerror; static if (is(typeof(registerMemoryErrorHandler))) registerMemoryErrorHandler(); | http://vibed.org/docs | CC-MAIN-2016-50 | en | refinedweb |
Opened 10 years ago
Closed 10 years ago
Last modified 10 years ago
#2555 closed defect (wontfix)
[patch] Validators in BooleanField validator_list are called only when the field is set to True
Description
Assume the following model:
def check_frobbyness( field_data, all_data): raise ValidationError, "Booh!" class Frob( models.Model): is_frobby = models.BooleanField( _("Frobs OK"), validator_list=[ check_frobbyness])
The
ValidationError occurs exactly when the checkbox
is_frobby is checked in the admin, therefore validation is not possible for the "off" state.
Attachments (2)
Change History (5)
Changed 10 years ago by
comment:1 Changed 10 years ago by
Changed 10 years ago by
A cleaner solution... with a separated javascript file and more modular
comment:2 Changed 10 years ago by
Thanks for the patch, but I think this fix is a bit too heavy-handed for this case. If you want a validator to always run for a BooleanField, set the
always_test attribute on the validator to True.
This feature is, admittedly, undocumented right at the moment, but that will be fixed shortly.
comment:3 Changed 10 years ago by
Sorry, that resolution decision was made by me. Was accidently not logged in.
Fixed... it uses Javascript but without JS behaviour is good (same behaviour than before patching) | https://code.djangoproject.com/ticket/2555 | CC-MAIN-2016-50 | en | refinedweb |
I am trying to redirect one page to another by using mitmproxy and Python. I can run my inline script together with mitmproxy without issues, but I am stuck when it comes to changing the URL to another URL. Like if I went to google.com it would redirect to stackoverflow.com
def response(context, flow):
print("DEBUG")
if flow.request.url.startswith(""):
print("It does contain it")
flow.request.url = ""
print("It does contain it")
flow.request.url = ""
print("DEBUG")
if "google.com" in flow.request.url
google.com
Setting the
url attribute will not help you, as it is merely constructed from underlying data.
Depending on what exactly you want to accomplish, there are two options.
(1) You can send an actual HTTP redirection response to the client. Assuming that the client understands HTTP redirections, it will submit a new request to the URL you give it.
from mitmproxy.models import HTTPResponse from netlib.http import Headers def request(context, flow): if flow.request.host == 'google.com': flow.reply(HTTPResponse('HTTP/1.1', 302, 'Found', Headers(Location='', Content_Length='0'), b''))
(2) You can silently route the same request to a different host. The client will not see this, it will assume that it’s still talking to
google.com.
def request(context, flow): if flow.request.url == '': flow.request.host = 'stackoverflow.com' flow.request.path = '/users/'
These snippets were adapted from an example found in mitmproxy’s own GitHub repo. There are many more examples there.
For some reason, I can’t seem to make these snippets work for Firefox when used with TLS (
https://), but maybe you don’t need that. | https://codedump.io/share/W02H1ioTcN11/1/change-url-to-another-url-using-mitmproxy | CC-MAIN-2016-50 | en | refinedweb |
CA1414: Mark boolean P/Invoke arguments with MarshalAs
A platform invoke method declaration includes a System.Boolean parameter or return value but the System.Runtime.InteropServices.MarshalAsAttribute attribute is not applied to the parameter or return value.
A platform invoke method accesses unmanaged code and is defined by using the Declare keyword in Visual Basic or the System.Runtime.InteropServices.DllImportAttribute. MarshalAsAttribute specifies the marshaling behavior that is used to convert data types between managed and unmanaged code. Many simple data types, such as System.Byte and System.Int32, have a single representation in unmanaged code and do not require specification of their marshaling behavior; the common language runtime automatically supplies the correct behavior.
The Boolean data type has multiple representations in unmanaged code. When the MarshalAsAttribute is not specified, the default marshaling behavior for the Boolean data type is UnmanagedType.Bool. This is a 32-bit integer, which is not appropriate in all circumstances. The Boolean representation that is required by the unmanaged method should be determined and matched to the appropriate System.Runtime.InteropServices.UnmanagedType. UnmanagedType.Bool is the Win32 BOOL type, which is always 4 bytes. UnmanagedType.U1 should be used for C++ bool or other 1-byte types. For more information, see Default Marshaling for Boolean Types.
To fix a violation of this rule, apply MarshalAsAttribute to the Boolean parameter or return value. Set the value of the attribute to the appropriate UnmanagedType.
The following example shows two platform invoke methods that are marked with the appropriate MarshalAsAttribute attributes.
using System; using System.Runtime.InteropServices; [assembly: ComVisible(false)] namespace InteroperabilityLibrary { [ComVisible(true)] internal class NativeMethods { private NativeMethods() {} [DllImport("user32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern Boolean MessageBeep(UInt32 uType); [DllImport("mscoree.dll", CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.U1)] internal static extern bool StrongNameSignatureVerificationEx( [MarshalAs(UnmanagedType.LPWStr)] string wszFilePath, [MarshalAs(UnmanagedType.U1)] bool fForceVerification, [MarshalAs(UnmanagedType.U1)] out bool pfWasVerified); } } | https://msdn.microsoft.com/en-us/library/ms182206(VS.100).aspx | CC-MAIN-2016-50 | en | refinedweb |
LayoutMirroring QML Type
Property used to mirror layout behavior More...
Properties
- childrenInherit : bool
- enabled : bool
Detailed Description
The LayoutMirroring attached property is used to horizontally mirror Item anchors, positioner types (such as Row and Grid) and views (such as GridView and horizontal ListView). Mirroring is a visual change: left anchors become right anchors, and positioner types like Grid and Row reverse the horizontal layout of child items.
Mirroring is enabled for an item by setting the enabled property to true. By default, this only affects the item itself; setting the childrenInherit property to true propagates the mirroring behavior to all child items as well. If the
LayoutMirroring attached property has not been defined for an item, mirroring is not enabled.
The following example shows mirroring in action. The Row below is specified as being anchored to the left of its parent. However, since mirroring has been enabled, the anchor is horizontally reversed and it is now anchored to the right. Also, since items in a Row are positioned from left to right by default, they are now positioned from right to left instead, as demonstrated by the numbering and opacity of the items:
import QtQuick 2.0 Rectangle { LayoutMirroring.enabled: true LayoutMirroring.childrenInherit: true width: 300; height: 50 color: "yellow" border.width: 1 Row { anchors { left: parent.left; margins: 5 } y: 5; spacing: 5 Repeater { model: 5 Rectangle { color: "red" opacity: (5 - index) / 5 width: 40; height: 40 Text { text: index + 1 anchors.centerIn: parent } } } } }
Layout mirroring is useful when it is necessary to support both left-to-right and right-to-left layout versions of an application to target different language areas. The childrenInherit property allows layout mirroring to be applied without manually setting layout configurations for every item in an application. Keep in mind, however, that mirroring does not affect any positioning that is defined by the Item x coordinate value, so even with mirroring enabled, it will often be necessary to apply some layout fixes to support the desired layout direction. Also, it may be necessary to disable the mirroring of individual child items (by setting LayoutMirroring.enabled to false for such items) if mirroring is not the desired behavior, or if the child item already implements mirroring in some custom way.
See Right-to-left User Interfaces for further details on using
LayoutMirroring and other related features to implement right-to-left support for an application.
Property Documentation
This property holds whether the LayoutMirroring.enabled value for this item is inherited by its children.
The default value is false.
This property holds whether the item's layout is mirrored horizontally. Setting this to true horizontally reverses anchor settings such that left anchors become right, and right anchors become left. For positioner types (such as Row and Grid) and view types (such as GridView and ListView) this also mirrors the horizontal layout direction of the item.. | http://doc.qt.io/qt-5/qml-qtquick-layoutmirroring.html | CC-MAIN-2016-50 | en | refinedweb |
You are free to check some expression to evaluates some block of code as per your requirement. Java provides decision making statements to perform this task.
Java supports the following two decision making statements :
These statements allows you to control the flow of program's execution based upon the conditions known only during the run-time.
The if statement comprises of Boolean expression, followed by one or more statements. You will learn about the if statement in separate chapter.
The switch statement allows a variable to be tested for equality against the list of values. Each value is called a case, and the variable which being switched on is checked for the each case. You will learn about switch statement in separate chapter.
Here is an example program, helps in understanding how the decision making statement works in Java:
/* Java Decision Making - Example Program */ public class JavaProgram { public static void main(String args[]) { int num1=50, num2=60; if(num1>num2) { System.out.println("num1 is greater than num2"); } else { System.out.println("num1 is not greater than num2"); } } }
Here is the output produced by the above Java program:
Tools
Calculator
Quick Links | http://codescracker.com/java/java-decision-making.htm | CC-MAIN-2016-50 | en | refinedweb |
Welcome back. This is the final article in my series on making Swing applications feel native. In Part 1, we set up custom menus, the appropriate L&F, and native user alerts. InPart 2, we built double-clickable applications and added file-type associations. In this last installment, we will create custom icons and add some final polish to really make our application shine.
Setting the Icon
Now that the application looks and launches native, what about the icon? Both Mac and Windows have a default executable icon for all Java applications (Figures 1 and 2). These icons are pretty useless, since they don't look any different than any other generic application, Java or otherwise, much less reflect anything special about your app. So let's get rid of that right away.
Creating an OS X Icon
To get a better-looking application, first we have to create the icon and then attach it to the executable. For the Mac, we can use Apple's IconComposer utility, located in/Developer/Applications. You can see it in action in Figure 3. You will need to install the free developer tools from Apple. This program doesn't have command-line access, unfortunately, but it shouldn't matter, since we probably won't be changing our icon very often.
To generate an icon, just drag the source image from the Finder into each thumbnail well and save it into the src/imagesdirectory. IconComposer should accept any image format that QuickTime understands, which includes all of the major formats, such as GIF, TIFF, PNG, and JPEG. I have had the best success with PNGs because IconComposer can use the alpha channel in your PNG (assuming you created one) to generate the hit mask. A hit mask is a second bitmap that indicates which part of the image can be clicked on. The operating system will use this for drawing selections and doing transparency on the desktop. Once saved, this will create a .icns file.
Figure 3. IconComposer in action
With the icon created, we just need to attach it to the program. We need to set another property in our Info.plist file to tell the Finder which icon to use. (The Info.plist file was introduced in Part 2 of our series.)
<key>CFBundleIconFile</key> <string>MadChatter.icns</string>
Finally, we add a copy task to the
osx.app task of our Ant build file to copy the image into theContents/Resources directory of our application bundle.
<copy todir="${dist-mac}/${app-name}.app/Contents/Resources"> <fileset dir="${src}/images"> <include name="*"/> </fileset> </copy>
Now run the
osx.app target, and we get an application with an icon in Figure 4.
Figure 4. Mac OS X Application Icon
Creating a Windows Icon
As with OS X, Windows uses its own proprietary and incompatible icon format, this time called a .ico. Under Windows, we will use an open source program, png2ico, which can generate a .ico file from a PNG image. We will use the same PNG image that we used with IconComposer for OSX. One more Ant task will do the trick.
<target name="win-icon"> <exec executable="bin/png2ico.exe" dir="."> <arg value="${build}/icon.ico"/> <arg value="${images}/icon.png"/> </exec> </target>
Unfortunately, attaching the icon to the executable isn't as easy as it is on the Macintosh. There isn't an officially sanctioned API to do it, and it doesn't look like there's going to be one any time soon. Fortunately, our packager, JExePack, can create a .exe with any icon we specify. We just need to add this line to our jexepack.ini file:
/icon:images\icon.ico
Notice the use of a backslash: this is the platform-specific separator for Windows.
Run the
exe task and we get another desktop application with a real icon, as seen in figure 5.
Figure 5. Windows Application Icon
Compressed Packaging
We want to make installation as easy for our users as possible, so the final step is to compress our program for easy download. The .exe will go into a .zip file, since .zip is the most common compression format for Windows, and XP supports it natively in the File Explorer. For the Mac, we will use the .tar.gz format, since it's also built-in and can handle preserving the executable bit that lets OS X know it's a program. We won't used StuffIt because it's commercial and not as easily scriptable. I've also decided not to use a disk image, because it's difficult to automate the disk creator program and get the volume sizes right. Perhaps in the next release of the developer tools this will be an option.
Here are our final two build targets:
<target name="dist-mac" depends="OS X.app"> <exec command= "tar -C ${dist-mac} -cvf ${dist-mac}/${app-name}.tar ${app-name}.app"/> <gzip zipfile="${dist-mac}/${app-name}.tar.gz" src="${dist-mac}/${app-name}.tar"/> </target> <target name="dist-win" depends="exe"> <zip zipfile="${build}/${app-name}.zip" basedir="${dist-win"/> </target>
Native Open and Save Dialogs
Now we want to do a few final things to make the application feel native. The first is to use native file dialogs. The Swing file open and close dialogs are very powerful but not identical to the native dialogs. An alternative is to use the AWT FileDialog instead of the JFileChooser, since the AWT version uses a native component. However, recent versions of the Windows JDK have made great strides in perfecting the Swing JFileChooser. Now it actually looks better than the standard native file chooser and more like the advanced file browser you would find in modern Microsoft applications (like Outlook). And if you do use the AWT version, you will have to give up the customization of the JFileChooser. It's a command decision. We could go with native for all platforms, but I've chosen to only use it on the Mac, per Apple's recommendations, and to use a JFileChooser on other platforms. The code is pretty straightforward:
save.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { if(xp.isMac()) { // use the native file dialog on the mac FileDialog dialog = new FileDialog(frame, "Save Log",FileDialog.SAVE); dialog.show(); } else { // use a swing file dialog on the other platforms JFileChooser chooser = new JFileChooser(); chooser.showOpenDialog(frame); } } });
Adding a Splash Screen
While not strictly a native application issue, it would be nice to have a splash screen. It makes our program feel a little bit more professional. Splash screens were originally invented to mask the loading process, but our app will probably load pretty quickly, so we'll just give it a time delay.
Our splash screen will be a
JWindow without any decorations (title bar, close and minimize buttons, etc.), centered on the screen. We want an image (from our fantastic graphic design department, right?) smack in the middle of the panel. While we could subclass
Panel to draw it, the quickest way to get an
Image on the screen is to use an
ImageIcon in a textless
JLabel. Then we turn off decorations and do some quick calculations to center the frame on the screen. A quick note here: we have to do a
pack() before our calculations, because the width and height are undefined until
pack() has been called.
public class SplashScreen extends JWindow { public SplashScreen() { ImageIcon image = null; JLabel label = new JLabel(image); try { image = new ImageIcon("logo.png"); label = new JLabel(image); } catch (Exception ex) { u.p(ex); label = new JLabel("unable to load: " + res); } getContentPane().add(label); pack(); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); int x = (int)(dim.getWidth() - getWidth())/2; int y = (int)(dim.getHeight() - getHeight())/2; setLocation(x,y); } }
Notice something here: we are loading the image from a string. This string represents the filename relative to the current working directory. Our entire philosophy up to this point has been that we should avoid having extra files lying around; anything extra can be lost or corrupted. We could package the image up using the mechanisms built into JExePack and Application Bundles, but Java actually has its own way of doing it: resource bundles. You can load a resource from the classpath, the same way a class is loaded. Then it won't matter if our application is compressed into a .jar or loaded across the network, as long as we put the resource with the classes, we can get to it. We just copy the resource, an image in our case, into the directory with our classfiles and then use a different function to load it.
First we need to modify the build file to put the images into the right place. To make sure the image gets picked up by all of the different packaging tasks we'll just put it in the compile target, which is required by all of them. Now the target looks like this:
<target name="compile" depends="init" description="compile"> <mkdir dir="${classes}"/> <javac srcdir="${java}" destdir="${classes}" debug="on"> <classpath> <fileset dir="${lib}"> <include name="*.jar"/> </fileset> </classpath> </javac> <copy file="${src}//images/2004/01/logo.png" todir="${classes}"/> </target>
Finally, we change the call to
ImageIcon:
ImageIcon image = new ImageIcon(this.getClass().getResource("/logo.png"));
Note that I've put a
/ at the front of the logo path. If we didn't put in a
/ the class loader would assume that it was relative to the current class, and would prepend it with the package name. Thus it would look for/org/joshy/oreilly/swingnative/logo.png and would return null when it couldn't find the image.
We can launch
SplashScreen with a thread that just sleeps for three seconds and then closes the window. Since this is a separate thread, the main initialization code (say, connecting to the chat server) can continue to run in the background. In a more sophisticated application, we would have the initialization code actually close the splash screen instead of just waiting three seconds.
final SplashScreen splash = new SplashScreen(); splash.pack(); splash.show(); new Thread(new Runnable() { public void run() { try { Thread.currentThread().sleep(3000); splash.hide(); } catch (InterruptedException ex) { } } }).start();
The splash screen looks like Figure 6:
Figure 6. The Splash Screen
Conclusion
It's a lot of work to make Java applications cross platforms and still feel natural to users on those platforms, but with some help from the platform provider and the use of open source libraries, we can make it happen. We have created native menus, file-type associations, user alerts, a splash screen, and most importantly, native executables. All of these add up to a much more pleasant experience for the end user.
With the hope that we can make this easier, I have created a Java.net project where we can develop reusable technology for native integration. It will begin with the codebase for The Mad Chatter; we will add to it as the community grows. | https://community.oracle.com/docs/DOC-983319 | CC-MAIN-2016-50 | en | refinedweb |
SignedData object
[The SignedData object is available for use in the operating systems specified in the Requirements section. Instead, use the SignedCms Class in the System.Security.Cryptography.Pkcs namespace.]
The SignedData object provides properties and methods to establish the content to be signed with a digital signature, to sign or cosign data digitally, and to verify the digital signature of signed data. The signed message is in PKCS #7 format.
A data signature, if verified, proves the association between a signer and data and shows that the data was not changed in any way after the signature was created.
The SignedData object has these types of members:
Methods
The SignedData object has these methods.
Properties
The SignedData object has these properties.
Remarks
The SignedData object can be created, and it is safe for scripting. The ProgID for the SignedData object is CAPICOM.SignedData.1.
Requirements
See also | https://msdn.microsoft.com/en-us/library/windows/desktop/aa387722.aspx | CC-MAIN-2016-50 | en | refinedweb |
Can someone please help fix this program? I'm pretty new in Python. Every time I run this program it says :
Traceback (most recent call last):
File "E:/Python/delin.py", line 38, in <module>
discounted_total = regular_total - full_discount
TypeError: unsupported operand type(s) for -: 'float' and 'NoneType'
def find_discount(total):
if total <120:
discount = 0
else:
if total <300:
discount = 0.03*total
else:
if total <500:
discount = 0.05*total
else:
discount = 0.07*total
return discount
#---------------------------------------------------------------------------
#main program
beef = 8.49
pork = 6.12
chicken = 5.21
quantity_beef= input("How many pounds of beef were bought?")
quantity_pork = input("How many pounds of pork were bought")
quantity_chicken = input("How many pounds of chicken were bought?")
total_beef = beef * quantity_beef
total_pork = pork * quantity_pork
total_chicken = chicken * quantity_chicken
regular_total = total_beef + total_pork + total_chicken
full_discount = find_discount(regular_total)
discounted_total = regular_total - full_discount
print "The total is " + discounted_total
This is Python 2.7 btw.
Edit: also, the function on the top [find_discount(total)] has the normal indentations needed. But when posting this, the lines didn't indent
Edited 6 Years Ago by hi102: Version of Python, Note | https://www.daniweb.com/programming/software-development/threads/327506/python-typeerror-unsupported-operand-type-s-for-float-and-nonetype | CC-MAIN-2016-50 | en | refinedweb |
Here boolean hideIssueReceipt() {
> return hideAcknowledgePayment();
> }
>
> public String disableIssueReceipt() {
> return disableAcknowledgePayment();
> }
>
> Compare this to:
> /**
> * Invoice life-cycle 3a: Treasurer acknowledges payment / generates
> receipt (updates balance)
> */
> public Receipt acknowledgePayment(final Payment invoicePayment,
> @Named("Amount paid") final double payment);
>
> with methods:
> public boolean hideAcknowledgePayment() {
> return (authentication.hasCouncilRights() != true);
> }
>
> public String disableAcknowledgePayment() {
> if (authentication.hasTreasurerRights() != true) {
> return "Only for treasurer";
> }
> return null;
> }
>
> The applib methods "hideAcknowledgePayment" and
> "disableAcknowledgePayment" are hidden from the user, as expected.
>
> The applib methods "hideIssueReceipt" and "disableIssueReceipt" are
> visible to the user, which is very much unexpected.
>
>
> On 5 Feb 2012 at 17:33, Dan Haywood wrote:
>
> > On 5 February 2012 15:31, Kevin Meyer - KMZ <kevin@kmz.co.za> wrote:
> >
> > >
> > > I don't know how long this has been a problem - but I'm getting some
> > > weirdness from FacetedMethodsBuilder:
> > >
> > > 17:13:37,881 [FacetedMethodsBuilder main INFO ] introspecting
> > > dom.finance.Receipt
> > > 17:13:37,913 [FacetedMethodsBuilder main INFO ] skipping
> > > possible helper method public abstract dom.finance.Receipt
> > >
> dom.IMember.issueReceipt(dom.finance.Invoice,double,dom.finance.Payment)
> > >
> > > The problem is that "issueReceipt" has corresponding
> > > "hideIssueReceipt" and "disableIssueReceipt" that are not being
> > > picked up as applib methods and are left behind as visible actions that
> > > the user can invoke.
> > >
> > > issueReceipt is an action on my Member interface, used by the
> > > treasurer.
> > > /**
> > > * Issue a receipt for an invoice, for an optional payment.
> > > *
> > > * @param invoice
> > > * @param amountPaid
> > > * @param payment
> > > * @return
> > > */
> > > public Receipt issueReceipt(final Invoice invoice, @Named("Amount
> > > paid") double amountPaid,
> > > @Optional final Payment payment);
> > >
> > >
> > > Any advice as to what is going on here?
> >
> > My guess is it's a mismatch in the set of arguments to the helpers.
> >
> > Can you post the hide and disable methods also?
>
> | http://mail-archives.apache.org/mod_mbox/incubator-isis-dev/201202.mbox/%3CCALJOYLG2rXrpiLdZfXwhHBnd+FveBADMt3fytJa3AOTLFsMXug@mail.gmail.com%3E | CC-MAIN-2016-50 | en | refinedweb |
E
August 13, 2010
We begin with a function
f to count the random numbers required to reach a sum greater than one:
(define (f)
(do ((i 0 (+ i 1))
(s 0.0 (+ s (rand))))
((< 1 s) i)))
Now we run the simulation n times:
(define (e n)
(do ((i 0 (+ i 1))
(s 0.0 (+ s (f))))
((= i n) (/ s i))))
And the answer is:
> (e #e1e6)
2.718844
Run
f enough times, and the surprising average is the transcendental number e. A good explanation of the math involved is given by John Walker. Mathematically, this puzzle is known as the uniform sum distribution.
We used
rand from the Standard Prelude. You can run the program at.
[…] Praxis – E By Remco Niemeijer In today’s Programming Praxis exercise our task is to determine how many random numbers between 0 and 1 we […]
My Haskell solution (see for a version with comments):
A couple of improvements could be made. I left the j variable in accidently, it is unused. In C++, the scope of the sum value could be confined to the for loop in which it appears. A do { } while loop would mean that I didnt have two different increments of the ttrial variable.
Here’s my solution in Clojure:
PLT “racket”:
#! /bin/sh
#| Hey Emacs, this is -*-scheme-*- code!
#$Id$
exec mzscheme -l errortrace –require “$0″ –main — ${1+”$@”}
|#
#lang scheme
;;
(define (trial)
(let loop ([number-of-numbers 0]
[sum 0])
(if (inexact
(/ (apply + outcomes)
(length outcomes)))))
(provide main)
/me tips his hat to Mark VandeWettering, Oregon ’86 or thereabouts
Gaah. Stupid wordpad.
Here’s a Python implementation:
import random
import sys
random.seed()
numIterations = int(sys.argv[1])
count = 0.0
sum = 0.0
for i in range(numIterations):
sum += random.random()
if sum > 1.0:
count += 1.0
sum = 0.0
print numIterations/count
A naive ruby implementation
Here’s a Java solution:
The output, as expected, is 2.72197.
(* OCaml *)
let test () =
let acc = ref 0. and cpt = ref 0 in
while !acc < 1. do
incr cpt;
acc := !acc +. (Random.float 1.);
done;
!cpt;;
let mean n =
let rec aux n =
if n = 0
then 0
else test () + aux (n-1)
in
(float_of_int (aux n)) /. (float_of_int n);;
print_string ((string_of_float (mean 10000))^”\n”);;
(* Purely functional looks even better (well, as in “no references”…) *)
let rec test acc cpt =
if acc < 1.
then test (acc +. (Random.float 1.)) (cpt + 1)
else cpt
let mean n =
let rec aux n =
if n = 0
then 0
else test 0. 0 + aux (n-1)
in (float_of_int (aux n)) /. (float_of_int n);;
print_string ((string_of_float (mean 10000))^”\n”);;
[…] about computing Euler’s Number, e, using Clojure. It wasn’t until I saw the idea on Programming Praxis, though, that I decided to just do […]
//quick and dirty javascript
var getRandomCount = function(ctr,buf){
while(buf < 1){
var nbr = Math.random();
ctr = ctr + 1;
buf = buf + nbr;
}
return ctr;
}
var getAverageNumberOfTimes = function(iter){
var total = 0;
for(i=0;i<iter;i++){
total = total + getRandomCount(0,0);
}
return total;
}
alert(getAverageNumberOfTimes(1000)/1000);
C#
Random randNum = new Random();
int trials = 1000000;
long totalTrials = 0;
double i = 0;
for (int runs = 0; runs < trials; i = 0, runs++)
for (totalTrials++ ; (i += randNum.NextDouble()) < 1.0; totalTrials++) ;
Console.WriteLine((float)totalTrials / trials);
Console.ReadLine();
Here is a FORTH version, without floating point.
A random 32 bit number is treated as binary random between 0-1. When overflow occurs (requires 33 bits), it is interpreted as exceeding 1.0.
And here is session with SwiftForth :- | https://programmingpraxis.com/2010/08/13/e/2/ | CC-MAIN-2016-50 | en | refinedweb |
Ticket #5223 (closed Bugs: fixed)
boost::regex only accepts turning off one Perl modifier
Description
I'm trying to use modifiers with the extended Perl syntax. Turning on multiple modifiers seems to work fine, but turning them off only seems to accept a single modifier after the '-':
#include <iostream> #include <boost/regex.hpp>
int main() {
using std::cerr; using boost::regex; using boost::regex_error;
try {
regex m1("(?xism:
d)", regex::perl); ok regex m2("(?-x:
d)", regex::perl); ok regex m3("(?-xism
d)", regex::perl); bad regexp
} catch (boost::regex_error err) {
cerr << "Bad regular expression: " << err.what() << "\n";
}
}
I'm using Boost 1.45 from MacPorts? on Mac OS X 10.6.6, trying to "port" some Perl code to C++.
Attachments
Change History
comment:1 Changed 6 years ago by lpancescu@…
- Summary changed from boost::perl only accepts turning off one Perl modifier to boost::regex only accepts turning off one Perl modifier
comment:2 Changed 6 years ago by johnmaddock
- Status changed from new to closed
- Resolution set to fixed
Test case | https://svn.boost.org/trac/boost/ticket/5223 | CC-MAIN-2016-50 | en | refinedweb |
0
Below is my LinkedList class and also a private Node class inside it, I also write a unit test method to test if every method in LinkedList work, but the hasNext() and Next() ultimately failed.
Please let me know what is wrong with the next() and hasNext() method.
Here is the program:
public class LinkedList<E> { private static class Node<E> { public E data; public Node<E> next; public Node(E data, Node<E> next) { this.data = data; this.next = next; } } private Node<E> head; // the number of elements in the list private int count; public LinkedList() { head = null; count = 0; } public void addToFront(E e) { head = new Node<E>(e, head); count++; } public void remove(E e) { Node<E> previous = null; Node <E>current = head; while (current != null) { if(current.data.equals(e)) { current = current.next; if(previous == null) { previous = current; } else { previous.next = current; count--; } } else { previous = current; current = current.next; } } count--; } // size() returns the number of elements in this list. public int size() { return count; } public void clear() { head = null; count = 0; } // iterator() returns a new iterator that has not yet returned any of // the elements of this list. public Iterator iterator() { return new Iterator(); } public class Iterator { // you'll need to add fields here public Node<E> cursor; // The constructor initializes a new iterator that has not yet // returned any of the elements of the list. public Iterator() { cursor = head; } // hasNext() returns true if there are more elements in the list // that have not been returned, and false if there are no more // elements. public boolean hasNext() { if(cursor.next == null) { return true; } return false; } public E next() { if(hasNext()) { throw new NoSuchElementException("No next element"); } E toReturn = cursor.data; cursor = cursor.next; return toReturn; } } }
Here is the test case:
public class ForwardingProgram { public static void main(String[] args) { LinkedList<String> list = new LinkedList<String>(); list.addToFront("Will"); list.addToFront("this"); list.addToFront("work?"); LinkedList<String>.Iterator i = list.iterator(); while(i.hasNext()) { System.out.println(i.next()); } } }
so the while loop should print out Will this work?
but my compiler didn't show that to me.
Please let me know what is wrong with it.
Edited 6 Years Ago by jliao20: n/a | https://www.daniweb.com/programming/software-development/threads/316528/java-linkedlist-help-on-hasnext-and-next-method | CC-MAIN-2016-50 | en | refinedweb |
Hi!
This is my first day developing for the Nokia 6700 Classic!
I've got my Java installed, Netbeans Mobile, and finally the S40 SDK from Nokia. I've been able to compile and publish the GameBuilder1 demo to my phone. It's great.
I saw a 3D cube demo along with the GameBuilder demo, so I tried compiling it, sadly it failed telling me the following don't exist:
import java.nio.*;
import javax.microedition.khronos.egl.*;
import javax.microedition.khronos.opengles.*;
After about 40 minutes of surfing the internet looking for a nice JSR239.JAR file to download and add to my compile path - all I've seen is the bloody documents... documents, documents... and more documents.
Not a single set of classes anywhere! =(
Can somebody PLEASE point me towards a download for the above imports?
Please!? | http://www.khronos.org/message_boards/showthread.php/6278-Help!-S40-development?p=20366&mode=linear | CC-MAIN-2014-35 | en | refinedweb |
]>
NAME
SYNOPSIS
REQUEST ARGUMENTS
DESCRIPTION
RETURN VALUE
ERRORS
SEE ALSO
AUTHOR
xcb_grab_key − Grab keyboard key(s)
#include <xcb/xproto.h>
Request function
owner_events
If 1, the grab_window will still get the pointer events. If 0, events are not reported to the grab_window.
grab_window
Specifies the window on which the pointer should be grabbed.
Using the special value XCB_MOD_MASK_ANY means grab the pointer with all possible modifier combinations.
The special value XCB_GRAB_ANY means grab any key.
pointer.
keyboard.
Establishes a passive grab on the keyboard. In the future, the keyboard is actively grabbed (as for Grab.
Returns an xcb_void_cookie_t. Errors (if any) have to be handled in the event loop.
If you want to handle errors directly with xcb_request_check instead, use xcb_grab_key_checked. See xcb-requests(3) for details.
xcb_access_error_t
Another client has already issued a GrabKey with the same button/key combination on the same window.
xcb_window_error_t
The specified window does not exist.
xcb_value_error_t
TODO: reasons?
xcb-requests(3), xcb_grab_keyboard(3)
Generated from xproto.xml. Contact xcb@lists.freedesktop.org for corrections and improvements. | http://www.x.org/releases/current/doc/man/man3/xcb_grab_key.3.xhtml | CC-MAIN-2014-35 | en | refinedweb |
Auteur de questions
Self-hosted WCF Service - Clustered Environment
Hello,
I developed a self-hosted Windows Service WCF application that basically just exposes some interface to the WPF client (authentication, report viewing, etc.). The configuration on my service is stated below:
<system.serviceModel> <services> <service name="WcfNamespace.MyService" behaviorConfiguration="WcfNamespace.MyServiceBehavior"> <host> <baseAddresses> <add baseAddress="" /> </baseAddresses> </host> <endpoint address="" bindingNamespace="" binding="wsHttpBinding" bindingConfiguration="MyWsHttpBinding" name="wsHttpEndpoint" contract="WcfNamespace.Contracts.IKioskService" behaviorConfiguration="MyEndpointBehavior"> </endpoint> <endpoint address="mex" binding="mexHttpsBinding" name="MexHttpsBindingEndpoint" contract="IMetadataExchange"/> </service> </services> <behaviors> <endpointBehaviors> <behavior name="MyEndpointBehavior"> <dataContractSerializer maxItemsInObjectGraph="2147483647"/> </behavior> </endpointBehaviors> <serviceBehaviors> <behavior name="WcfNamespace.MyServiceBehavior"> <serviceMetadata httpGetEnabled="False" httpsGetEnabled="True" /> <serviceDebug includeExceptionDetailInFaults="False" /> <dataContractSerializer maxItemsInObjectGraph="2147483647" /> </behavior> </serviceBehaviors> </behaviors> <bindings> <wsHttpBinding> <binding name="MyWsHttpBinding" receiveTimeout="01:00:00" openTimeout="01:00:00" closeTimeout="01:00:00" sendTimeout="01:00:00" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" messageEncoding="Mtom" > <security mode="Transport"> <message establishSecurityContext="false" /> <transport clientCredentialType="None" /> </security> <readerQuotas maxArrayLength="2147483647" maxDepth="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" maxStringContentLength="2147483647"/> </binding> </wsHttpBinding> </bindings> </system.serviceModel>
This works fine in a non-clustered environment but when deployed to the production server (3 nodes - clustered server) it is not working. The client cannot authenticate or get any result from any of the interface exposed in the server.
Sometimes we get this error even though the service is running for the 3 nodes when investigated and accessing the WCF service endpoint URL directly in the browser is working fine.
"An error occurred while receiving the HTTP response to. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down"
I am new to WCF obviously and also somehow I tried to set the keepAliveEnabled to false but still no luck using Custom Binding.
<customBinding> <binding name="MyCustomBinding" receiveTimeout="01:00:00" openTimeout="01:00:00" closeTimeout="01:00:00" sendTimeout="01:00:00"> <mtomMessageEncoding maxBufferSize="2147483647" maxWritePoolSize="2147483647" maxReadPoolSize="2147483647"> <readerQuotas maxArrayLength="2147483647" maxDepth="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" maxStringContentLength="2147483647"/> </mtomMessageEncoding> <httpsTransport authenticationScheme="Anonymous" transferMode="Streamed" keepAliveEnabled="false" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" maxBufferPoolSize="2147483647" /> </binding> </customBinding>
I have read couple of articles including the forum thread that is related to this topic but with no luck and some I am not sure if related to this problem.
Please let me know what am I missing as this is going nuts already for almost 2 days. Thanks.
Question
Toutes les réponses
hi
Is there a load balancer?
When you turn off security does it work?
Turn on WCF log and trace on the server(s) to see what error they contain.
Yaron
WCF Security, Interoperability And Performance Blog
You need to check whether you have any object in DataContract which can be serialized. or try increasing the value of maxRequestLength in httpRuntime and timeouts and buffer sizes. As Yaron Naveh metioned, you'd better enable WCF tracing at the server side to see the inner detailed error information to find some indicates.
#enable WCF tracing.
You can also check this article.
Please mark the replies as answers if they help or unmark if not. If you have any feedback about my replies, please contact msdnmg@microsoft.com Microsoft One Code Framework
Hi Peter,
I think I have increased the sizes as per my configuration sample (first post) since we have encountered issues before regarding that and so every timeout and buffer size is set to "2147483647". Also set the data contract serializer max object graph size to "2147483647".
Please elaborate when you say "You need to check whether you have any object in DataContract which can be serialized". I have data contracts object that is returned by the service that looks like the sample code below and so how do I determine if that needs to be serialized? please bare with me on this.
[DataContract] public class MyObject { [DataMember] public DateTime TransDate { get; set; } [DataMember] public string Name { get; set; } }Thanks for the information about enabling the WCF tracing. I will try this out and get back to you as well.
As for that sentence, what I meaning is that you need to check the DataContract class as return type or parameter in WCF operations whether has other class object that cannot be serialized. But see the above DataContract class, all the class members can be serialized.
Please mark the replies as answers if they help or unmark if not. If you have any feedback about my replies, please contact msdnmg@microsoft.com Microsoft One Code Framework
Ok, so should I leave it as is or I need to do something for the members to be serializable? As far as I know though, WCF Data contact serialization happens by default as long the types are supported.
- Modifié dotnetnewby vendredi 13 avril 2012 08:37
Hi,
I enabled the WCF tracing and I saw the following error messages from tracelog.svclog:).
Receive bytes on connection ''.
There is a problem with the XML that was received from the network. See inner exception for more details.
System.ServiceModel.Channels.HttpRequestContext.CreateMessage()
System.ServiceModel.Channels.HttpChannelListener.HttpContextReceived(HttpRequestContext context, Action callback)
System.ServiceModel.Channels.SharedHttpTransportManager.OnGetContextCore(IAsyncResult result)
System.ServiceModel.Channels.SharedHttpTransportManager.OnGetContext(IAsyncResult result)
System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
System.Net.LazyAsyncResult.Complete(IntPtr userToken)
System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken)
System.Net.ListenerAsyncResult.WaitCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP))."
in the clustered environment, when you have a client to by pass the lb and talk directly to the service, does it work? if so compare the message between working and non working clinet.
one gotcha is that the ws addressing To header may be different. You may need to define a clientVia behavior on the client and a ListenUri on all servers. Each client states in the To header to which server it goes to. If you do not use clientVia then the server url will be the physical one (lb / proxy). the actual servers will reject that destination To. So you need to override on the client what it sends (clientVia) and on servers what they expect (ListenUri).
WCF Security, Interoperability And Performance Blog
The error illustrates that the receiver could not process the message because no contract claimed it.
As the error message described, it may be caused by the following reasons.
1. You have different contracts between client and sender.
2. You’re using a different binding between client and sender.
3. The message security settings are not consistent between client and sender.
For more about this, here is a similar post to which you can refer.
Please mark the replies as answers if they help or unmark if not. If you have any feedback about my replies, please contact msdnmg@microsoft.com Microsoft One Code Framework
- Marqué comme réponse dotnetnewby mercredi 25 avril 2012 10:59
- Non marqué comme réponse dotnetnewby mercredi 25 avril 2012 11:00
- Thank Peter, I will look into the link you provided. However, just wondering how the first and second items happen. Our WPF client basically reference the same production URL specified in the service and so binding should also be the same. Please correct me if I am wrong here.
- lb is load balancer, but it can be any router that decides to which of the 3 servers the client request will go.
WCF Security, Interoperability And Performance Blog | http://social.msdn.microsoft.com/Forums/vstudio/fr-FR/280435bc-172e-48e8-a8c8-e55c858d6382/selfhosted-wcf-service-clustered-environment?forum=wcf | CC-MAIN-2014-35 | en | refinedweb |
11 March 2010 22:48 [Source: ICIS news]
HOUSTON (ICIS news)--US imports of methyl ethyl ketone (MEK) rose in January to 5,628 tonnes, an increase of 129% from 2,454 tonnes imported during the same month of 2009, according to US International Trade Commission (ITC) data released on Thursday.
Competitively priced imports contributed to larger volumes sent to the ?xml:namespace>
MEK imports were up by nearly 170% in January from December, the commission indicated.
US MEK exports also rose significantly in January to 2,891 tonnes compared with the 1,122 tonnes shipped to foreign buyers in January a year ago, according to the ITC.
About 52% of January’s MEK exports were shipped to
Current US prices for MEK were 62-66 cents/lb ($1,367-1,455/tonne, €998-1,062/tonne), according to data from global chemical market intelligence service ICIS pricing.
US MEK suppliers include Shell Chemicals and ExxonMobil.
($1= €0.73) | http://www.icis.com/Articles/2010/03/11/9342119/us-january-mek-imports-more-than-double-year-ago-volume.html | CC-MAIN-2014-35 | en | refinedweb |
This article will show you how to develop Windbg extensions in Visual Studio, and to leverage the .NET platform through the C++/CLI technology.
Windbg
I was once assigned the task to evaluate the applicability of code obfuscation of .NET assemblies with respect to protection of intellectual property, but also its consequences for debugging and support.
Obfuscation is not without drawbacks. It makes debugging almost impossible, unless it is possible to reverse the obfuscation.
The Obfuscator I evaluated provided an external tool for deobfuscation with the use of map files. You had to manually copy and paste the text into this tool.
Although deobfuscation was possible, it was still very tedious to do so.
In order to make full obfuscation a viable approach, we needed it to be integrated in the build environment by using plugins for both Visual Studio and Windbg. Luckily, the Obfuscator company, provided a public .NET Assembly, which they encouraged you to use.
Windbg
My first approach was to build a normal Windbg Extension with the Windows Driver Kit (WDK), and make it use a C++/CLI DLL built in Visual Studio. This C++/CLI DLL would in turn, use the .NET Assembly. The solution proved to be much simpler.
Enjoy the reading!
Read the manual that comes with Windbg.
It clearly states that you should use the Windows Driver Kit.
Below, you see a screenshot of the build environment.
It is a command line based build environment.
After having been spoiled with Visual Studio, it is not really fun to go back to command line based environments. It only reminds me of the spartan development tools they have in UN*X.
There is a salvation for us Visual Studio fans. I came across this article Developing WinDbg Extension DLLs. It is a step by step guide on how to develop Windbg Extensions with Visual Studio. Praise the Lord!!
My contribution is showing you how to integrate .NET assemblies in your Windbg Extensions. The road to success was trial and error development, recompilation, and lots of crashes.
The earlier mentioned article showed only how to build Windbg Extensions in Visual Studio in native C++ using the C API.
I got that working. Then I changed the project into a managed C++/CLI project. The extension still worked. That implied that it would be possible to use .NET assemblies.
Then, I changed to the C++ API of windbg. That did not work. It crashed on loading the DLL. Since my concern was the Deobfuscator not troubleshooting, I reverted back to the C API.
windbg
To add a reference to .NET library, you have two options:
Right clicking on the project, and selecting "references" to bring up this window.
Another approach is just to add the following line in your C++ file.
#using "StackTraceDeobfuscator.dll"
Now it is possible to call the .NET Assembly from C++/CLI.
StackTraceDeobfuscator^ decoder = gcnew StackTraceDeobfuscator(filename);
String^ s = decoder->DeobfuscateText(obfuscatedText);
Managed objects, such as strings, cannot be passed around freely. Managed strings are references. The garbage collector performs memory compactation once in a while, meaning that the underlying memory can move around. Another restriction is that unmanaged code cannot use managed types. Fortunately, there is a special data type, called msclr::auto_gcroot that addresses this problem. For further information, please read Mixing Native and Managed Types in C++.
string
msclr::auto_gcroot
#include <span class="code-keyword"><msclr\auto_gcroot.h>
</span>
struct NativeContainer
{
msclr::auto_gcroot<String^> obj;
};
NativeContainer container;
void foo(const char* text)
{
container.obj = gcnew String(text);
}
I used this construction in order to save the filename to the mapfile between calls.
In order to avoid allocation when you use char* strings, try to use the std::string. That type will automatically handle deallocation and reallocation for you.
char* string
std::string
std::string str = "abc";
str += "def";
char* backAgain = str->c_str();
You might also need to convert a managed string to a native string and pass it to a native C/C++ function.
string
void OutCliString(String^ clistr)
{
IntPtr p = Marshal::StringToHGlobalAnsi(clistr);
const char* linkStr = static_cast<char* />(p.ToPointer());
dprintf(linkStr);
Marshal::FreeHGlobal(p);
}
I had to use it in order to call the C API function dprintf for outputting text to Windbg.
dprintf
Then I tested my extension:
0:000> .loadby sos mscorwks
0:000> .load DeobfuscateExt.dll
0:000> !mapfile C:\SecretApp_1.0.0.0.nrmap
0:000> !dclrstack
To my surprise, it crashed when it tried to access the .NET assembly. So I inserted some exception handling, in order to get the error message. This is what I saw:
0:000> !dclrstack
Exception
Could not load file or assembly
'StackTraceDeobfuscator, Version=..., Culture=neutral, PublicKeyToken=...'
or one of its dependencies. The system cannot find the file specified.
How was that possible? It existed in the same directory as the other DLL.
After many failed attempts to get it working, I almost included the assembly as an embedded resource, to be loaded manually through the LoadAssembly function.
LoadAssembly
To my rescue, was the Process Monitor program from sysinternals. It logs registry accesses, loading of libraries, assembly bindings, etc. In the log, I could see that Windbg looked in the GAC, then it looked in the installation folder, but never in the winext extension folder.
When I copied the .NET library to the installation folder, it worked. DLLs are supposed to be copied to the winext folder. Since I don't like ugly work-arounds, I continued to investigate. In Process Monitor, I saw that the assembly loader, also looked for a Windbg.config file, but none was found. Then it hit me. The .NET assembly loader, sees Windbg as a .NET application now.
After adding a windbg.config file in the installation folder, telling windbg to look in the winext folder for .NET extensions. It finally worked.
windbg
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<runtime>
<assemblyBinding
xmlns="urn:schemas-microsoft-com:asm.v1">
<probing privatePath="winext" />
</assemblyBinding>
</runtime>
</configuration>
This is how the final result looked in Windbg:
0:000> g
// Load in the SOS .Net extension
0:000> .loadby sos mscorwks
// Display the .Net callstack
0:000> !ClrStack
OS Thread Id: 0x748 (0)
ESP EIP
003bed14 770b22a1 [NDirectMethodFrameStandalone:
003bed14] EP8d6KKZNOc1stcvCF.rW7Nf5orPqjZvnA6qV.VeInoLCS1()
003bed24 0029390b EP8d6KKZNOc1stcvCF.rW7Nf5orPqjZvnA6qV.glsAhkOLS(System.String)
003bed30 002938e9 EP8d6KKZNOc1stcvCF.rW7Nf5orPqjZvnA6qV.RqruoQ7Wy(System.String)
003bed38 002938c9 EP8d6KKZNOc1stcvCF.rW7Nf5orPqjZvnA6qV.y870B2Qwn(System.String)
003bed40 002938a9 EP8d6KKZNOc1stcvCF.rW7Nf5orPqjZvnA6qV.MshWmjm77(System.String)
003bed48 00293889 EP8d6KKZNOc1stcvCF.rW7Nf5orPqjZvnA6qV.EQqEmimFN(System.String)
003bed50 00293869 EP8d6KKZNOc1stcvCF.rW7Nf5orPqjZvnA6qV.lTK9lM3pf(System.String)
003bed58 00293849 EP8d6KKZNOc1stcvCF.rW7Nf5orPqjZvnA6qV.CRBliDoRv(System.String)
003bed60 00293829 EP8d6KKZNOc1stcvCF.rW7Nf5orPqjZvnA6qV.rEXh0q6dg(System.String)
003bed68 0029009d yIRVo677UilAvTI0XH.LoYYaNO29PLFbE32gm.ayXxZy7mO(System.String[])
003bef94 6f0a1b6c [GCFrame: 003bef94]
// Load my deobfuscator extension
0:000> .load DeobfuscateExt.dll
0:000> !mapfile C:\SecretApp_1.0.0.0.nrmap
0:000> !dclrstack
OS Thread Id: 0x748 (0)
ESP EIP
003bed14 770b22a1 [NDirectMethodFrameStandalone: 003bed14]
SecretApp.NestingCalls.DebugBreak()
003bed24 0029390b SecretApp.NestingCalls.Ti(System.String)
003bed30 002938e9 SecretApp.NestingCalls.La(System.String)
003bed38 002938c9 SecretApp.NestingCalls.So(System.String)
003bed40 002938a9 SecretApp.NestingCalls.Fa(System.String)
003bed48 00293889 SecretApp.NestingCalls.Mi(System.String)
003bed50 00293869 SecretApp.NestingCalls.Re(System.String)
003bed58 00293849 SecretApp.NestingCalls.Do(System.String)
003bed60 00293829 SecretApp.NestingCalls.Execute(System.String)
003bed68 0029009d SecretApp.Program.Main(System.String[])
003bef94 6f0a1b6c [GCFrame: 003bef94]
My extension works as a filter on its input. It was written to deobfuscate the output from the ClrStack command in the Sos extension.
ClrStack
// Other possibilities
0:000> !dclrstack -a // Same as !ClrStack -a
0:000> !deobfuscate !ClrStack -a // The general deobfuscate function
// executes "!ClrStack -a"
0:000> !deobfuscate <cmd> <cmd> <cmd>
The implementation was originally done for a specific Obfuscator. Since I was unsure of the appropriateness to include their DLL in this project, I removed it. The only thing changed from the original implementation is the reference to StackTraceDeobfuscator.dll, which has been replaced by a simple dummy .NET DLL which just converts its input to uppercase. The windbg command mapfile accepts any existing file. The command dclrstack and deobfuscate just converts its input to uppercase.
mapfile
dclrstack
deobfuscate
I didn't get the C++ API of windbg to work. The C++ API, is a set of macros, which is expanded to C functions, which calls into the C++ methods. The C function gets called correctly, and the transition to the C++ method too. But the call to a base class constructor makes it crash. I analyzed the crashes a bit. To me, it seems to be some conflict in the calling convention between __cdecl and __stdcall. I still haven't figured out a way to make it work. Any contribution in that area is highly appreciated.
__cdecl
__stdcall. | http://www.codeproject.com/script/Articles/View.aspx?aid=187726 | CC-MAIN-2014-35 | en | refinedweb |
iGeneralFactorySubMesh Struct Reference
[Mesh plugins]
A submesh of a genmesh factory. More...
#include <imesh/genmesh.h>
Inheritance diagram for iGeneralFactorySubMesh:
Detailed Description
A submesh of a genmesh factory.
Definition at line 51 of file genmesh.h.
Member Function Documentation
Add a sliding window for progressive LODs.
Clear progressive LOD sliding windows.
Return the start index and end index of the sliding window indicated by index.
Get the number of LOD sliding windows for progressive LODs.
The documentation for this struct was generated from the following file:
Generated for Crystal Space 2.0 by doxygen 1.6.1 | http://www.crystalspace3d.org/docs/online/api-2.0/structiGeneralFactorySubMesh.html | CC-MAIN-2014-35 | en | refinedweb |
Child of FieldSet has height that extends the contents of Field Set (clips correctly)
Child of FieldSet has height that extends the contents of Field Set (clips correctly)
G
VerticalLayoutDataWithinFieldSetExtendsPastFieldSet.jpg
Chrome 25
VerticalLayoutDataWithinFieldSetExtendsPastFieldSet_Chrome.jpg.
Code:
ContentPanel p = new ContentPanel(); p.setHeadingText("panel"); container.add(p, new VerticalLayoutData(1, 1, new Margins(5)));
VerticalLayoutDataWithinFieldSetExtendsPastFieldSetContentPanel.png
Chrome
VerticalLayoutDataWithinFieldSetExtendsPastFieldSetContentPanel_Chrome.png
Test Code
FieldSetAndVerticalLayoutContainer.zip
Based on other useful information Colin has provided on another topic, did changes to my .html and .gwt.xml file, and neither fixed this issue.
removed unnecessary code from the Examples.html file and made sure it had a link to the reset.css style sheet.
Code:
<!doctype html> <html> <head> <link type="text/css" rel="stylesheet" href="examples/reset.css" /> <script type="text/javascript" language="javascript" src="examples/examples.nocache.js"></script> </head> <body> </body> </html>
<inherits name='com.google.gwt.user.User' />
<inherits name='com.google.gwt.user.theme.clean.Clean' />
Code:
<?xml version="1.0" encoding="UTF-8"?> <module rename- <inherits name="com.sencha.gxt.ui.GXT" /> <set-property <set-property <source path='client' /> <entry-point </module>
Thanks, I've confirmed this issue, though am not yet certain of the cause or a workaround. It seems to behave properly in FF17, but incorrectly in both IE8 and Chrome 23. There are slight differences between how it is broken in Chrome 23 and IE8 though.
We'll update this thread when we've come to any conclusion on the bug, or if a workaround becomes available.
And by the way, there is no problem with having an inherits statement for the User module - but it isn't required either. GXT depends on and inherits User, so it will implicitly be added automatically.
Simplest test case I can produce, broken in Chrome 23 (just barely too tall), in IE8 (slightly too tall). It appears that GXT is measuring the element that it should be, but that these browser report sizes that do not make sense when asked for how much space is available inside the fieldset's body (they either include too much top or bottom padding/margin that is owned by the parent), while FF17 reports the correct values.
Code:
public class Test implements EntryPoint { private FieldSet fieldSet = new FieldSet(); private VerticalLayoutContainer container = new VerticalLayoutContainer(); public Test() { ContentPanel p = new ContentPanel(); p.setHeadingText("panel"); container.add(p, new VerticalLayoutData(1, 1)); fieldSet.setHeadingText("field set"); fieldSet.add(container); } public void onModuleLoad() { Viewport viewport = new Viewport(); viewport.add(fieldSet, new MarginData(20));//margins help to show overlap in firebug/inspector RootPanel.get().add(viewport); } }
Success! Looks like we've fixed this one. According to our records the fix was applied for EXTGWT-2660 in a recent build. | http://www.sencha.com/forum/showthread.php?250675-Child-of-FieldSet-has-height-that-extends-the-contents-of-Field-Set-(clips-correctly)&p=918153 | CC-MAIN-2014-35 | en | refinedweb |
I am trying to create a program to calculate the Fantasy performances of my players, but I am comming across some problems. Here is my Code so far.
The bolded portion gives me the error "no matching function to call RunningBack::GetRush(int)"The bolded portion gives me the error "no matching function to call RunningBack::GetRush(int)"Code:#include <iostream> using namespace std; class RunningBack { public: int GetRush(int); void SetRush(int rush); private: int itsRush; }; int RunningBack::GetRush(int rush) { cin >> rush; return itsRush; } void RunningBack::SetRush(int rush) { itsRush = rush; } int main() { RunningBack Back1; cout<< "Back number 1 ran for " ; cout << Back1.GetRush() << " yards today\n"; cin.get(); return 0; }
I can't get it to display the yards that you input. Also how do I convert these yards to points. The points work like this: for every 20 yards you get 1 point. So if the user inputs 97 it should round off to 4 points. | http://cboard.cprogramming.com/cplusplus-programming/83382-fantasy-calculator.html | CC-MAIN-2014-35 | en | refinedweb |
I have played around with SSE. I am using VS2012, and I wanted to know what was the fastest way to calculate the length of a vector.
The code looks very bad.
float Magnitude() const { #if SSE && SSE_ASM float result; //Optimized magnitude calculation with SSE and Assembly __asm { MOV EAX, this //Move [this] to EAX. MOVAPS XMM2, [EAX] //Copy data EAX to XMM2 register MULPS XMM2, XMM2 //Square the XMM2 register. MOVAPS XMM1, XMM2 //Make a copy SHUFPS XMM2, XMM1, _MM_SHUFFLE(1, 0, 3, 2) //Shuffle so that we can add together the elements. ADDPS XMM2, XMM1 //Add the elements. MOVAPS XMM1, XMM2 //Make a copy SHUFPS XMM1, XMM1, _MM_SHUFFLE(0, 1, 0, 1) //Second addition of elements using shuffle ADDPS XMM2, XMM1 SQRTPS XMM2, XMM2 //Get the square root MOVSS [result], XMM2 //Store the result in the float. } return result; #elif SSE __m128 tmp = _mm_mul_ps(components, components); tmp = _mm_add_ps(_mm_shuffle_ps(tmp, tmp, _MM_SHUFFLE(1, 0, 3, 2)), tmp); tmp = _mm_sqrt_ps(_mm_add_ps(tmp, _mm_shuffle_ps(tmp, tmp, _MM_SHUFFLE(0, 1, 0, 1)))); float result; _mm_store_ss(&result, tmp); return result; #endif #if !SSE && !SSE_ASM return sqrtf(__x * __x + __y * __y + __z * __z + __w * __w); #endif }
Guess what, the normal method was as fast as the SSE-Intrinsics, while my assembly code was acctually slower.
So yeah, you can't beat the compiler
| http://www.gamedev.net/user/179450-tapped/?tab=topics | CC-MAIN-2014-35 | en | refinedweb |
You use the component compiler to generate a SWC file from
component source files and other asset files such as images and
style sheets.
To use the component compiler with
Flex SDK, you use the compc command-line utility. In Flash Builder,
you use the compc component compiler by building a new Flex Library
Project. Some of the Flex SDK command-line options have equivalents
in the Flash Builder environment. You use the tabs in the Flex Library
Build Path dialog box to add classes, libraries, and other resources
to the SWC file.
About the component compiler options
Compiling stand-alone components
and classes
Compiling components in packages
Compiling components using namespaces
Adding utility classes
Adding nonsource classes
Creating themes | http://help.adobe.com/en_US/Flex/4.0/UsingSDK/WS2db454920e96a9e51e63e3d11c0bf69084-7fd2.html | CC-MAIN-2014-35 | en | refinedweb |
If you have been lucky enough to get the Compact Framework or Smart devices extension beta for April 2002 you may be wondering what you can do with it. After previous articles showing some simple C# code I though why not do something with the Internet and getting stock quotes is a good idea.However before delving into this article ask yourself why, bearing in mind that Pocket PC comes with a pretty good web browser would you write an application to access a web site directly? The simple reason is that most web sites do not consider that they may be accessed by a small device like a Pocket PC and so write web pages assuming everyone is running on a large screen. Of course a pocket PC screen is typically one quarter the size of a VGA screen so you can see the problem.Even so if you accessed nasdaq.com using the Pocket PC browser it would do a fairly good job of trying to fit all the information on screen. Of course all this takes time and as web sites get more complicated the browser on the Pocket PC does a lot of work working out how to present information designed for a large screen on to the small Pocket PC screen.That is why being able to write programs like this and bypass a web browser alltogether can be useful.Here is what the application runs like on my Pocket PC emulator:As you can see from the code I am using the WebRequest and WebResponse classes to talk to. I read the response into a string and then search through it using the IndexOf methd of the string class. Using this simple technique allows me to search through the returned HTML code and extract the data I need. Of course if Nasdaq.com change their pages then its likely this code will break.Once again I tested this code on the Pocket PC emulator and it worked fine if slightly slowly. Some things to note where this program could be improved.
Lastly, to show that this program is waiting for web responses I display an hourglass using Pocket PC APIs to inform the user the program is actually busy.When I get more time later versions of this program will gather more Nasdaq information and allow you to do things like symbol lookups etc//PocketPCNasdaq.cs//Lets you check stock quotes over internet on a Pocket PC//Written using Compact Framework Beta 1//Written May 21st 2002 by John O'Donnell - csharpconsulting@hotmail.com using System;using System.Windows.Forms;using System.Net;using System.IO;using System.Text;using System.Runtime.InteropServices;namespace PocketPCNasdaq{public class Form1 : System.Windows.Forms.Form{private const int hourGlassCursorID = 32514;//Pocket PC API's to show and hide waitcursor[DllImport("coredll.dll")]private static extern int LoadCursor(int zeroValue, int cursorID);[DllImport("coredll.dll")]private static extern int SetCursor(int cursorHandle); private System.Windows.Forms.Label label1;private System.Windows.Forms.Label label5;private System.Windows.Forms.Label label4;private System.Windows.Forms.Label label3;private System.Windows.Forms.Label label2;private System.Windows.Forms.TextBox textBox1;private System.Windows.Forms.TextBox textBox2;private System.Windows.Forms.TextBox textBox3;private System.Windows.Forms.TextBox textBox4;private System.Windows.Forms.TextBox textBox5;private System.Windows.Forms.Button button1;private System.Windows.Forms.Label label7;private System.Windows.Forms.Label label8;private System.Windows.Forms.Panel panel1;public Form1(){InitializeComponent();}protected override void Dispose( bool disposing ){base.Dispose( disposing );}#region Windows Form Designer generated code// Some code here#endregion static void Main() {Application.Run(new Form1());}private void button1_Click(object sender, System.EventArgs e){this.ShowWaitCursor(true);if (textBox1.Text!="")label2.Text=GetQuote(textBox1.Text);if (textBox2.Text!="")label3.Text=GetQuote(textBox2.Text); if (textBox3.Text!="")label4.Text=GetQuote(textBox3.Text);if (textBox4.Text!="")label5.Text=GetQuote(textBox4.Text);if (textBox5.Text!="")label6.Text=GetQuote(textBox5.Text); this.ShowWaitCursor(false);}//Returns the current value for a particular stockpublic string GetQuote(string symbol){string a;string b;string c;string d="";string query=;query=query+symbol+"&&quick.x=0&quick.y=0";WebRequest wrq = WebRequest.Create(query);// Return the response. WebResponse wr= wrq.GetResponse();StreamReader sr = new StreamReader(wr.GetResponseStream(),Encoding.ASCII);a=sr.ReadToEnd().ToString();if(a.IndexOf("data")>-1){int pos1=a.IndexOf("[");int pos2=a.IndexOf("]");b=a.Substring(pos1+1,pos2-pos1);pos1=b.IndexOf(";");c=b.Substring(pos1,10);pos1=c.IndexOf(",");d=c.Substring(1,pos1-2); } //close resources between callswr.Close();sr.Close(); return(d);}// Shows or Hides the wait cursor on the PPCpublic void ShowWaitCursor(bool ShowCursor) {int cursorHandle = 0;if (ShowCursor) {cursorHandle = LoadCursor(0, hourGlassCursorID);}SetCursor(cursorHandle);}}}
©2014
C# Corner. All contents are copyright of their authors. | http://www.c-sharpcorner.com/UploadFile/jodonnell/GettingQuotesInPocketPC11292005035750AM/GettingQuotesInPocketPC.aspx | CC-MAIN-2014-35 | en | refinedweb |
java.lang.Object
oracle.adf.share.prefs.ADFPreferencesFactoryoracle.adf.share.prefs.ADFPreferencesFactory
public class ADFPreferencesFactory
A factory object that generates Preferences objects. This factory class
has been implemented to provide access to an MDS back ended Preferences
Repository. This also brings with it a richer user concept based on the
J2EE authenticated username, and the ability to define user over system
customization levels beyond the standard Java Preferences API's system and
user levels, which are also still catered for..
public ADFPreferencesFactory()
public ADFPreferencesFactory(ADFPreferencesConfig config)
config- The ADFPreferenceConfig object to be used by this factory.
public java.util.prefs.Preferences systemRoot()
systemRootin interface
java.util.prefs.PreferencesFactory
public java.util.prefs.Preferences userRoot()
userRootin interface
java.util.prefs.PreferencesFactory
public java.util.prefs.Preferences sharedUserRoot()
public java.util.prefs.Preferences sharedSystemRoot()
public java.util.prefs.Preferences userOverSystemRoot()
protected ADFPreferencesRegistry getRegistry()
public static void cleanUpApplicationState(java.lang.ClassLoader appClassLoader)
appClassLoader- The application class loader. | http://docs.oracle.com/cd/E28280_01/apirefs.1111/e10686/oracle/adf/share/prefs/ADFPreferencesFactory.html | CC-MAIN-2014-35 | en | refinedweb |
Factory for creating BorderedSolver strategy objects. More...
#include <LOCA_BorderedSolver_Factory.H>
Factory for creating BorderedSolver strategy objects.
The parameters passed to the create() through the
solverParams argument method should specify the "Bordered Solver Method" as described below, as well as any additional parameters for the particular strategy.
There are also Epetra and LAPACK specific strategies that can be instantiated by the LOCA::Epetra::Factory and LOCA::LAPACK::Factory. See LOCA::BorderedSolver::LAPACKDirectSolve, LOCA::BorderedSolver::EpetraHouseholder and LOCA::BorderedSolver::Epetra::Augmented.
Create bordered system solver strategy.
References Teuchos::RCP< T >::get(), and Teuchos::rcp(). | http://trilinos.sandia.gov/packages/docs/r10.6/packages/nox/doc/html/classLOCA_1_1BorderedSolver_1_1Factory.html | CC-MAIN-2014-35 | en | refinedweb |
*
A friendly place for programming greenhorns!
Big Moose Saloon
Search
|
Java FAQ
|
Recent Topics
|
Flagged Topics
|
Hot Topics
|
Zero Replies
Register / Login
JavaRanch
»
Java Forums
»
Java
»
Beginning Java
Author
Need help with Incompatible type error
Ken smith
Greenhorn
Joined: Jun 01, 2006
Posts: 8
posted
Jun 04, 2006 12:14:00
0
I'm trying to resolve this problem.
Numbers whose sum of digit divible by 3 represent number divisible by 3.
Write a program to verify this famous statement.
Input a 5-digit interger n from the keyboard.
Find the sum of digits. Call it sum.
Verify the either (a)both n and the sum are divisible by 3 or (b)both are indivisible by 3.
Your output is:
Given number n = ...
Print one of the following three statement:
(a)Both n and sum are divisible by 3.
(b)Both n and sum are indivisible by 3.
(c)The famous statement is wrong
I'm getting Incompatible type error when I run the code below on if(g = 0).
import java.util.*; class test {); System.out.println("Remainder after division = " + g); if(g = 0) System.out.println("Sum is divisible by 3"); } }
My questions are:
1) on if(g = 0), I thought 0 is a int. What is wrong with g = 0.
2) How do I capture n in a variable and
test
if it divisible by 3. For example: if I type in 58973 on the key borad, I would like to capture this intergers in a variable. Does anyone knows what's happening here. Please help
Regards
Ken
Rusty Shackleford
Ranch Hand
Joined: Jan 03, 2006
Posts: 490
posted
Jun 04, 2006 12:28:00
0
1. Nothing generally, but the if statement needs a boolean value and in Java booleans are not numeric values. Try using a comparison operator instead of the assignment operator.
2. Do you mean it divides evenly with 3? ie 3,6,9,... Check out the modulus operator(%)
[ June 04, 2006: Message edited by: Rusty Shackleford ]
"Computer science is no more about computers than astronomy is about telescopes" - Edsger Dijkstra
Jeroen T Wenting
Ranch Hand
Joined: Apr 21, 2006
Posts: 1847
posted
Jun 04, 2006 12:44:00
0
g = 0 results in an int (namely the result of the assignment, in this case 0(.
An if statement requires a boolean,
Therefore using an integer assignment (like g = 0) as a condition for an if statement (or any boolean statement) is illegal, as a boolean statement requires a boolean condition.
42
Ken smith
Greenhorn
Joined: Jun 01, 2006
Posts: 8
posted
Jun 04, 2006 13:53:00
0
Thanks for responding to my posting. I've modify the code as seen below. The error message is gone. Does anyone knows what the n in the problem above means? On Given number n = .... What does the n stands for? Thanks in advance
import java.util.*; class Week5prob2KT {); if(0<g&&g>0) System.out.println("Both n and Sum are indivisible by 3"); else System.out.println("Both n and Sum are divisible by 3"); } }
Rusty Shackleford
Ranch Hand
Joined: Jan 03, 2006
Posts: 490
posted
Jun 04, 2006 14:56:00
0
According to the problem you posted, n is the 5 digit number you entered. ie if you enter 12345, then n=12345 and sum=15. If I remember correctly, if the sum of the digits is divisible by three, then the number is also divisible by 3.
An easier way to test if a 0 was returned is if(g!=0) instead of if(g<0&&g>0). They are equivilent, but the second way has two comparison tests, so is a bit less efficient. When you add n into your program, there will be 2 required comparison checks, and the way you did it requires 4, thus a bit of a exponentional explosion can happen.
[ June 04, 2006: Message edited by: Rusty Shackleford ]
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 38334
23
posted
Jun 04, 2006 15:32:00
0
Have people really understood the problem? The problem is not how you find out whether a number divides by 3 (as Rusty Shackleford correctly says "if(n % 3 == 0)" is a lot easier).
The problem is how to add up the transverse sum (
ts
) of
n
= a number's digits in decimal. You see,
n - ts
always
divides exactly by 3, so if
ts
divides exactly by 3, then
n
divides exactly by 3. [It also works for dividing by 9.]
What happens when you write "myScanner.nextInt()" is that the program reads the next
int
, which is a 32-bit two's complement signed integer. What you hoped you would read from the keyboard is the next digit, which forms part of that
int
number when it is written out in decimal (=denary) numerals. You can't do that with nextInt(). There are ways to read a single character from the keyboard, but they are hard to work with.
What you need to do is to find out how to get a number like 59973 (which does, by the way, divide exactly by 3), and type it from the keyboard.
Your Scanner object
(kbi)
will give you an input of, would you believe, 59973.
So far, so good. You
don't
need 5 tries with the scanner to read a 5-digit number. You need one. One kbi.nextInt(); statement will read a 1-digit number or an 8-digit number just as easily.
Now you need to divide up your number 59973 into 5 9 9 7 and 3.
Do you know anything about iteration (repetition or loops) yet? It ought to be very easy to set up a loop which takes off successive digits (3 then 7 then 9 then 9 then 5 is much easier than 5 then 9 then 9 then 7 then 3).
If you don't know about iteration, you will have to make sure to stick to 5-digit numbers, and take each digit off in a line all of its own.
Then add them all together. Then see whether what you have divides exactly by 3.
By the way, Rusty, your second suggestion
if(g != 0)
is not only easier than
if(0 < g && g > 0)
; it will actually work. You didn't notice that
if (0 < g && g > 0)
always
returns
false
.
I hope that lot makes things clearer rather than obscuring things.
CR
By the way: If rather than verifying that a number whose transverse sum adds up to an exact multiple of 3 divides by 3, you would prefer to
prove
it, I know how to do that too.
[ June 04, 2006: Message edited by: Campbell Ritchie ]
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 38334
23
posted
Jun 04, 2006 15:39:00
0
I may have missed part of the point of Ken Smith's original post. Are you entering only single digits? It didn't say so on the posting.
I think your instructor expects you to be able to take a number apart into its constituent digits.
Rusty Shackleford
Ranch Hand
Joined: Jan 03, 2006
Posts: 490
posted
Jun 04, 2006 17:45:00
0
"You didn't notice that if (0 < g && g > 0) always returns false."
Whoops my bad, sorry about that.
I was a little hazy on that part of the divisibility rule. It is an if and only if definition. So really all you need to do is get the number from the user, and test that, by definition, if 3 divides that number, so will its sum. That makes the problem even more easier, but you can use the defintion to go the other way as well.
But there is a third possible output in the requirements: "The famous statement is wrong",it will never happen(Let Campbell Ritchie give ya the proof if you want, I am burned out on proofs), but you need to test for it. So you do need to check for n and the sum, and apply each conditional statement on both.
Just remember your program will not prove the statement, since it is unlikely you can test every single possiblity.
edit: here is a link about the rule and its proof:
[ June 04, 2006: Message edited by: Rusty Shackleford ]
I agree. Here's the link:
subject: Need help with Incompatible type error
Similar Threads
Scanner class help
what's wrong with this code?
Alphametics
Find prime nums from 1-100 algorithm
Why does my 'd' variable stay at zero?
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
JForum
|
Paul Wheaton | http://www.coderanch.com/t/403705/java/java/Incompatible-type-error | CC-MAIN-2014-35 | en | refinedweb |
In this article I will continue with explanations how to implement higly functional web 2.0 tables in J2EE using the JQuery. In the previous article "JQuery Data Tables in Java Web Applications" I have explained how you can easily convert a plain HTML table to fully functional Web 2.0 table. Here I will explain how you can add additional data management functionalities in web tables. The following example shows a web table that enables the user to edit cells using an inline editor.
You can see a lot of functionality in this table for data browsing (filtering by keyword, ordering by header cell, pagination, changing number of records that will be shown per page) and data management (editing cells inline, deleting rows, and adding new ones). In the first article about this topic "JQuery Data Tables in Java Web Applications", I have explained how to integrate basic JQuery DataTables functionalities with Java web tables.
Enhancing HTML tables with search, ordering, pagination, changing the number of records shown per page, etc., is an easy task if you are using the jQuery DataTables plug-in. Using this plug-in, you can add all the above mentioned functionalities to a plain HTML table placed in the source of a web page, using a single JavaScript call:
$("myTable").dataTable();
In this example, "myTable" is the ID of an HTML table that will be enhanced using the DataTables plug-in. The only requirement is to have a valid HTML table in the source of the web page.
myTable
The goal of this article is to show how you can add additional functionalities using the JQuery DataTables Editable plug-in. Using this plug-in, you can add features for inline editing, deleting rows, and adding new records using the following code:
$("myTable").dataTable().makeEditable();
This call will add data management functionalities on top of the standard DataTable functionalities. These functionalities handle complete interaction with the user related to editing cells, deleting and adding rows. On each action, the plug-in sends an AJAX request to the server-side with information about what should be modified, deleted, or added. If you are using a J2EE application, you will need to implement server-side functionalities that perform ADD, DELETE, and UPDATE that will be called by the DataTables Editable plug-in. In this article, you can find detailed instructions about the implementation of these data management functionalities.
This article will explain how you can convert plain tables into fully functional tables with data management functionalities. I will show you how you can implement the following:
These functionalities will be added directly on the client side using jQuery. The jQuery plug-in that enables these functionalities will handle the complete interaction with the user and send AJAX requests to the server-side. The advantage of this approach is that the jQuery plug-in is server-side platform independent, i.e., it can be applied regardless of what J2EE technology you are using (servlets, JSP, JSF, Struts, etc.). The only thing that is important is that your server-side component produces a valid HTML table as the one shown in the following example:
<table id="myDataTable">
<thead>
<tr>
<th>ID</th><th>Column 1</th><th>Column 2</th><th>Column 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td><td>a</td><td>b</td><td>c</td>
</tr>
<tr>
<td>2</td><td>e</td><td>f</td><td>g</td>
</tr>
</tbody>
</table>
If you generate that kind of HTML table on the server-side and send it to the client-side, you can decorate it with the jQuery DataTable and jQuery DataTable Editable plug-ins using the following line of code:
$("myDataTable").dataTable().makeEditable();
This call will add filtering, ordering, and pagination to your table (this will be done by the .dataTables() call), and on top of these functionalities will be added features that enable the user to add, edit, and delete records in the table. The DataTables Editable plug-in will handle all client side interaction and send AJAX requests to the server side depending on the user action. An example of an AJAX call sent to the server-side is shown in the following figure:
.dataTables()
In the figure, you can see that CompanyAjaxDataSource is called when information should be reloaded into the table (e.g., when the current page or sort order is changed). UpdateData is called when a cell is edited, DeleteData is called when a row is deleted, and AddData is called when a new record is added. You can also see the parameters that are sent to the server-side when the UpdateData AJAX call is performed. To integrate the plug-in with the server-side code, you will need to create three servlets that will handle add, delete, and update AJAX calls. Examples of the servlets that can handle these AJAX requests are shown in the following listing:
CompanyAjaxDataSource
UpdateData
DeleteData
AddData
@WebServlet("/AddData")
public class AddData extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException { }
}
@WebServlet("/DeleteData")
public class DeleteData extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException { }
}
@WebServlet("/UpdateData")
public class UpdateData extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException { }
}
You will need to implement these classes/methods in order to make the DataTables Editable plug-in functional. The following sections will describe in detail what should be done to implement each of these features.
The starting point is to create a J2EE application that generates a plain HTML table. This example will use a simple JSP page that generates a list of companies in an HTML table. Then, you will need to apply the DataTables plug-in to this table to enable adding basic data table enhancements. This is the second article in the group that describes how you can use jQuery DataTables to enhance your J2EE applications, and it will not explain how you can add the basic DataTables functionalities. The focus of this article will be on the data management functionalities only. If you have not read the previous article jQuery Data Tables and J2EE applications integration, I will recommend that you read that article first because it explains how you can integrate the DataTables plug-in with a J2EE application. This article will assume that the code for the integration of the jQuery DataTables plug-in is implemented, and only the code required for integration of the DataTables Editable plug-in will be explained here.
This section explains the implementation of the following features:
The following sections explain how to implement these features.
As described above, the prerequisite for this code is that you integrate the jQuery DataTable plug-in into the Java application. You can find detailed instructions here: JQuery Data Tables in Java Web Applications, but I will include a short description in this article.
Also, in this article, I will describe the major difference between the standard DataTables integration and integration with DataTables in CRUD mode. If you want to update and delete rows, you need to have some information that tells the plug-in what is the ID of a row. This ID will be sent to the server-side so it can be determined what record should be updated/deleted.
The jQuery DataTables plug-in works in two major modes:
<TBODY>
In the client-side processing mode, the table is generated on the server side (in some JSP page) and the ID of each record should be placed as the ID attribute of the <TR> element. Part of the JSP code that generates this table is shown in the example below:
ID
<TR>
<table id="companies">
<thead>
<tr>
<th>Company name</th>
<th>Address</th>
<th>Town</th>
</tr>
</thead>
<tbody>
<% for(Company c: DataRepository.GetCompanies()){ %>
<tr id="<%=c.getId()%>">
<td><%=c.getName()%></td>
<td><%=c.getAddress()%></td>
<td><%=c.getTown()%></td>
</tr>
<% } %>
</tbody>
</table>
Each time the user edits or deletes some row/cell, the plug-in will take this attribute and send it as an ID.
In the server-side processing mode, only a plain table template is returned as HTML, and it is dynamically populated via an AJAX call when the page is loaded. An example of the plain table template is shown in the following listing:
<table id="companies">
<thead>
<tr>
<th>ID</th>
<th>Company name</th>
<th>Address</th>
<th>Town</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
In this case, nothing is generated in the body of the table and the row will be dynamically loaded by the DataTables plug-in. In this case, the ID of the record is placed in the first column (this column is usually hidden in the DataTables configuration). In the code example that can be downloaded in this article, you can find a table integrated in the server-side processing mode.
For more details about integrating DataTables with a Java web application, see the JQuery Data Tables in Java Web Applications article.
Cell content is edited using the jEditable inline editor, and validation is implemented using the jQuery validation plug-in. Therefore, these scripts should be included in the head section of the HTML page where the editable data table plug-in is used.
The example above shows how data table/editable plug-ins are applied to the table without parameters. In the default mode, each cell in the table is replaced with a text box that can be used for editing. When the user finishes editing, an AJAX request is sent to the server.
Editors applied on the columns can be customized. The following example shows how you can change the URL of the server-side page that will be called when a cell is updated and how you can use different editors in different columns.
$('#myDataTable').dataTable().makeEditable({
"sUpdateURL": "/Company/UpdateCompanyData"
'}"
}
]
});
Each of the elements of the aoColumns array defines an editor that will be used in one of the table columns. In the example above, an empty object is set to the first column, null to the second (to make the second column read-only), and the third column uses a select list for editing.
aoColumns
null
Regardless of what configuration you use, the DataTables Editable plug-in will send the same format of AJAX request to the server-side. The AJAX request sends the following information:
id
<tr>
value
columnName
rowId
columnPosition
columnId
You will also need a servlet that will accept the request described above, receive information sent from the plug-in, update the actual data, and return a response. Servlet code that is used in this example is shown here:
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
//int columnId = Integer.parseInt(request.getParameter("columnId"));
int columnPosition = Integer.parseInt(request.getParameter("columnPosition"));
//int rowId = Integer.parseInt(request.getParameter("rowId"));
String value = request.getParameter("value");
//String columnName = request.getParameter("columnName");
for(Company company: DataRepository.GetCompanies())
{
if(company.getId()==id)
{
switch (columnPosition)
{
case 0:
company.setName(value);
break;
case 1:
company.setAddress(value);
break;
case 2:
company.setTown(value);
break;
default:
break;
}
response.getWriter().print(value);
return;
}
}
response.getWriter().print("Error - company cannot be found");
}
The servlet reads the ID of the record that should be updated, a column that will determine the property of the object that will be updated, and a value that should be set. If nothing is returned, the plug-in will assume that the record was successfully updated on the server-side. Any other message that is returned will be shown as an error message and the updated cell will be reverted to the original value.
The DataTables Editable plug-in enables users to select and delete rows in a table. The first thing you need to do is to place a plain HTML button that will be used for deleting rows somewhere in the form. An example of this button is shown in the following listing:
<button id="btnDeleteRow">Delete selected company</button>
The only thing that is required is to set the ID of the button to the value btnDeleteRow (this ID is used by the DataTables Editable plug-in to add delete handlers to the button). The DataTables Editable plug-in will disable the button initially and when the user select a row in the table, the button will be enabled again. If a row is unselected, the button will be disabled. If the delete button is pressed while a row is selected, the DataTables Editable plug-in will take the ID of the selected row and send an AJAX request to the server side. The AJAX request has a singe parameter, the ID of the record that should be deleted, as shown in the following figure:
btnDeleteRow
The servlet that handles this delete request is shown in the following listing:
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
for(Company c: DataRepository.GetCompanies())
{
if(c.getId()==id)
{
DataRepository.GetCompanies().remove(c);
return;
}
}
response.getWriter().print("Company cannot be found");
}
This servlet takes the ID of the record that should be deleted and removes it from the collection. If nothing is returned, the DataTables Editable plug-in will assume that the delete was successful and the selected row will be removed from the table. Any text that is returned by the servlet will be recognized as an error message, shown to the user, and the delete action will be aborted.
The DataTables Editable initialization call that is used in the example above do not need to have any parameters. However, if you want, you can customize the behavior of the delete functionality as shown in the following example:
$('#myDataTable').dataTable().makeEditable({
sDeleteHttpMethod: "GET",
sDeleteURL: "/Company/DeleteCompany",
sDeleteRowButtonId: "btnDeleteCompany",
});
This call sets the HTTP method that will be used for the AJAX delete call (e.g., "POST", "GET", "DELETE"), the URL that will be called, and the ID of the button that should be used for delete (this is useful if you do not want to put a default ID for the delete button or if you have two delete buttons for two tables on the same page, as in the example on the live demo site).
To enable adding new records, you will need to add a few items on the client side. In the DataTables Editable plug-in, new rows are added using a custom dialog that you will need to define. This dialog is shown in the following figure:
The form for adding new records will always be custom because it will depend on the fields you want to enter while you are adding, the type of elements you want to use for entering data (text boxes, select lists, check boxes, etc.), the required fields, and design. Therefore I have left it to you to define what form should be used for adding new records. However, it is not a complex task because the only things you would need to add are plain HTML buttons for adding new records, and a plain empty form that will be used as the template for adding new records. An example of plain HTML elements that are added in this example is shown in the following listing:
<button id="btnAddNewRow">Add new company...</button>
/>
<button id="btnAddNewRowOk">Add</button>
<button id="btnAddNewRowCancel">Cancel</button>
</form>
Similar to the delete functionality, there should be placed a button that will be used for adding new records - this button should have the ID "btnAddNewRow". The form for adding new records should have the ID "formAddNewRow" and should have OK and Cancel buttons with IDs "btnAddNewRowOk" and "btnAddNewRowCancel". The DataTables Editable plug-in will find the add new row button by ID, attach the event handler for opening the form in the dialog, and attach event handlers for submitting and canceling adding new records to the OK and Cancel buttons. You can place any input field in the form - all values that are entered in the form will be posted to the server. The AJAX call that will be sent to the server-side is shown in the figure below:
btnAddNewRow
formAddNewRow
btnAddNewRowOk
btnAddNewRowCancel
You can see that all values of the input fields are sent to the server-side. On the server side, you need to have a servlet that handles this AJAX call and adds a new record. The code for the servlet method that handles the AJAX call is shown in the following listing:
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name");
String address = request.getParameter("address");
String town = request.getParameter("town");
int country = Integer.parseInt(request.getParameter("country"));
Company c = new Company(name, address, town, country);
DataRepository.GetCompanies().add(c);
response.getWriter().print(c.getId());
}
This code takes parameters sent in the AJAX call, and creates and adds a new company record. The method must return the ID of the new record because the plug-in will set this value as the ID of the added row in the table.
When the AJAX call is finished, the DataTables Editable plug-in adds a new row to the table. Values that are added in the table columns are mapped using the rel attributes in the form elements. You can see that the elements id, Name, Address, and Town have rel attributes 0, 1, 2, and 3 - these values will be used to map the new record to the columns in the table.
rel
Name
Address
Town
Similar to the previous cases, adding a behavior can be configured via parameters passed to the makeEditable() function. An example is shown in the following listing:
makeEditable()
$('",
sAddURL: "/Company/AddNewCompany",
sAddHttpMethod: "POST",
});
In this example, we change the default IDs of the form for adding a new record, the Add button, OK/Cancel buttons used in the add new record pop-up, URL that will be called when a new row should be added, and the HTTP method that should be used in the AJAX call.
This article described how you can create a fully featured client side web table that enables the client to perform all important data management actions (creating new records, deleting records, editing cells inline etc.). You can integrate this client-side code with a Java web application that will accept AJAX calls from the client side.
I believe that this article can help you create effective user interfaces using jQuery plug-ins.
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
$(document).ready(function () {
$.ajaxSetup({ scriptCharset: "utf-8" , contentType: "application/json; charset=utf-8", cache: false });
var anOpen = [];
var sImageUrl = "";
oTable = $('#example').dataTable( {
"bProcessing": true,
"sPaginationType": "full_numbers",
"bJQueryUI": true,
"sAjaxSource": "",
"aoColumns": [
{
"mDataProp": null,
"sClass": "control center",
"sDefaultContent": '<img src="" alt="" />'
},
{ "mDataProp": "HOT_CODCOBOL" },
{ "mDataProp": "HOT_NOMBRE" },
{ "mDataProp": "POBNOM" },
{ "mDataProp": "NOMPROV" },
{ "mDataProp": "AFILIACION" },
{ "mDataProp": "PROVEEDOR" },
{ "mDataProp": "PRIORIDAD" }
]
} ).makeEditable({
sUpdateURL: "",
"aoColumns": [
null,
null,
null,
null,
null,
null,
null,
{
//para poner que sea editable este campo.
}
]
});
$('>DIRECCION:</td><td>'+oData.DIRECCION+'</td></tr>'+
'<tr><td>CODIGO POSTAL:</td><td>'+oData.CODIGOPOSTAL+'</td></tr>'+
'<tr><td>FAX:</td><td>'+oData.FAX+'</td></tr>'+
'<tr><td>PAIS:</td><td>'+oData.PAIS+'</td></tr>'+
'<tr><td>TELEFONO:</td><td>'+oData.TELEFONO+'</td></tr>'+
'<tr><td>DESCRIPCION:</td><td>'+oData.DESCRIPCION+'</td></tr>'+
'</table>'+
'</div>';
return sOut;
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("entra DOPOST ");
String id = request.getParameter("id");
String value = request.getParameter("value");
String columnName = request.getParameter("columnName");
String columnId = request.getParameter("columnId");
String columnPosition = request.getParameter("columnPosition");
String type = request.getParameter("type");
System.out.println("valor de id: "+type);
response.getWriter().print("Error - no funciona");
}
<form id="formulariop">
<div style="margin-top: 20px;vertical-align: center">
<table cellpadding="0" cellspacing="0" border="0" class="display" id="example">
<thead>
<tr>
<th></th>
<th>COBOL</th>
<th>NOMBRE</th>
<th>POBLACION</th>
<th>PROV.</th>
<th>AFILIACION</th>
<th>PROVEEDOR</th>
<th>PRIORIDAD</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</form>
General News Suggestion Question Bug Answer Joke Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | http://www.codeproject.com/Articles/193068/Adding-data-management-CRUD-functionalities-to-the?PageFlow=FixedWidth | CC-MAIN-2014-35 | en | refinedweb |
Created on 2013-09-06 09:00 by arigo, last changed 2019-08-30 07:30 by rhettinger.
In argparse, default arguments have a strange behavior that shows up in mutually exclusive groups: specifying explicitly on the command-line an argument, but giving it its default value, is sometimes equivalent to not specifying the argument at all, and sometimes not.
See the attached test diff: it contains two apparently equivalent pieces of code, but one passes and one fails. The difference is that, in CPython, int("42") is 42 but int("4200") is not 4200 (in the sense of the operator "is").
The line that uses "is" in this way is this line in argparse.py (line 1783 in 2.7 head):
if argument_values is not action.default:
The patch isn't a good unittest case because it produces an Error, not a Failure. It does, though, raise a valid question about how a Mutually_exclusive_group tests for the use of its arguments.
As you note, argparse does use the `is` test: `argument_values is not action.default`. argument_values is the result of passing an argument_string through its 'type' function.
This reworks your test case a bit:
group = parser.add_mutually_exclusive_group()
group.add_argument('--foo', default='test')
group.add_argument('--bar', type=int, default=256)
group.add_argument('--baz', type=int, default=257)
'--foo test --baz 257' will give the `argument --foo: not allowed with argument --baz` error message, but '--foo test --baz 256' does not.
So which is right? Should it complain because 2 exclusive arguments are being used? Or should it be excused from complaining because the values match their defaults?
The other issue is whether the values really match the defaults or not. With an `is` test, the `id`s must match. The ids for small integers match all the time, while ones >256 differ.
Strings might have the same id or not, depending on how they are created. If I create `x='test'`, and `y='--foo test'.split()[1]`. `x==y` is True, but `x is y` is False. So '--foo test' argument_value does not match the 'foo.default'.
So large integers (>256) behave like strings when used as defaults in this situation. It's the small integers that have unique ids, and hence don't trigger mutually_exclusive_group errors when they should.
This mutually_exclusive_group 'is' test might not be ideal (free from all ambiguities), but I'm not sure it needs to be changed. Maybe there needs to be a warning in the docs about mutually_exclusive_groups and defaults other than None.
A further complication on this. With the arguments I defined in the previous post
p.parse_args('--foo test --baz 257'.split())
gives the mutually exclusive error message. `sys.argv` does the same.
p.parse_args(['--foo', 'test', '--baz', '257'])
does not give an error, because here the 'test' argument string is the same as the default 'test'. So the m_x_g test thinks `--foo' is the default, and does not count as an input.
Usually in testing an argparse setup I use the list and split arguments interchangeably, but this shows they are not equivalent.
Getting consistently one behavior or the other would be much better imho; I think it's wrong-ish to have the behavior depend uncontrollably on implementation details. But I agree that it's slightly messy to declare which of the two possible fixes is the "right" one. I'm slightly in favor of the more permissive solution ("--bar 42" equivalent to no arguments at all if 42 is the default) only because the other solution might break someone's existing code. If I had no such backward-compatibility issue in mind, I'd vote for the other solution (you can't specify "--bar" with any value, because you already specified "--foo").
> The patch isn't a good unittest case because it produces an Error, not
> a Failure.
Please let's not be pedantic about what a "good unittest" is.
Changing the test from
if argument_values is not action.default:
to
if argument_values is not action.default and \
(action.default is None or argument_values != action.default):
makes the behavior more consistent. Strings and large ints behave like small ints, matching the default and not counting as "present"
Simply using `argument_values != action.default` was not sufficient, since it raised errors in existing test cases (such as ones involving Nones).
A possibly unintended consequence to this `seen_non_default_actions` testing is that default values do not qualify as 'present' when testing for a required mutually exclusive group.
p=argparse.ArgumentParser()
g=p.add_mutually_exclusive_group(required=True)
g.add_argument('--foo',default='test')
g.add_argument('--bar',type=int,default=42)
p.parse_args('--bar 42'.split())
raises an `error: one of the arguments --foo --bar is required`
In the original code
p.parse_args('--foo test'.split())
does not raise an error because 'test' does not qualify as default. But with the change I proposed, it does raise the error.
This issue may require adding a `failures_when_required` category to the test_argparse.py MEMixin class. Currently nothing in test_argparse.py tests for this issue.
Note that this contrasts with the handling of ordinarily required arguments.
p.add_argument('--baz',type=int,default=42,required=True)
'--baz 42' does not raise an error. It is 'present' regardless of whether its value matches the default or not.
This argues against tightening the `seen_non_default_actions` test. Because the current testing only catches a few defaults (None and small ints) it is likely that no user has come across the required group issue. There might actually be fewer compatibility issues if we simply drop the default test (or limit it to the case where the default=None).
I should add that defaults with required arguments (or groups?) doesn't make much sense. Still there's nothing in the code that prevents it.
Fwiw I agree with you :-) I'm just relaying a bug report that originates on PyPy ().
This `argument_values` comes from `_get_values()`. Most of the time is derived from the `argument_strings`. But in a few cases it is set to `action.default`, specifically when the action is an optional postional with an empty `argument_strings`.
test_argparse.TestMutuallyExclusiveOptionalAndPositional is such a case. `badger` is an optional positional in a mutually exclusive group. As such it can be 'present' without really being there (tricky). Positionals are always processed - otherwise it raises an error.
If this is the case, what we need is a more reliable way of knowing whether `_get_values()` is doing this, one that isn't fooled by this small int caching.
We could rewrite the `is not` test as:
if not argument_strings and action.nargs in ['*','?'] and argument_values is action.default:
pass # _get_values() has set: argument_values=action.default
else:
seen_non_default_actions.add(action)
...
is a little better, but still feels like a kludge. Having `_get_values` return a flag that says "I am actually returning action.default" would be clearer, but, I think, too big of a change.
At the very least the `is not action.default` needs to be changed. Else where in argparse `is` is only used with `None` or constant like `SUPPRESS`. So using it with a user defined parameter is definitely not a good idea.
Possible variations on how `is` behaves across implementations (pypy, ironpython) only complicates the issue. I'm also familiar with a Javascript translation of argparse (that uses its `!==` in this context).
This patch uses a narrow criteria - if `_get_values()` sets the value to `action.default`, then argument counts as 'not present'. I am setting a `using_default` flag in `_get_values`, and return it for use by `take_action`.
In effect, the only change from previous behavior is that small ints (<257) now behave like large ints, strings and other objects.
It removes the nonstandard 'is not action.default' test, and should behave consistently across all platforms (including pypy).
The patch looks good to me. It may break existing code, though, as reported on. I would say that it should only go to trunk. We can always fix PyPy (at Python 2.7) in a custom manner, in a "bug-to-bug" compatibility mode.
This patch corrects the handling of `seen_non_default_action` in another case - a positional with '?' and `type=int` (or other conversion).
if
parser.add_argument('badger', type=int, nargs='?', default=2) # or '2'
and the original test 'seen_non_default_actions' is:
if argument_values is not action.default
'argument_values' will be an 'int' regardless of the default. But it will pass the 'is' test with the (small) int default but not the string default.
With the patch proposed here, both defaults behave the same - 'badger' will not appear in 'seen_non_default_actions' if it did not occur in the argument_strings (i.e. match an empty string).
I may add case like this to `test_argparse.py` for this patch.
I need to tweak the last patch so 'using_default' is also set when an "nargs='*'" positional is set to the '[]' default.
if action.default is not None:
value = action.default
+ using_default = True
else:
value = arg_strings
+ using_default = True # tweak
This came up again,
An optional with int type and small integer default.
paul, will you work on this patch? or I can help this issue, too.
I haven't downloaded the development distribution to this computer, so can't write formal patches at this time.
Another manifestation of the complications in handling '?' positionals is in
argparse: successive parsing wipes out nargs=? values
Any progress with this? I believe it would fix my use case:
```
import argparse
import pprint
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--device-get-capabilities',
action='store_true',
help='Execute GetCapabilities action from ONVIF devicemgmt.wsdl')
group.add_argument('--ptz-absolute-move',
nargs=3,
metavar=('x', 'y', 'z'),
help='Execute AbsoluteMove action from ONVIF ptz.wsdl')
group.add_argument('--ptz-get-status',
metavar='MEDIA_PROFILE',
default='MediaProfile000',
help='Execute GetSatus action from ONVIF ptz.wsdl for a media profile (default=%(default)s)')
pprint.pprint(parser.parse_args(['--ptz-get-status']))
```
Outputs (using 3.6.3):
```
python3 ./test-ex-group-with-defult.py
usage: test-ex-group-with-defult.py [-h]
(--device-get-capabilities | --ptz-absolute-move x y z | --ptz-get-status MEDIA_PROFILE)
test-ex-group-with-defult.py: error: argument --ptz-get-status: expected one argument
```
Are there know workarounds for this?
Did you copy the output right? Testing your parser:
Without any arguments, I get the exclusive group error - the group is required:
0930:~/mypy/argdev$ python3 issue18943.py
usage: issue18943.py [-h]
(--device-get-capabilities | --ptz-absolute-move x y z | --ptz-get-status MEDIA_PROFILE)
issue18943.py: error: one of the arguments --device-get-capabilities --ptz-absolute-move --ptz-get-status is required
0931:~/mypy/argdev$ python3 --version
Python 3.5.2
On 2017-12-06 19:43, paul j3 wrote:
>
In my example I pasted, I had hardcoded arguments:
```
pprint.pprint(parser.parse_args(['--ptz-get-status']))
``
I expected `python myscript.py --ptz-get-status` to work, because default value is set.
I do not compute that "With one flag but not its argument", sorry. It has default argument set, shoudn't that work?
Thanks!
That's not how flagged (optionals) arguments work.
The default value is used if the flag is not provided at all. One of your arguments is a 'store_true'. Its default value if False, which is changed to True if the '--device-get-capabilities' flag is provided.
"nargs='?'" provides a third option, assigning the 'const' value if the flag is used without an argument.
In any case your problem isn't with a required mutually exclusive group (defaults or not). It has to do with understanding optionals and their defaults.
On 2017-12-06 20:28, paul j3 wrote:
> The default value is used *if the flag is not provided at all.*
>
> "nargs='?'" provides a third option, assigning the 'const' value *if the flag is used without an argument*.
This did a "click" in my head. It works now with `nargs='?'` and `const='MediaProfile000'` as expected, thanks!
I am really sorry for the noise, due to misunderstanding while reading (skipping-throuhg?) Python documentation. | https://bugs.python.org/issue18943 | CC-MAIN-2020-50 | en | refinedweb |
Sales and use taxes
Taxable goods
What goods are subject to sales and use tax in your state (at both state and local level)?
Illinois and its localities impose tax on the occupation of selling at retail tangible personal property and on the use of tangible personal property purchased from a retailer (see, e.g., 35 ILCS 120/2; 35 ILCS 105/3; 65 ILCS 5/8-11-1 (Home Rule Municipal Retailers’ Occupation Tax Act); 65 ILCS 5/8-11-6 (Home Rule Municipal Use Tax Act)). Additionally, sales and use tax is imposed on tangible personal property acquired as an incident to the sale of a service (see, e.g., 35 ILCS 115/3; 35 ILCS 110/3; 65 ILCS 5/8-11-5 (Home Rule Municipal Service Occupation Tax Act)).
State rate
What is the state sales tax rate?
The state sales tax rate is 6.25% on sales of tangible personal property other than sales of some food (generally grocery food items), drugs, and medical appliances, which are taxed at 1% (35 ILCS 120/2-10).
Local rates
What is the range of local sales tax rates levied in your state?
Local sales tax rates generally range from 0.1% to 2.5%, depending on the taxing jurisdiction. See ST-62 (R-01/18) for a list of local sales tax rates administered by the Department of Revenue. See also the Tax Rate Database on the Department of Revenue’s website to find local sales tax rates by location.
Exemptions
What goods are exempt from sales and use tax?
Generally, sales and use tax is imposed on retail sales of tangible personal property. In order for goods to be tax exempt, they must qualify for a specific exemption. For example, Illinois exempts from sales and use tax certain items of machinery, equipment, personal property, and vehicles (see, e.g., 35 ILCS 120/2-5 & 35 ILCS 105/3-5 (listing exemptions); see also 86 Ill. Admin. Code § 150.301 (sales tax exemptions apply to use tax)).
Services
Are any services taxed?
Pure services are not taxed in Illinois. Under the service occupation and use taxes, tangible personal property transferred incident to sales of service from servicemen is taxed (see, e.g., 35 ILCS 115/3; 35 ILCS 110/3).
Filing requirements
What filing requirements and procedures apply?
In general, retailers making taxable sales in Illinois must file with the Illinois Department of Revenue a sales and use tax return (ST-1) on a monthly basis (see 35 ILCS 120/3). The preceding month’s return is due by the 20th of the following month (35 ILCS 120/3). The Department of Revenue’s sales and use tax forms and instructions are available at. Retailers making sales for resale must collect and maintain certificates of resale from their buyers to support the conclusion that tax was not owed on the sale. Charitable organizations must obtain certificates of sales tax exemption from the state and supply a copy of the certificate to their retailers in order to avoid sales tax. | https://www.lexology.com/library/detail.aspx?g=9ac48e9a-8701-45e9-af64-65f83d2311de | CC-MAIN-2020-50 | en | refinedweb |
DateTimePicker control¶
This control allows you to select dates from a calendar and optionally the time of day using dropdown controls. You can configure the control to use 12 or 24-hour clock.
Here are some examples of the control:
DateTime Picker 12-hour clock
DateTime Picker 24-hour clock
DateTime Picker Date Only
DateTime Picker No Seconds
DateTime Picker Dropdowns for Time Part
How to use this control in your solutions¶
- Check that you installed the
@pnp/spfx-controls-reactdependency. Check out the getting started page for more information about installing the dependency.
- Import the control into your component. The DateConvention and TimeConvention controls if the time of day controls are shown and the time format used (12 hours/24 hours).
import { DateTimePicker, DateConvention, TimeConvention } from '@pnp/spfx-controls-react/lib/dateTimePicker';
- Use the
DateTimePickercontrol in your code as follows, either as an uncontrolled or a controlled component:
// Uncontrolled <DateTimePicker label="DateTime Picker - 12h" dateConvention={DateConvention.DateTime} timeConvention={TimeConvention.Hours12} /> // Controlled <DateTimePicker label="DateTime Picker - 24h" dateConvention={DateConvention.DateTime} timeConvention={TimeConvention.Hours24} value={this.state.date} onChange={this.handleChange} />
Implementation¶
The
DateTimePicker control can be configured with the following properties:
Enum
TimeDisplayControlType
Enum
DateConvention
Enum
TimeConvention
Interface
IDateTimePickerStrings extends IDatePickerStrings | https://pnp.github.io/sp-dev-fx-controls-react/controls/DateTimePicker/ | CC-MAIN-2020-50 | en | refinedweb |
Filer access on macOS
You can choose between two ways of accessing the departmental filer:
- NFSv3 protocol – Behaves like lab-managed Unix/Linux. Files created will have Unix/POSIX-style access control permissions (see “man chmod”), symbolic links are fully supported, and the protocol is very fast, especially on LANs. This option is in particular much preferable for anyone who mostly collaborates with Unix/Linux users, or who uses their Mac commonly from the shell command-line.
- SMB 2/3 protocol – Behaves much like access from Windows, in particular most files you create will be managed by the filer using Windows NTFS-style access controls. Symbolic links created under Unix/Linux will not be recognizeable as such, but mandatory locking is available. This was the only protocol supported in our previous filer “elmer”, but since the October 2019 migration to a new filer “wilbur”, this is now the less recommended option.
For both forms of access, your computer either needs to be connected to an appropriate subnet within the William Gates Building (e.g., the “Internal-CL” wifi or one of the wired connections for lab-managed machines), or you need to set up and connect the Computer Laboratory VPN.
You will also need a valid departmental Kerberos login, i.e. the same password as for using lab-managed Linux or Windows machines in the DC.CL.CAM.AC.UK Active Directory domain.
Preventing the creation of .DS_Store files
Before accessing the filer for the first time from macOS, please perform the following step.
Users of the macOS Finder application who browse filer directories where they have communal write access risk becoming a nuisance to other users because Finder litters every folder it visits with a .DS_Store file (to store custom attributes of the folder such as the position of icons, etc.)
To disable the creation of these nuisance files on remote file servers by your NFS/SMB/WebDAV client, execute the following command in Terminal:
$ defaults write com.apple.desktopservices DSDontWriteNetworkStores true
This is also likely to speed up the display of folders in Finder.
See also:
Access via NFS
You need macOS Sierra (10.12) or newer.
Configuring LDAP
The following instructions are for Macs that have not yet already been joined to an Active Directory domain. If you find that your Mac shows in the second step below next to “Network Account Server:” an Active Directory domain and a green bullet, better contact Markus Kuhn for advice first.
To help macOS Directory Services receive the departmental automount tables, as well as the tables for mapping between numeric user and group identifiers and the corresponding names, you have to configure it with the “Open Directory Utility” to connect to a departmental Unix LDAP server:
- Under '(Apple)|System Preferences|Users & Groups' click on 'Login Options'. Then click the padlock symbol and unlock it with your admin password. (You may later be asked for that admin password a few more times.)
- Next to 'Network Account Server:' click 'Join...' and then on the menu that pops up click the button 'Open Directory Utility...'.
- In the Directory Utility, again open the padlock using your admin password. Under 'Services', double-click 'LDAPv3'; on the menu that opens, click 'Show Options' and then 'New...'.
- In the 'New LDAP Connection' menu that pops up, set 'Server Name or IP Address:' to 'ldap-serv1.cl.cam.ac.uk'. Among the options underneath, make sure that 'Use for authentication' is ticked. Then click 'Continue'.
- Back on the list of options, for the server you just added, set 'LDAP Mappings' to 'RFC2307'. You will then be prompted for 'Search Base Suffix' and should enter enter 'dc=cl,dc=cam,dc=ac,dc=uk'. The screen should then look like the screnshot below. Then press 'OK'.
Back in the Directory Utility main window you can check whether under 'Search policy' and 'Authentication' it now says 'Custom path' and has under '/Local/Default' the second directory domain '/LDAPv3/ldap-serv1.cl.cam.ac.uk' added. If not, click '+' to add it, then press 'Apply'. Close the Directory Utility main window
Once you have succeeded, the little bullet in front of 'ldap-serv1.cl.cam.ac.uk' on the 'Users & Groups' tool 'Login Options' menu will have changed from grey to green.
One more thing: setting up an LDAP connection on a laptop may cause some startup delays if the LDAP server is not reachable. You can configure timeouts in the Open Directory Utility (under Services | LDAPv3 | ldap-serv1.cl.cam.ac.uk | Edit... | Connection):
Reduce the first two timeouts to e.g. 3 seconds.
Command-line configuration
Alternatively, on macOS version prior to Catalina, you could also run (as root) the commands
$ sudo bash # dsconfigldap -a ldap-serv1.cl.cam.ac.uk # cd /Library/Preferences/OpenDirectory/Configurations/LDAPv3/ # curl -O # killall opendirectoryd
To remove the configuration again, you can use
# dsconfigldap -r ldap-serv1.cl.cam.ac.uk
(Since Catalina, the folder /Library/Preferences/OpenDirectory/Configurations/LDAPv3/ has no longer been writeable, even for root. This currently leaves a fully-scripted LDAP configuration on macOS Catalina an open problem.)
Automount symlinks
Configuring LDAP will (after reboot and kinit) result in the appearance of new directories /auto/homes, /auto/groups, /auto/userfiles, /auto/anfs, and /Nfs/Mounts in your local filesystem.
On lab-managed Linux machines, these are (for historic reasons) usually still accessed via these five symbolic links:
/homes -> /auto/homes /anfs -> /auto/anfs /a -> /Nfs/Mounts /global -> /anfs/glob /usr/groups -> /auto/groups
Before macOS 10.15 “Catalina”, you could create these with
ln -s /auto/homes /homes ln -s /auto/anfs /anfs ln -s /Nfs/Mounts /a ln -s /anfs/glob /global ls -s /auto/groups /usr/groups
However, Apple's System Integrity Protection policy (introduced with macOS El Capitan) prevented you already from creating the fifth symbolic link at /usr/groups. So on Macs you will have to access /auto/groups directly, instead of via the traditional /usr/groups prefix.
On macOS Catalina (or newer), instead of creating the above symbolic links, use these commands to create equivalent “synthetic firmlinks” (see “man synthetic.conf”):
$ sudo bash # curl -o /etc/synthetic.conf # reboot
Testing your NFS access
After the reboot (and if you are outside the department: reconnecting the CL VPN), you should now be able to
$ kinit your-crsid@DC.CL.CAM.AC.UK your-crsid@DC.CL.CAM.AC.UK's password: your-departmental-password $ ls -l /anfs/www/tools total 12 drwxrwsr-x 3 mgk25 wwwpages 4096 Sep 29 14:26 bin drwxrwsr-x 9 mgk25 wwwpages 4096 Oct 6 09:22 share drwxrwsr-x 4 mgk25 wwwpages 4096 Sep 26 2019 windows
The Kerberos ticket you get with “kinit” lasts for 10 hours or until you log out. After that you need to run “kinit” again. You can check the expiry time of your ticket with “klist”.
If you ever get “permission denied” errors with NFS, first of all try another “kinit”.
A note for older users: If you haven't reset your departmental Kerberos password in the past decade (since the departmental Active Directory server was upgraded to Windows Server 2008), then you may have to reset your password first before it will work on macOS, otherwise our Kerberos Server will not yet have had a chance to store an AES-compatible hash of your password.
Wishlist
- The departmental LDAP server should support either Kerberos or TLS encryption and authentication, so it can't be impersonated by a hostile network.
- LDAP on a laptop may also pose security risks on untrusted networks as long as we do not support and require TLS or Kerberos encryption and authentication of the LDAP connection. Therefore the LDAP setup is at the moment mainly recommended for stationary macOS machines located in the department.
- For historic reasons, our Unix LDAP server still defines a number of UID and GID values below 1000, although these are today reserved for use by the client operating system. Where local and LDAP UIDs/GIDs overlap, they may be displayed incorrectly in commands like “id” or “ls -l”.
- The filer namespace should be redesigned. Two goals might be:
- phase out /usr/groups/
- make the paths look the same as under Windows and Unix (e.g., /auto vs. \\filer), except for the slashes.
- Phase out the need to create five symlinks on the root partition.
References
- Mac OS X Server – Open Directory Administration
Appendix B explains what the OS X Directory Service expects to find in an LDAP server.
- Autofs: Automatically Mounting Network File Shares in Mac OS X. Technical White Paper, Apple, June 2009
Access via SMB
To mount an SMB share, you first need to make sure that you have obtained a Kerberos ticket with “kinit [Javascript required]” (same as for NFS access).
Then start “Finder” and select the menu item “Go | Connect to Server ...” and type in as the “Server Address:” the required smb:// path that you want to mount.
Example mount points that currently work (this can change in the near future):
- To mount your superhome (contains contains your unix_home and windows_home):
smb://wilbur.cl.cam.ac.uk/userfiles/CRSid
- To mount your group space
smb://wilbur.cl.cam.ac.uk/groups/groupname
- To mount webserver related filespaces (/auto/anfs/www* on NFS)
smb://wilbur.cl.cam.ac.uk/webserver/
If you get a GUI password prompt as below, click “Cancel” and use “kinit” instead:
The previously recommended path smb://CRSid@filer.cl.cam.ac.uk/ is now served by a DFS server. It appears that DFS redirecting currently does fully work on macOS (e.g. mounting smb://filer.cl.cam.ac.uk/groups/security works, but mounting smb://filer.cl.cam.ac.uk/groups mounts a folder that contains empty folders such as security). It appears that macOS follows DFS redirects on the initial mount, but does not deal with them when an application such as Finder later encounters a DSF redirect while traversing the mounted filesystem.
See also: | https://www.cl.cam.ac.uk/local/sys/filesystems/mac/ | CC-MAIN-2020-50 | en | refinedweb |
James_R_Green
14-08-2017
I am working with a client to create an alternative means to update XDP files as opposed to updating them within Workbench/Form Designer.
I am specifically interested in the exdata section:
<exData contentType="text/html" xliff:
<body xmlns="" xmlns:
<p style="letter-spacing:0in">Text1</p>
<p style="letter-spacing:0in">Text2</p>
</body>
</exData>
Although I can see that the content within the exData section is effectively html with inline styles, I want to ensure that we keep inline with the specification.
Is there any documentation for the XDP file format? Is the contents of the section (as the namespace suggests) fully xhtml compliant? | https://experienceleaguecommunities.adobe.com/t5/adobe-experience-manager-forms/xdp-file-specification/m-p/291814/highlight/true | CC-MAIN-2020-50 | en | refinedweb |
.
At the end of the sales process, the employee closes the case either marked as “successful” or “unsuccessful”. In a successful, case a new case for the internal division which will work on the project will be created. All that data is stored inside a Data Warehouse and can be used for reports and further analysis. To train and test the machine learning algorithms the closed sales cases were used.
To find out whether a sales case will be closed as successful or not, the features of the cases need to be analysed. Therefore, the following features were exported for every sales case:
- Lifetime: The time between the creation date of the case and the date when it was closed or the current date, if the case is still open
Activity: This simply counts the amount of communication with the customer of any kind, like phone calls, mails and meetings.
Activity per time: While activity counts the communication over the whole lifetime of a case, the activity per time indicates how many communications there have been within a week.
Customer status: Whether the potential customer is a new customer or an existing one.
Division: The division inside the company, which would work on the project.
Origin: Gives information where the opportunity is coming from, for example an already known customer, an event or a request for proposals.
Sales volume
sales volume for licenses
proportional marketing costs
All these features were exported from the Data Warehouse as csv and then processed with Python. Therefore, a Jupyter Notebook was used. These notebooks are very flexible since they can run on your local machine or they can even connect to a Hadoop cluster, using PySpark, where they can be used by several users via the WebUI.
A first step is to search for clusters within the given data, in this example the already closed sales cases. Using K-Means, it is possible to find out if a certain combination of features more likely leads to a successful closing of the sales case.
For that approach, the K – Means algorithm is a good option. It is an unsupervised machine learning algorithm that needs no labels. It finds k clusters within the data, where k is a number of your choice. The algorithm starts with k randomly picked data points and chooses them as the centers for the k clusters. Then, all other data points are assigned to the cluster where the center is nearest to them. In the next step for the now existing clusters the centers are newly calculated. Then again, every data point is assigned to the cluster with the nearest center. This procedure goes on until the centers don’t really change their positions anymore.
The K - Means algorithm is already included in the python package “sklearn”. Further information can be found at the scikit-learn documentation.
But it is also no big deal to implement that algorithm yourself. If your data is stored in a Hadoop cluster, you can connect the Jupyter Notebook to Spark and use the following PySpark code to run the algorithm on the cluster:
import numpy as np def closestPoint(p, centers): bestIndex = 0 closest = float("+inf") for i in range(len(centers)): Dist = np.sum((p - centers[i]) ** 2) if Dist < closest: closest = Dist bestIndex = i return bestIndex data = ... K = 3 convergeDist = 0.1 kPoints = data.takeSample(False, K, 1) Dist = 1.0 while Dist > convergeDist: closest = data.map(lambda p: (closestPoint(p, kPoints), (p, 1))) pointStats = closest.reduceByKey(lambda p1, p2: (p1[0] + p2[0], p1[1] + p2[1])) newPoints = pointStats.map(lambda st: (st[0], st[1][0] / st[1][1])).collect() Dist = sum(np.sum((kPoints[i] - p) ** 2) for (i, p) in newPoints) for (i, p) in newPoints: kPoints[i] = p
This snippet calculates the final coordinates for the centers for each cluster. In the end each data point has to be assigned to its closest center which can easily be done with the function “closestPoint”.
So far, no prediction for the open sales cases has been generated. For that purpose, a supervised machine learning algorithm is used. A more simple one is the decision tree algorithm. The decision tree algorithm splits the data into groups at every branch until the final decision is made. The paths from root to leaf represent classification rules. This tree-like structure can be plotted as seen in the example picture below.
Supervised algorithms generate knowledge based on training data, here the already closed sales cases were used for that purpose. After the training phase the model needs to be tested. Therefore 20 percent of the closed sales cases were used, while the other 80 percent were training data. A good choice is to split the data with a random component.
df['is_train'] = np.random.uniform(0, 1, len(df)) <= .8 train, test = df[df['is_train']==True], df[df['is_train']==False]
For the decision tree it is possible to visualize the decisions as seen above. This is a good way to get a first impression of the data. In the next step, the random forest algorithm was used because it is more reliable. Random forest consists of several uncorrelated decision trees, where every tree had grown with a random component during its learning process. The features are always randomly permuted at each split. In default, random forest grows 10 trees. This can be changed with the variable n_estimators. For the final classification of the data every tree has a vote. The class with most votes will be the one assigned to the data. This algorithm has many advantages:
In Python it’s quite simple to use that algorithm.
import sklearn from sklearn.ensemble import RandomForestClassifier data = ... features = df.columns[:9] clf = RandomForestClassifier(n_jobs=2, random_state=0) clf.fit(train[features], train['success']) clf.predict(test[features])[0:10]
To evaluate the prediction on the test data you can create a confusion matrix.
M=pd.crosstab(test['success'], clf.predict(test[features]), rownames=['Actual success'], colnames=['Predicted success'])
The random forest algorithm gives you also the ability to view a list of the features and their importance scores.
sorted(list(zip(train[features], clf.feature_importances_)),key=itemgetter(1), reverse=True)
Finally, the algorithm was used on the open sales cases to predict their success.
It turns out that multiple features are important to predict the success of an open sales case. And of course the right balance between these features makes a sales opportunity successful.
The most important features are:
The results can be integrated in the existing reporting by pushing them back as a table into the Data Warehouse.
Analysing data from ConSol CM with Machine Learning algorithms can also be used to optimise complaint management, for fraud detection, to cluster customers into groups and many more. | https://labs.consol.de/de/consol-cm/big-data/2018/04/20/machine-learning-and-consol-cm.html | CC-MAIN-2020-50 | en | refinedweb |
Important: Please read the Qt Code of Conduct -
Embed PyQt in C++/C
Hi, I have written a PyQT application in PyQt5. I now need to embed that in a C/C++ application. I see how to embed Python in C/C++ but I do not know how I can make sure the PyQt5 widgets are also available when run inside a C/C++.
Some of the PyQt5 widgets I have used:
from PyQt5.QtWidgets import QApplication, QFrame, QGridLayout, QHBoxLayout, QPushButton, QSizePolicy, QSpacerItem,QToolButton, QVBoxLayout, QWidget, QTextEdit
How do I make sure these PyQt5 objects are there inside C/C++ when I embed?
Any help much appreciated. Thanks!
Have a look at PythonQT | https://forum.qt.io/topic/96088/embed-pyqt-in-c-c/2 | CC-MAIN-2020-50 | en | refinedweb |
How to Draw Pixel Art on Python with Turtle!
In this Tutorial you shall learn how to create your own pixel art on Python with Turtle, I hope you enjoy.
The first step to creating our art is to import turtle and set a background. My personal tip is to use black as it works best with pixel art.
Here is model code:
import turtle t=turtle.Turtle() wn=turtle.Screen() wn.bgcolor("Black") #Remember Speech Marks.
Then, for step 2, we will set the speed of your turtle to be a high value, using this command:
t.speed(0)
Then, now the technical aspects are over with, let us get into the real juicy code!
First, we must define square. My optimum size after a lot of testing was a 20 by 20 square. You define a function using this piece of code:
def square(): for x in range(4): t.forward(20) t.right(90) #Remember Indentation.
Then, After that step, we can start making pixel art!
To add colours to our squares, we use the begin_fill command. Let me show an example about how this works.
def Tetris_Piece_1(): for x in range(4): t.begin_fill() square() t.color("Blue") t.end_fill() t.color("Black") t.forward(20)
We created this function. Now we may uses it whenever we like with this command:
Tetris_Piece_1().
This code will make a Horizontal line of 4 pixels, like the Tetris piece! Look at the example below to see Pac-Man also.
You've come to the end of the Tutorial. However, if you would like to extend this, here are some ideas.
Find a way to define Red_Square or Blue_Square.
Make a video-game character.
Create a model of a Tetris screen.
It has lots of uses, so try it today.
Remember to click on Python with Turtle and not python 2.7, Python or Django.
I recommend you watch the example in larger screen by pressing Open in Repl.it.
Special Credit to JSer for teaching me how to use markdown on this post!
Up the pensize to 4 if you want it really blocky using this command!
t.pensize(4)
Nice! I've been having trouble with pixel art. This should take care of it! I've got to make each pixel smaller though.
@DragonLord5646 That's really nice to hear! Making pixels smaller should add a more refined image! I'm glad to know I helped!
@timmy_i_chen Thanks for the advice. I'll fix it up tomorrow though as I'm in the U.K and it's getting late.
This is sick nice job! You get my upvote!
@IEATPYTHON Thanks. I upvoted your Colourful circle generator. That was amazing! It was very complex, and made a very eye-pleasing pattern!
This is really great!
This is amazing! I really like the pacman design!
@ChillBreeze Thanks. The capabilities are large for what you can create with this Code!
Cool Beans!
Nice job!!
@stubaduble He defined a "Tetris Piece". He then executes the command to draw the "Tetris Piece". Code to the "Tetris Piece":
def Tetris_Piece_1() for x in range(4): t.begin_fill() square() t.color("Blue") t.end_fill() t.color("Black") t.forward(20)
To execute the command, he writes
Tetris_Piece_1() in his code.
Good Job John!
@nothplus Thanks!
@John_WardWard John be sure to support my Tutorial if you really liked it!
@Mohanad_Alaas Sure, Done it now.
@John_WardWard John you got discord, if not get it and let me add you
@nothplus Yea , I'm on the repl.it server:)
@John_WardWard Ok John whats your name I need to PM
@nothplus
TheLegendJohnWard
@John_WardWard CHeck it, ur discord and stay active
@John_WardWard Lookin good dude! | https://repl.it/talk/learn/How-to-draw-Pixel-Art-on-Python-with-Turtle/7556 | CC-MAIN-2020-50 | en | refinedweb |
PY-4481 (Bug)
Incorrect hightlighting for the last value of a multi-line dict if not followed by comma
PY-4568 (Bug)
2.0 Hangs
PY-4548 (Bug)
"Fix all 'Single quoted docstring' problems" results in 5 quotes
PY-4478 (Exception)
Quick Definition Lookup: Throwable at com.intellij.openapi.application.impl.ApplicationImpl.assertReadAccessAllowed
PY-3612 (Cosmetics)
Console: strange empty space after enabling Stop button which was grayed out before
PY-1124 (Feature)
Support Smart Step Into in Python debugger
PY-4395 (Bug)
Python docs run configurations: provide visual distinction between sphinx and docutils tasks
PY-4391 (Bug)
Python docs run configurations / sphinx: provide temporary run configuration on Ctrl+Shift+F10 for docs sources directory
PY-4392 (Bug)
Python docs run configurations: messed up slashes for input\output fields
PY-4464 (Bug)
Delete Line command and new line
PY-4398 (Usability Problem)
"Statement seems to have no effect" should handle misplaced docstrings better
PY-4518 (Bug)
'"Default argument value is mutable" inspection is not triggered for a dict constructor
PY-4551 (Bug)
"Remove redundant parenthesis" suggestion yields to mistake
PY-4546 (Exception)
Jinja: java.lang.Error at com.jetbrains.jinja2.lexer._Jinja2FlexLexer.a
PY-4522 (Feature)
Mako: better control structures highlighting
PY-4523 (Bug)
Mako: element not closed: false positive for closing element right after one-line comment
PY-4521 (Bug)
Mako: Element not closed: false negative for doc tag
PY-4526 (Bug)
?????
PY-4524 (Bug)
Mako: do not highlight double number sign as comment once it is not the first non-space characters on a line
PY-4530 (Bug)
Mako: missing resolve for names defined in namespaces
PY-4571 (Bug)
False positive for "Control structure should end with :" if first line is comment
PY-4533 (Exception)
Mako: AIOOBE at com.jetbrains.mako.psi.impl.MakoCall.getName
PY-4534 (Bug)
PyCharm can't find nosetests runner.
PY-4363 (Bug)
Map help button to correct Help reference in Python test Run/Debug configurations | https://confluence.jetbrains.com/plugins/viewsource/viewpagesrc.action?pageId=41487778 | CC-MAIN-2020-50 | en | refinedweb |
ENTRUST (Laravel 5 Package)ENTRUST (Laravel 5 Package)
Entrust is a succinct and flexible way to add Role-based Permissions to Laravel 5.
If you are looking for the Laravel 4 version, take a look Branch 1.0. It contains the latest entrust version for Laravel 4.
ContentsContents
- Installation
- Configuration
- Usage
- Troubleshooting
- License
- Contribution guidelines
- Additional information
InstallationInstallation
In order to install Laravel 5 Entrust, just add
"zizaco/entrust": "5.2.x-dev"
to your composer.json. Then run
composer install or
composer update.
or you can run the
composer require command from your terminal:
composer require zizaco/entrust:5.2.x-dev.
ConfigurationConfigurationUser relation to roles
Now generate the Entrust migration:
php artisan entrust:migration
It will generate the
<timestamp>_entrust_setup_tables.php migration.
You may now run it with the artisan migrate command:
php artisan migrate
After the migration, four new tables will be present:
roles— stores role records
permissions— stores permission records
role_user— stores many-to-many relations between roles and users
permission_role— stores many-to-many relations between roles and permissions
ModelsModels
RoleRole
Create a Role model inside
app/models/Role.php using the following example:
<?php namespace App; use Zizaco\Entrust\EntrustRole; class Role extends EntrustRole { }
The
Role model has three main attributes:
name— Unique name for the Role, used for looking up role information in the application layer. For example: "admin", "owner", "employee".
display_name— Human readable name for the Role. Not necessarily unique and optional. For example: "User Administrator", "Project Owner", "Widget Co. Employee".
description— A more detailed explanation of what the Role does. Also optional.
Both
display_name and
description are optional; their fields are nullable in the database.
PermissionPermission
Create a Permission model inside
app/models/Permission.php using the following example:
<?php namespace App; use Zizaco\Entrust\EntrustPermission; class Permission extends EntrustPermission { }
The
Permission model has the same three attributes as the
Role:
name— Unique name for the permission, used for looking up permission information in the application layer. For example: "create-post", "edit-user", "post-payment", "mailing-list-subscribe".
display_name— Human readable name for the permission. Not necessarily unique and optional. For example "Create Posts", "Edit Users", "Post Payments", "Subscribe to mailing list".
description— A more detailed explanation of the Permission.
In general, it may be helpful to think of the last two attributes in the form of a sentence: "The permission
display_name allows a user to
description."
UserUser
Next, use the(),
hasRole($name),
can($permission), and
ability($roles, $permissions, $options) within your
User model.
Don't forget to dump composer autoload
composer dump-autoload
And you are ready to go.
Soft DeletingSoft Deleting
The default migration takes advantage of
onDelete('cascade') clauses within the pivot tables to remove relations when a parent record is deleted. If for some reason you cannot use cascading deletes in your database, the EntrustRole and EntrustPermission classes, and the HasRole trait include event listeners to manually delete records in relevant pivot tables. In the interest of not accidentally deleting data, the event listeners will not delete pivot data if the model uses soft deleting. However, due to limitations in Laravel's event listeners, there is no way to distinguish between a call to
delete() versus a call to
forceDelete(). For this reason, before you force delete a model, you must manually delete any of the relationship data (unless your pivot tables uses cascading deletes). For example:
$role = Role::findOrFail(1); // Pull back a given role // Regular Delete $role->delete(); // This will work no matter what // Force Delete $role->users()->sync([]); // Delete relationship data $role->perms()->sync([]); // Delete relationship data $role->forceDelete(); // Now force delete will work regardless of whether the pivot table has cascading delete
UsageUsage
ConceptsConcepts
Let's start by creating the following
Roles and
Permissions:
$owner = new Role(); $owner->name = 'owner'; $owner->display_name = 'Project Owner'; // optional $owner->description = 'User is the owner of a given project'; // optional $owner->save(); $admin = new Role(); $admin->name = 'admin'; $admin->display_name = 'User Administrator'; // optional $admin->description = 'User is allowed to manage and edit other users'; // optional $admin->save();
Next, with both roles created let's assign them to the users.
Thanks to the
HasRole trait this is as easy as:
$user = User::where('username', '=', 'michele')->first(); // role attach alias $user->attachRole($admin); // parameter can be an Role object, array, or id // or eloquent's original technique $user->roles()->attach($admin->id); // id only
Now we just need to add permissions to those Roles:
$createPost = new Permission(); $createPost->name = 'create-post'; $createPost->display_name = 'Create Posts'; // optional // Allow a user to... $createPost->description = 'create new blog posts'; // optional $createPost->save(); $editUser = new Permission(); $editUser->name = 'edit-user'; $editUser->display_name = 'Edit Users'; // optional // Allow a user to... $editUser->description = 'edit existing users'; // optional $editUser->save(); $admin->attachPermission($createPost); // equivalent to $admin->perms()->sync(array($createPost->id)); $owner->attachPermissions(array($createPost, $editUser)); // equivalent to $owner->perms()->sync(array($createPost->id, $editUser->id));
Checking for Roles & PermissionsChecking for Roles & Permissions
Now we can check for roles and permissions simply by doing:
$user->hasRole('owner'); // false $user->hasRole('admin'); // true $user->can('edit-user'); // false $user->can('create-post'); // true
Both
hasRole() and
can() can receive an array of roles & permissions to check:
$user->hasRole(['owner', 'admin']); // true $user->can(['edit-user', 'create-post']); // true
By default, if any of the roles or permissions are present for a user then the method will return true.
Passing
true as a second parameter instructs the method to require all of the items:
$user->hasRole(['owner', 'admin']); // true $user->hasRole(['owner', 'admin'], true); // false, user does not have admin role $user->can(['edit-user', 'create-post']); // true $user->can(['edit-user', 'create-post'], true); // false, user does not have edit-user permission
You can have as many
Roles as you want for each
User and vice versa.
The
User abilityUser ability
More advanced checking can be done using the awesome
ability function.
It takes in three parameters (roles, permissions, options):
rolesis a set of roles to check.
permissionsis a set of permissions to check.
Either of the roles or permissions variable can be a comma separated string or array:
$user->ability(array('admin', 'owner'), array('create-post', 'edit-user')); // or $user->ability('admin,owner', 'create-post,edit-user');
This will check whether the user has any of the provided roles and permissions.
In this case it will return true since the user is an
admin and has the
create-post permission.
The third parameter is an options array:
$options = array( 'validate_all' => true | false (Default: false), 'return_type' => boolean | array | both (Default: boolean) );
validate_allis a boolean flag to set whether to check all the values for true, or to return true if at least one role or permission is matched.
return_typespecifies whether to return a boolean, array of checked values, or both in an array.
Here is an example output:
$options = array( 'validate_all' => true, 'return_type' => 'both' ); list($validate, $allValidations) = $user->ability( array('admin', 'owner'), array('create-post', 'edit-user'), $options ); var_dump($validate); // bool(false) var_dump($allValidations); // array(4) { // ['role'] => bool(true) // ['role_2'] => bool(false) // ['create-post'] => bool(true) // ['edit-user'] => bool(false) // }
The
Entrust class has a shortcut to
ability() for the currently logged in user:
Entrust::ability('admin,owner', 'create-post,edit-user'); // is identical to Auth::user()->ability('admin,owner', 'create-post,edit-user');
Blade templatesBlade templates
Three directives are available for use within your Blade templates. What you give as the directive arguments will be directly passed to the corresponding
Entrust function.
@role('admin') <p>This is visible to users with the admin role. Gets translated to \Entrust::role('admin')</p> @endrole @permission('manage-admins') <p>This is visible to users with the given permissions. Gets translated to \Entrust::can('manage-admins'). The @can directive is already taken by core laravel authorization package, hence the @permission directive instead.</p> @endpermission @ability('admin,owner', 'create-post,edit-user') <p>This is visible to users with the given abilities. Gets translated to \Entrust::ability('admin,owner', 'create-post,edit-user')</p> @endability
MiddlewareMiddle' => ['permission:owner', 'permission:writer']
For more complex situations use
ability middleware which accepts 3 parameters: roles, permissions, validate_all
'middleware' => ['ability:admin|owner,create-post|edit-user,true']
Short syntax route filterShort::routeNeedsRole('admin/advanced*', 'owner', Redirect::to('/home'));
Furthermore both of these methods accept a fourth parameter. It defaults to true and checks all roles/permissions given. If you set it to false, the function will only fail if all roles/permissions fail for that user. Useful for admin applications where you want to allow access for multiple groups.
// if a user has 'create-post', 'edit-comment', or both they will have access Entrust::routeNeedsPermission('admin/post*', array('create-post', 'edit-comment'), null, false); // if a user is a member of 'owner', 'writer', or both they will have access Entrust::routeNeedsRole('admin/advanced*', array('owner','writer'), null, false); // if a user is a member of 'owner', 'writer', or both, or user has 'create-post', 'edit-comment' they will have access // if the 4th parameter is true then the user must be a member of Role and must have Permission Entrust::routeNeedsRoleOrPermission( 'admin/advanced*', array('owner', 'writer'), array('create-post', 'edit-comment'), null, false );
Route filterRoute filter
Entrust roles/permissions can be used in filters by simply using the
can and
hasRole methods from within the Facade:
Route::filter('manage_posts', function() { // check the current user if (!Entrust::can('create-post')) { return Redirect::to('admin'); } }); // only users with roles that have the 'manage_posts' permission will be able to access any admin/post route Route::when('admin/post*', 'manage_posts');
Using a filter to check for a role:
Route::filter('owner_role', function() { // check the current user if (!Entrust::hasRole('Owner')) { App::abort(403); } }); // only owners will have access to routes within admin/advanced Route::when('admin/advanced*', 'owner_role');
As you can see
Entrust::hasRole() and
Entrust::can() checks if the user is logged in, and then if he or she has the role or permission.
If the user is not logged the return will also be
false.
TroubleshootingTroubleshooting
If you encounter an error when doing the migration that looks like:
SQLSTATE[HY000]: General error: 1005 Can't create table 'laravelbootstrapstarter.#sql-42c_f8' (errno: 150) (SQL: alter table `role_user` add constraint role_user_user_id_foreign foreign key (`user_id`) references `users` (`id`)) (Bindings: array ())
Then it's likely that the
id column in your user table does not match the
user_id column in
role_user.
MakeLicense
Entrust is free software distributed under the terms of the MIT license.
Contribution guidelinesContribution guidelines
Support follows PSR-1 and PSR-4 PHP coding standards, and semantic versioning.
Please report any issue you find in the issues page.
Pull requests are welcome. | https://libraries.io/packagist/l5cms%2Fentrust | CC-MAIN-2020-50 | en | refinedweb |
From R Hub – JavaScript for the R package developer
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Originally posted on the R Hub blog
JS and R, what a clickbait! Come for JS, stay for our posts about Solaris and WinBuilder.
No matter how strongly you believe in JavaScript being the language of the future (see below), you might still gain from using it in your R practice, be it back-end or front-end.
In this blog post, Garrick Aden-Buie and I share a roundup of resources around JavaScript for R package developers.
JavaScript in your R package
Why and how you include JavaScript in your R package?
Bundling JavaScript code
JavaScript’s being so popular these days, you might want to bundle JavaScript code with your package. Bundling instead of porting (i.e. translating to R) JavaScript code might be a huge time gain and less error-prone (your port would be hard to keep up-to-date with the original JavaScript library).
The easiest way to interface JavaScript code from an R package is using the V8 package. From its docs, “A major advantage over the other foreign language interfaces is that V8 requires no compilers, external executables or other run-time dependencies. The entire engine is contained within a 6MB package (2MB zipped) and works on all major platforms.” V8 documentation includes a vignette on how to use JavaScript libraries with V8. Some examples of use include the js package, “A set of utilities for working with JavaScript syntax in R“; jsonld for working with, well, JSON-LD where LD means Linked Data; slugify (not on CRAN) for creating slugs out of strings.
For another approach, depending on a local NodeJS and Node Package Manager (NPM) installation, see Colin Fay’s blog post “How to Write an R Package Wrapping a NodeJS Module”. An interesting read about NPM and R, even if you end up going the easier V8 route.
JavaScript for your package documentation
Now, maybe you’re not using JavaScript in your R package at all, but you might want to use it to pimp up your documentation! Here are some examples for inspiration. Of course, they all only work for the HTML documentation, in a PDF you can’t be that creative.
Manual
The roxygenlabs package, that is an incubator for experimental roxygen features, includes a way to add JS themes to your documentation. With its default JS script, your examples gain a copy-paste button!
Noam Ross once described a way to include a searchable table in reference pages, with DT.
In writexl docs, the infamous Clippy makes an appearance. It triggers a tweet nearly once a week, which might be a way to check people are reading the docs?
For actual analytics in manual pages, it seems the unknown package found a trick by adding a script from statcounter.
Vignettes
In HTML vignettes, you can also use web dependencies. On a pkgdown website, you might encounter some incompatibilities between your, say, HTML widgets, and Boostrap (that powers pkgdown).
Web dependency management
HTML Dependencies
A third, and most common, way in which you as an R package developer might interact with JavaScript is to repackage web dependencies, such as JavaScript and CSS libraries, that enhance HTML documents and Shiny apps! For that, you’ll want to learn about the htmltools package, in particular for its
htmlDependency() function.
As Hadley Wickham describes in the Managing JavaScript/CSS dependencies section of Mastering Shiny, an HTML dependency object describes a single JavaScript/CSS library, which often contains one or more JavaScript and/or CSS files and additional assets. As an R package author providing reusable web components for Shiny or R Markdown, in Hadley’s words, you “absolutely should be using HTML dependency objects rather than calling
tags$link(),
tags$script(),
includeCSS(), or
includeScript() directly.”
htmlDependency()
There are two main advantages to using
htmltools::htmlDependency(). First, HTML dependencies can be included with HTML generated with htmltools, and htmltools will ensure that the dependencies are loaded only once per page, even if multiple components appear on a page. Second, if components from different packages depend on the same JavaScript or CSS library, htmltools can detect and resolve conflicts and load only the most recent version of the same dependency.
Here’s an example from the applause package. This package wraps applause-button, a zero-configuration button for adding applause/claps/kudos to web pages and blog posts. It was also created to demonstrate how to package a web component in an R package using htmltools. For a full walk through of the package development process, see the dev log in the package README.
html_dependency_applause <- function() { htmltools::htmlDependency( name = "applause-button", version = "3.3.2", package = "applause", src = c( file = "applause-button", href = "[email protected]/dist" ), script = "applause-button.js", stylesheet = "applause-button.css" ) }
The HTML dependency for
applause-button is provided in the
html_dependency_applause() function. htmltools tracks all of the web dependencies being loaded into a document, and conflicts are determined by the
name of the dependency where the highest
version of a dependency will be loaded. For this reason, it’s important for package authors to use the package name as known on npm or GitHub and to ensure that the
version is up to date.
Inside the R package source, the applause button dependencies are stored in inst/applause-button.
applause └── inst └── applause-button ├── applause-button.js └── applause-button.css
The
package,
src, and
script or
stylesheet arguments work together to locate the dependency’s resources:
htmlDependency() finds the
package‘s installation directory (i.e.
inst/), then finds the directory specified by
src, where the
script (
.js) and/or
stylesheet (
.css) files are located. The
src argument can be a named vector or a single character of the directory in your package’s
inst folder. If
src is named, the
file element indicates the directory in the
inst folder, and the
href element indicates the URL to the containing folder on a remote server, like a CDN.
To ship dependencies in your package, copy the dependencies into a sub-directory of
inst in your package (but not
inst/src or
inst/lib, these are reserved directory names1). As long as the dependencies are a reasonable size2, it’s best to include the dependencies in your R package so that an internet connection isn’t strictly required. Users who want to explicitly use the version hosted at a CDN can use shiny::createWebDependency().
Finally, it’s important that the HTML dependency be provided by a function and not stored as a variable in your package namespace. This allows htmltools to correctly locate the dependency’s files once the package is installed on a user’s computer. By convention, the function providing the dependency object is typically prefixed with
html_dependency_.
Using an HTML dependency
Functions that provide HTML dependencies like
html_dependency_applause() aren’t typically called by package users. Instead, package authors provide UI functions that construct the HTML tags required for the component, and the HTML dependency is attached to this, generally by including the UI and the dependency together in an
htmltools::tagList().
applause_button <- function(...) { htmltools::tagList( applause_button_html(...), html_dependency_applause() ) }
Note that package authors can and should attach HTML dependencies to any tags produced by package functions that require the web dependencies shipped by the package. This way, users don’t need to worry about having to manually attach dependencies and htmltools will ensure that the web dependency files are added only once to the output. This way, for instance, to include a button, using the
applause package an user only needs to type in e.g. their Hugo blog post3 or Shiny app:
applause::button()
Some web dependencies only need to be included in the output document and don’t require any HTML tags. In these cases, the dependency can appear alone in the
htmltools::tagList(), as in this example from xaringanExtra::use_webcam(). The names of these types of functions commonly include the
use_ prefix.
use_webcam <- function(width = 200, height = 200, margin = "1em") { htmltools::tagList( html_dependency_webcam(width, height) ) }
JS and package robustness
How do you test JS code for your package, and how do you test your package that helps managing JS dependencies? We’ll simply offer some food for thought here. If you bundle or help bundling an existing JS library, be careful to choose dependencies as you would with R packages. Check the reputation and health of that library (is it tested?). If you are packaging your own JS code, also make sure you use best practice for JS development.
Lastly, if you want to check how using your package works in a Shiny app, e.g. how does that applause button turn out, you might find interesting ideas in the book “Engineering Production-Grade Shiny Apps” by Colin Fay, Sébastien Rochette, Vincent Guyader and Cervan Girard, in particular the quote “instead of deliberately clicking on the application interface, you let a program do it for you”.
Learning and showing JavaScript from R
Now, what if you want to learn JavaScript? Besides the resources that one would recommend to any JS learner, there are interesting ones just for you as R user!
Learning materials
The resources for learning we found are mostly related to Shiny, but might be relevant anyway.
- Colin Fay’s field notes about JS for Shiny
- Materials from the RStudio conf 2020 workshop about JS for Shiny lead by Garrick Aden-Buie
- Really only for Shiny, see the documentation about packaging JavaScript in Shiny apps
Literate JavaScript programming
As an R user, you might really appreciate literate R programming. You’re lucky, you can actually use JavaScript in R Markdown.
At a basic level,
knitr includes a JavaScript chunk engine that writes the code in JavaScript chunks marked with
```{js} into a
tag in the HTML document. The JS code is then rendered in the browser when the reader opens the output document!
Now, what about executing JS code at compile time i.e. when knitting? For that the experimental bubble package provides a knitr engines that uses Node to run JavaScript chunks and insert the results in the rendered output.
The js4shiny package blends of the above approaches in html_document_js(), an R Markdown output for literate JavaScript programming. In this case, JavaScript chunks are run in the reader’s browser and console outputs and results are written into output chunks in the page, mimicking R Markdown’s R chunks.
Different problem, using JS libraries in Rmd documents
More as a side-note let us mention the htmlwidgets package for adding elements such as leaflet maps to your HTML documents and Shiny apps.
Playground
When learning a new language, using a playground is great. Did you know that the js4shiny package provides a JS playground you can use from RStudio? Less new things at once if you already use RStudio, so more confidence for learning!
And if you’d rather stick to the command line, bubble can launch a Node terminal where you can interactively run JavaScript, just like the R console.
R from JavaScript?
Before we jump to the conclusion, let us mention a few ways to go the other way round, calling R from JavaScript…
Shiny, “an R package that makes it easy to build interactive web apps straight from R.”, and the golemverse, a set of packages for developing Shiny apps as packages
OpenCPU is “An API for Embedded Scientific Computing” that can allow you to use JS and R together.
If you use the plumber R package to make a web API out of R code, you can then interact with that API from e.g. Node.
Colin Fay wrote an experimental Node package for calling R.
Conclusion
In this post we went over some resources useful to R package developers looking to use JavaScript code in the backend or docs of their packages, or to help others use JavaScript dependencies. Do not hesitate to share more links or experience in the comments below!
The post From R Hub – JavaScript for the R package developer. | https://www.r-bloggers.com/2020/08/from-r-hub-javascript-for-the-r-package-developer/ | CC-MAIN-2020-50 | en | refinedweb |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.