text stringlengths 454 608k | url stringlengths 17 896 | dump stringclasses 91 values | source stringclasses 1 value | word_count int64 101 114k | flesch_reading_ease float64 50 104 |
|---|---|---|---|---|---|
This tutorial is part of a series, in which we are learning all about the layout system in React Native. I recommend that you read the previous tutorial about how flexDirection works as we will continue using the same project that we created in the first tutorial.
Now that we have a better understanding of flex direction, let’s review the alignment options that we have available. We will create a container that displays a message with a title, we will learn how to align this component.
First we need to create the required views and texts, open the index.ios.js tab in your favorite text editor and add the following code to the render method, as a child of the content view.
'use strict'; var React = require('react-native'); var { AppRegistry, StyleSheet, Text, View, Component } = React; class ReactLayouts extends Component{ render() { return ( <View style={styles.mainContainer}> <View style={styles.toolbar}> <Text style={styles.toolbarButton}>Add</Text> <Text style={styles.toolbarTitle}>This is the title</Text> <Text style={styles.toolbarButton}>Like</Text> </View> <View style={styles.content}> {/* START NEW CODE */} <View style={styles.messageBox}> <View> <Text style={styles.messageBoxTitleText}>A simple mesage</Text> </View> <View> <Text style={styles.messageBoxBodyText}>This is just a dummy sample it will help us to see the alignment in action.</Text> </View> </View> {/* END NEW CODE */} </View> </View> ); } }
In the previous code we’ve defined a message box container. It’s important to notice that we are adding just the code between the comments, the toolbar code was defined before in the flexDirection tutorial. We only have the title, and the content is completely static.
Once we have the component rendered, we need to add some styles to the stylesheet object.
var styles = StyleSheet.create({ // … messageBox:{ backgroundColor:'#ef553a', width:300, paddingTop:10, paddingBottom:20, paddingLeft:20, paddingRight:20, borderRadius:10 }, messageBoxTitleText:{ fontWeight:'bold', color:'#fff', textAlign:'center', fontSize:20, marginBottom:10 }, messageBoxBodyText:{ color:'#fff', fontSize:16 } });
These is a pretty common styles, just some colors, paddings, fonts and so on. As a result we should have something as in the following image.
Now that we have a component, we can start playing around with the alignment. Aligning components in React is very straightforward, all we need to do is define the alignItems property in the container’s styles.
var styles = StyleSheet.create({ //.. content:{ backgroundColor:'#ebeef0', flex:1, alignItems:'center' //<----- }, //... });
This will automatically center the component on the screen. Because we didn’t define a flex direction, the column direction is used. Therefore the component is horizontally centered.
On the other hand, if we set the flex direction to row, the component will be vertically centered. This is a very important concept to keep in mind.
We have three more options to align our component.
1.flex-start which will align the component at the top/start of the parent component.
2.flex-end which will align the component to the bottom/end of the parent container.
3.stretch will set the height or width to 100% of the container, based on the flex direction.
We can also justify our components. For example if we want to center our components horizontally and vertically, we will need to apply the following changes to our styles.
var styles = StyleSheet.create({ content:{ flex:1, flexDirection:'row', alignItems:'center', justifyContent:'center' }, … });
First we set the flex direction to row, this will arrange the children horizontally. In order to center the component horizontally we use the alignItems property, then we use justifyContent to vertically center the component.
We have a few more options to justify our component to the left, right, as well as to add space between or around the children.
Conclusion
The layout system in React Native is very powerful and flexible, we can create any layout with all the available options that we have. Understanding how flexbox works is important in order to build our very custom layouts and components.
You can download the code from Github. I recommend you to take a look at the documentation and try all the possible values in the available properties.
Crysfel Villa
Related Posts
- React Navigation and Redux in React Native Applications
In React Native, the question of “how am I going to navigate from one screen…
- React Navigation and Redux in React Native Applications
In React Native, the question of “how am I going to navigate from one screen… | https://moduscreate.com/blog/aligning-children-using-flexbox-in-react-native/ | CC-MAIN-2021-43 | refinedweb | 730 | 57.16 |
Introduction
Part 1 of this discussion of the J2EE platform covered the major APIs of the J2EE. This article continues that discussion with an overview of the Java XML Pack, which is part of the Java Web Services Developer Pack (Java WSDP), which in turn includes a host of other things such as a Java Registry Server (a UDDI-compliant registry). We'll also cover the J2EE vendors and their associated products.
The Java XML Pack includes additional APIs specifically for working with web services:
Java API for XML Processing (JAXP)
Java API for XML Messaging (JAXM)
Java API for XML Registries (JAXR)
Java API for XML-Based RPC (JAX-RPC)
The following sections briefly describe each of these APIs.
Java API for XML Processing (JAXP)
JAXP is a document-oriented API; through a "pluggability" layer, it allows any XML-compliant parser to be used from within an application.
NOTE
As discussed previously, XML parsers support either the SAX API (for efficiently parsing XML documents through the use of event handlers) or the DOM API (for building and modifying XML documents through a tree structure).
JAXP also supports namespaces and XML schemas as well as XML Stylesheet Language Transformations (XSLT), which provides both a display mechanism for XML documents and a way to transform XML documents from one format to another.
Java API for XML Messaging (JAXM)
JAXM facilitates developing programs that produce and consume SOAP messages. It provides methods such as creating SOAP messages and adding contents to the SOAP messages.
An application that uses JAXM is known as a JAXM client or a JAXM application. By default, a JAXM application supports only synchronous messaging. To support asynchronous messaging, a JAXM application must use a JAXM provider.
Additionally, the API provides functionality for industry initiatives such as ebXML. We'll get to ebXML in a future article.
Java API for XML Registries (JAXR)
JAXR defines a uniform way of accessing different types of registries. Currently, JAXR supports both the ebXML registry and UDDI registries. It includes functionality for publishing, searching, modifying, and deleting entries in the registry. JAXR also includes sample JAXR clients for browsing well-known registries, including those from Microsoft and IBM.
Java API for XML-Based RPC (JAX-RPC)
JAX-RPC provides an API for building web services and clients using RPCs and XML. Although it uses SOAP for messaging, the application doesn't actually deal with the parts of the SOAP message (as is the case with JAXM).
JAX-RPC supports both static invocation and dynamic invocation. Dynamic invocation is useful in cases where services can be discovered only during runtime. | http://www.informit.com/articles/article.aspx?p=29752&seqNum=4 | CC-MAIN-2018-26 | refinedweb | 436 | 51.99 |
JavaScript utility libraries
The Web3.Storage JavaScript client library provides a simple interface for interacting with Web3.Storage. This page highlights some additional libraries that may be helpful when working with the client library, or when using the HTTP API directly.
files-from-path
The files-from-path package provides a simple way for Node.js users to load files from the filesystem into the
File objects that the Web3.Storage client library likes to use.
Here's a quick example:
import { getFilesFromPath } from 'web3.storage'; async function storeFiles(path = 'path/to/somewhere') { const files = await getFilesFromPath(path); for (const f of files) { console.log(f); // { name: '/path/to/me', stream: [Function: stream] } } const web3Storage = getStorageClient(); const cid = await web3storage.put(files); console.log(`stored ${files.length} files. cid: ${cid}`); }
Note that if you're using the client library you don't need to install the
files-from-path package seperately. Instead, just import the
getFilesFromPath or
filesFromPath functions from the
web3.storage package.
ipfs-car
The Web3.Storage API works with Content Archive (CAR) files, which package up content addressed data into a simple format for storage and transport. Internally, the client library uses the ipfs-car package to create CARs from regular files before sending data to the API.
If you prefer to work with CARs directly, see the how-to guide on working with Content Archives for usage information for ipfs-car and information about other options.
carbites
The carbites package includes a command line tool and JavaScript API for splitting Content Archive (CAR) files into chunks. This is used to upload files that are larger than the 100mb size limit on the upload HTTP endpoint.
See the how-to guide on working with Content Archives for more information on using the carbites tool. | https://web3.storage/docs/reference/js-utilities/ | CC-MAIN-2022-40 | refinedweb | 297 | 56.66 |
Content uploaded by Muhamad Falih Akbar
Author content
All content in this area was uploaded by Muhamad Falih Akbar on Apr 23, 2020
Content may be subject to copyright.
AIP Conference Proceedings 2226, 030012 (2020); 2226, 030012
© 2020 Author(s).
Centralized swarming UAV using ROS for
collaborative missions
Cite as: AIP Conference Proceedings 2226, 030012 (2020);
Published Online: 22 April 2020
T. Indriyanto, A. R. Rizki, M. L. Hariyadin, M. F. Akbar, and A. A. A. Syafi
Centralized Swarming UAV Using ROS for Collaborative
Missions
T. Indriyanto1, A. R. Rizki1, a), M. L. Hariyadin1, M. F. Akbar2, A. A. A. Syafi2
1Faculty of Mechanical and Aerospace Engineering, Institut Teknologi Bandung, Indonesia
2School of Electrical and Informatics Engineering, Institut Teknologi Bandung, Indonesia
a)Corresponding author: asyraf.ridho@gmail.com
Abstract. Recently, UAV technology is growing rapidly. One of the technologies in the UAV is swarming. Many
applications of UAV can utilize the swarming technology, such as collaborative searching, monitoring, and mapping. In
this research, basic structure of swarming system was created. The objective is to develop a system with the ability to
adapt to various operational conditions, such as UAV connection loss and system failure in some UAVs. In such
conditions, the system should be able to generate new mission plan for each UAV based on the number of remaining
UAVs. Since swarming technology can be applied to many purposes, the swarming system has to be created to
accommodate various missions. For this research, ROS framework was chosen because it has been equipped with
complete tools. The swarming system created was then tested using SITL simulation because it can connect to the
swarming system with ease. Several simulations were performed with various number of UAV. Results show that the
created swarming system was able to finish the given missions regardless of the failure in some UAVs. The more number
of UAV utilized, the faster the mission can be finished.
INTRODUCTION
UAV is a developing technology in the community. The AIAA defines a UAV as “an aircraft which is designed
or modified, not to carry a human pilot and is operated through electronic input initiated by the flight controller or
by an onboard autonomous flight management control system that does not require flight controller intervention.”
Many people are competing to develop sophisticated technology of UAV in order to solve many challenges. There
are also remarkable development of UAVs and MAVs for military use. However, it can be said that the infinite
possibilities of utilizing their outstanding characteristics for civil applications remain hidden.1 Many activities are
greatly assisted with UAV technology, such as mapping, monitoring, searching, etc. Many researches have
developed the swarming UAV technology, either for quadcopter or fixed wing, to perform several missions as
described in Refs. 2–6.
In swarming technology, system architecture is important. The use of Unmanned Aerial Vehicles (UAVs) which
can operate autonomously in dynamic and complex operational environments is becoming increasingly more
common.7 Therefore, a system that can be customized to any missions is necessary. In addition to being modular for
any mission, the system has to respond to any disturbance in the field. Various problems can also be solved
using this swarming technology.
CENTRALIZED SWARMING
The cooperation of heterogeneous vehicles requires the integration of sensing, control, and planning in an
appropriated decisional architecture. These architectures can be either centralized or decentralized depending on
assumptions on the knowledge’s scope and accessibility of the individual vehicles, their computational power, and
the required scalability. A centralized approach will be relevant if the computational capabilities are compatible with
7th International Seminar on Aerospace Science and Technology – ISAST 2019
AIP Conf. Proc. 2226, 030012-1–030012-10;
Published by AIP Publishing. 978-0-7354-1985-8/$30.00
030012-1
the amount of information to process and the exchange of data meets both the requirements of speed (up-to-date
data) and expressivity (quality of information enabling well-informed decision-taking).8
The swarming system that we use is centralized, which means that communication only occurs between the
vehicle and its center, the GCS (Ground Control System). Centralized swarming does not require communication
among the vehicles. If the vehicle wants to give data to another vehicle, it can be passed through the GCS.
In this research, ROS framework was used to develop the system of swarming. SITL simulation was then used to
prove the algorithm of swarming system. Swarming UAV is an advanced technology that can be implemented on
various utilities, especially on a mission involved large area. This research is purposed to create the swarming
system that can adapt to alteration of UAV condition and various number of UAV. At first, the swarming system is
created using ROS. After the creation, the system is tested using SITL simulation.
Robot Operating System (ROS)
Robot Operating System (ROS) has been used as a framework for many robotic applications. The ROS was
chosen because it is an easy to use system with a neat structure and contains many packages developed by many
users. Besides that, ROS also has many tools to facilitate its operation. The ROS was designed to meet a specific set
of challenges encountered when developing large-scale service robots.9
The ROS architecture was designed and divided into three sections or levels of concepts. The levels are File
System level, Computation Graph level and Community level.10 On the File System level, ROS is divided into
several folders, just like general operating system. The smallest part of ROS is a package, in which there are
manifest, messages, services, code, etc. Messages and services are useful for transferring data between nodes, while
nodes are useful for processing existing data. Manifest functions to provide comprehensive information about the
package. The package collection is called stacks.
On the Computational Graph level, ROS already has a structure that connects all existing processes. There are
several important components in this section, namely master, nodes, server parameters, messages, topics, services,
and bags. Nodes function as executable files that contain data processing that can be connected to each other. Nodes
can be written using Python or C++. Nodes can also be written using JavaScript, but their use is not yet common.
The master is the main core of ROS. Without a master, ROS will not work. The master is in charge of knowing
the location of all existing nodes, so that communication between nodes can be established.
Messages are data sent between nodes. Using message, nodes can communicate between one another. To
distinguish available messages, ROS uses topics so that a channel for messages is created. This concept is used so
that one topic can be subscribed by more than one node.
In addition to using messages, there are other ways to communicate with nodes, namely with services. With the
concept of services user can communicate with node and receive a reply. With the same concept, service parameters
work, parameters of a node or a system can be set with the service concept.
In addition to the components mentioned above, there is also file launcher. File Launcher functions to run
various nodes at once. Furthermore, the file launcher can also run other launcher files. One feature of the file
launcher that is very important is that nodes or launchers can be grouped and given namespace. As a result all t he
topics and services generated in that group will have namespaces.
Mavros
Mavros is a package that provides communication driver for various autopilots with MAVLink communication
protocol.11 With the Mavros Package, ROS can be used to manage UAV system. Mavros is used by calling an
existing package, namely apm.launch or px4.launch. With the launcher called, topics and services related to UAVs
are ready to use. A list of topics and services that can be used is shown in Fig. 1 and Fig. 2. Users then only have to
create a node to process data from available topics and services.
030012-2
FIGURE 1. List of Mavros' topics
FIGURE 2. List of Mavros' services
Software in the Loop (SITL) Simulation
SITL (software in the loop) simulator allows users to run Plane, Copter or Rover without any hardware. It is built
on the autopilot code using ordinary C++ compiler, giving users a native executable code that allows testing the
behaviour of the code without the need of hardware.12
FIGURE 3. SITL communication scheme12
030012-3
Using SITL users can test system that has been created by utilizing UDP connections with port 14550 to Other
GCS as shown in Fig. 3. The results can be checked by looking at the GCS application with a TCP connection port
5760.
SITL can be called more than once. One argument when calling SITL is instance. More than one SITL can be
called by giving different instances. Using different instances, different communication ports will be formed, so that
communication between one instance and the other will not collide.
SWARM ARCHITECTURE
In creating swarming system in ROS, a robust and dependable architecture to control more than one vehicle is
needed. In theory, the system needs to be able to manage countless vehicles.
The system shall also include multiple failsafe actions in reaction to the higher chance of failure in case of higher
quantity swarming, which requires methods to disarm specific failing vehicles safely. After ensuring the safety and
maturity of the system, user need to give the system missions to be performed by the vehicles through swarming
management. The ROS architecture of swarming management for N number of vehicles to do M number of
missions are depicted in Fig. 4.
FIGURE 4. The architecture of swarm system
The swarming system developed in this research is centralized, meaning that all managing algorithm for the
UAVs are put in the GCS. Two main packages were built for development, i.e. swarming management package and
mission management package. The separation are done to ensure that each package is focussing on its own tasks as
part of the whole framework.
The swarming package focuses on managing N number of vehicles currently active and doing the mission, by
monitoring their status and making sure that the vehicles are in the condition to continue the mission. Meanwhile,
the mission package focuses on making sure the vehicles do their mission correctly and efficiently. However, this
does not mean that the package are isolated from each other because topics can be used to communicate between the
two packages if needed.
030012-4
Swarm Management Package
Two main roles of the swarming management package are to separate data from all the participating vehicles and
separate failsafe management for each vehicles in the mission. Both are key roles in a working swarming system.
Data separation were done by a launcher file, which is named “initialization.launch.” Using this launch file users
can call other launcher by giving namespaces, in this case the apm.launch will be called and will give namespaces to
topics and services which will be generated by the nodes in apm.launch.
For every vehicle connected to the swarming management, the initialization launch will be launched. Not only
does it separate data, it will also forward the already separated data to the GCS application interface. To make this
possible, the use of the gcs_bridge node is needed. The scheme of the data transfer is depicted in Fig. 5.
FIGURE 5. Scheme of data transfer
One of the failsafe functionality is to determine the number of vehicles that are connected and able to continue
the mission. Sometimes some vehicles might suffer from specific conditions that refrain them from continuing on
with the mission, which is why determination of the number of mission-ready vehicles is needed, so that the mission
management can manage the vehicles to cover up for vehicles that are not able to continue the mission. The failsafe
functionality also needs to make sure that the vehicles are safe from harm while doing their mission. In this case the
battery and telemetry parameters can be used to decide whether or not the vehicles can continue their mission. If the
battery and telemetry state are below acceptable status, the vehicle(s) will trigger the RTL mode, make the UAV
returns to the home point.
Mission Management Package
The mission management package varies depending on the mission that need to be done using the swarming
method. Each mission management package will need to share the tasks to all vehicles available and ensure the
mission is done as efficiently as possible. The mission management package will also ensure that each vehicle gets
its share of work and will update every vehicle’s mission every time new vehicle is added to the swarming system.
In this research only simple case of sharing mission is performed.
SIMULATION
Two cases were simulated. In the first simulation four quadcopters were used to do a four waypoint monitoring
mission. The test includes simulating connection lost on the fourth vehicle and setting the third one to RTL. The
mission for the quadcopters is depicted in Fig. 6. When the swarming system started, the overall mission divided
into four, initial number of quadcopter. The next scenario is the fourth UAV is disconnected for several reasons.
After that, the overall mission is automatically divided into three because that alteration. The third scenario is the
third UAV enter the failsafe condition (ex: telemetry or battery below the limit). On the third scenario, the overall
mission is automatically divided into two, the number of remainder UAV.
030012-5
FIGURE 6. The mission for all UAVs in first simulation (indicated by yellow line)
In the second simulation, various numbers of UAV, quadcopter and fixed wing were used. All UAVs monitor
border between the USA and Mexico in straight line. The mission for the UAVs is given in Fig. 7. The length of the
border is 7.5 km and the longest distance from home to border is 4 km. The average speed of the quadcopter is 8 m/s
and the fixed wing is 22 m/s. All UAVs start from the same point, home position in the north of the border line, then
start the mission from the west of each mission. Each UAV monitor in a cycle, starting from the west to the east then
turn around to west again.
FIGURE 7. The mission of UAVs in second mission (indicated by yellow line)
RESULT AND DISCUSSION
In Fig. 8 the response of ROS system using four quadcopter swarming system is shown. In this simulation a new
message type with topic “/swarm/uav_status” was made. The message contains three data, i.e. the connected UAV,
still connected UAV and Mission-ready UAV.
030012-6
FIGURE 8. Ground Control Station view for second simulation
The waypoints for the swarming mission on the UAV1 was then loaded. An algorithm in the system was
developed to calculate and assign mission automatically. The whole mission is shown on Fig. 9, as well as the
division for each UAV: Fig. 9(a) for UAV1, etc.
(a)
(b)
(c)
(d)
FIGURE 9. The mission for four UAVs
UAV4 was then disconnected. The system recognized only three connected and active UAVs. As a result, the
system will automatically calculates and assign new waypoint to cover UAV4’s share of the mission: Fig. 10(a) for
UAV1, etc.
030012-7
(a)
(b)
(c)
FIGURE 10. The mission for three UAVs after UAV4 disconnected
UAV3 flight mode was then set to RTL to simulate failsafe function. This event made the number of mission-
ready UAV decrease again to two, so the system will generate newer waypoint for the remaining UAV: Fig. 11(a)
for UAV1 and 11(b) for UAV2.
(a)
(b)
FIGURE 11. The mission for two UAVs after UAV3 returned home
In the second simulation, time needed to complete the mission was recorded. The mission is completed when all
UAVs have performed a full circle two times to monitor their own line. The time is started when the UAV’s mode is
AUTO in home position.
030012-8
TABLE 1. Simulation with various number of quadcopter UAV.
Number of UAV
Time for Completing Mission
1
41 minutes 4 seconds
2
26 minutes 19 seconds
3
20 minutes 21 seconds
4
17 minutes 5 seconds
5
16 minutes 1 second
Table 2. Simulation with various number of fixed wing UAV.
Number of UAV
Time for Completing Mission
1
16 minutes 8 seconds
2
8 minutes 35 seconds
3
6 minutes 37 seconds
CONCLUSION
Simulation showed that the architecture of swarm system can be operated for any number of UAVs. The
flexibility in the number of UAV is important because each mission has different needs, so the number of UAV can
be varied. The system also showed resistance from interference caused by lost signal or UAV return to home. If
there is an interference amid mission, the system will generate new mission for each UAV automatically. When a
UAV lost connection, new missions are generated for each remaining UAVs. When a UAV do a failsafe by
returning home, new missions are generated for each remaining UAVs as well. This system can be developed for
different types of missions, based on mission packages that were created. For collaborative mission, it has been
proven that using more UAVs, there is a decrease in time for completing the mission. By adding number of UAV
from one to two, there is a significant decrease; however, with more number of UAVs the time reduction is less and
less.
ACKNOWLEDGMENTS
The research is funded by ITB through its research program P3MI 2019 ITB. This work is supported by
Aksantara UAV Research and Development Team ITB.
REFERENCES
1. K. Nonami, et al., Autonomous Flying Robots: Unmanned Aerial Vehicles and Micro Aerial Vehicles
(Springer, Tokyo, 2010), p. 2.
2. A. Bandala, et al., “Swarming Algorithm for Unmanned Aerial Vehicle (UAV) Quadrotors: Swarm Behavior
for Aggregation, Foraging, Formation, and Tracking,” J. Adv. Comput. Intelligence and Intelligent Inf. 18,
745 (2014).
3. X. Zhua, Z. Liu, and J. Yang, “Model of Collaborative UAV Swarm toward Coordination and Control
Mechanisms Study,” J. Procs. 51, 493 (2015).
4. H. V. D. Parunak, S. A. Brueckner, and J. J. Odell, “Swarming coordination of multiple UAV’s for
collaborative sensing,” in Proceedings of 2nd AIAA Unmanned Unlimited Systems (AIAA, San Diego,
California, 2003).
5. A. L. Alfeo1, et al., “Swarm coordination of mini-UAVs for target search using imperfect sensor,” Intelligent
Decision Technologies 12, 1 (2018).
6. A. P. Lamping, et al., “FlyMASTER: Multi-UAV control and supervision with ROS,” in 2018 Aviation
Technology, Integration, and Operations Conference (AIAA, Atlanta, Georgia, 2018).
7. K. Dalamagkidis, K. P. Valavanis, and L. A. Piegl, “Current status and future perspectives for unmanned
aircraft system operations,” J. Intell. Robot Syst. 52, 313.
8. I. Maza, et al., in Handbook of Unmanned Aerial Vehicles, edited by K. P. Valavanis and G. J. Vachtsevanos
(Springer, Dodrecht, 2015), p. 957.
030012-9
9. M. Quigley, et al., “ROS: an open-source Robot Operating System,” in ICRA Workshop on Open Source
Software (Kobe, Japan, 2009), p. 5.
10. A. Martinez and E. Fernandez, Learning ROS for Robotics Programming (Packt Publishing, Birmingham,
2013), p. 25.
11. V. Ermakov, Mavros documentation, 2018, available at [Accessed on 21 August
2019].
12. Ardupilot Development Team, SITL Simulator (Software in the Loop), 2019, available at) [Accessed on 21 August 2019].
030012-10 | https://www.researchgate.net/publication/340856977_Centralized_swarming_UAV_using_ROS_for_collaborative_missions | CC-MAIN-2022-40 | refinedweb | 3,220 | 56.15 |
Applies To: Windows Server 2008, Windows Server 2008 R2
Domain
The fully qualified domain name (FQDN) for the domain to which this resource record applies.
Service
The universal symbolic name of the TCP/IP service, such as "_telnet" or "_smtp" to be served by this record.
Protocol
The transport protocol that is used by this service. In most cases, this value is either Transmission Control Protocol (TCP) or User Datagram Protocol (UDP), although other transport protocols can be used if they are implemented for your network.
Priority. Lower numbers are given higher preference. The highest priority or preference goes to a host (offering the service that is specified in this record) that has a priority value of zero (0).
Where more than one service location (SRV) resource record is present for a specific service, the host with the lowest preference number is given first to Domain Name System (DNS) clients. If this host fails or is not reachable, the SRV-specified host with the next highest preference number is the next host that is used.
If two or more hosts that are listed in the service location (SRV) resource record for a specified service share the same preference number, DNS clients can try hosts of equal preference in random order..
We recommend that you use a value of 0 (no weighting) when load-balancing is not needed. This reduces processing time for SRV queries and makes SRV resource records more readable.
Port number
The TCP/IP server port on the host that offers the service that is specified in Service on the target host that is specified in Host offering this service. The range of port numbers is 0 through 65535. This number is often—but not required to be—a well-known reserved port number as specified in Requests for Comments (RFC) 1700, "Assigned Numbers." Depending on the value in Protocol that is included in this record, the port number can represent either a UDP or TCP port.
Host offering this service
The FQDN of the target host that provides the type of TCP/IP-based service that is described in Service. This name must match a valid host (A) resource record in the DNS domain namespace. If a target FQDN consisting of a single period (".") is used here, it indicates to any DNS resolvers (clients) requesting this type of service that this service is not available for this domain.
Allow any authenticated user to update all DNS records with the same name. This setting applies only to DNS records for a new name.
When this option is selected, it permits the resource record to be updated dynamically. When the update is performed, the host requesting). | http://technet.microsoft.com/en-us/library/cc742513 | CC-MAIN-2013-48 | refinedweb | 447 | 60.65 |
Django does not have a clean, built-in mechanism to separate GET and POST implementations. This simple decorator provides this behavior. Django does provide an alternate way using class-based views, but defining class for each of your view functions may be an overkill. You can name the get and post functions anything you wish, but you need to make sure they are returned in the same order (get first and then post).
Example usage:
@formview
def edit(request, id):
form = EditForm(id, request.POST or None) def get(): return render(request, 'edit.html', {'form' : form}) def post(): if form.is_valid(): form.save(id) return redirect('list') return get,
Nice example of "Simple is better than complex". I like it.
#
"Django does not have a clean, built-in mechanism to separate GET and POST implementations."
Yes it does. Use a class based view and derive your class from ProcessFormView. Then, simply define get() and post() methods.
See the Django ProcessFormView docs.
#
Please login first before commenting. | https://djangosnippets.org/snippets/2768/ | CC-MAIN-2022-27 | refinedweb | 166 | 69.48 |
The tag cloud represents items size according to the sum of their occurences in the list. This is typically the kind of control that you see on blogs, to show the post tags. When having a large list containing lots of items, the tag cloud can be used for a first filter to avoid sliding in the list for too long.
Here is an example of 2 tag clouds. You can change the background, foreground and the font family of the control. The tag cloud is compatible with both portrait and landscape mode.
The datasource used by the control is a collection of objects, and uses .ToString() for its representation.
In my case it is a collection of int for the first tag cloud and a collection of string for the second tag cloud. Bind the ItemsSource property of the tag cloud with this collection just like you would for a ListBox. The font size will be computed automatically, according to the item occurrences in the source list.
Use SelectedItem property or SelectionChanged event to get the selected tag.
In my example, I use a collection of DataSample:
public class DataSample
{
public string City { get; set; }
public int Year { get; set; }
}
The datasources of my 2 tag clouds are like follows, where dataSampleList is a collection of DataSample :
ct1.ItemsSource = dataSampleList.Select(d => d.Year);
ct2.ItemsSource = dataSampleList.Select(d => d.City);
In the XAML code, the namespace should be declared like this:
xmlns:cloud="clr-namespace:Wp7TagCloud;assembly=Wp7TagCloud"
Here is the code to declare the first tag cloud:
<cloud:TagCloud x:
Here is the second one, added with a TextBlock binded on the SelectedItem of the tag cloud and also handling the SelectionChanged event:
<cloud:TagCloud x:
<TextBlock Text="Selected City:"/>
<TextBlock Text="{Binding ElementName=ct2, Path=SelectedItem}"/>
Here is the assembly you should download to use the tag cloud control.
The source code should be available soon in the Coding4Fun Toolkit (thanks Clint ).
Hi,
I tried to use your control but I had some problems. When I add an ItemsSource manually in Page constructor everything goes right, but when I set ItemsSource after an event call the data is not refreshed. Any hints or tips?
Thanks in advance.
Lucas, I'll check that as soon as possible
Lucas, I juste fixed it : can you check ?
Thanks for your feedback !
What if I have a collection of strings and doubles and I need to make a tag cloud (the largest string is one with the biggest number). Do you have or know solution for that?
To use my control, you should provide a list of strings having as many occurrences of the same string than the corresponding number (double).
If it leads to a large number of occurences in the string list, you can provide an equivalent repartition (percentage) of string occurencies for each number.
Example : if you have ((Foo, 25000) (Bar, 50000)) you can provide the list (Foo, Bar, Bar).
This list should be easy to provide from your existing structure.
Hope it helps
Setting the selectedItem (or the item selected item is bound to) from code doesn't seem to update the highlight color :|
I don't see the assembly here - could you please point to that or the code? I don't think its there yet in Coding4Fun toolkik?
Hello Tushar,
You have a link to the assembly just under the code in this article.
Can we have access to the source code for this project?? | http://blogs.msdn.com/b/stephe/archive/2011/03/28/a-tag-cloud-control-for-windows-phone-7.aspx | CC-MAIN-2015-35 | refinedweb | 581 | 70.13 |
You can subscribe to this list here.
Showing
5
results of 5
M
Michael Kay <mike@...> writes:
>").
That's fine. My workaround was basically the same thing: treat the
in-scope namespaces as empty unless the node in question was an
ELEMENT. (I'm already walking "up" the tree to the nearest element,
for reasons I can't immediately recall.)
Be seeing you,
norm
--
Norman Walsh <ndw@...> | The whole secret of life is to be | interested in one thing profoundly and
| in a thousand things well.--Horace
| Walpole
Michael Kay <mike@...> writes:
>?
I created the QName with new QName("someURI", "someLocalName") then
passed it to receiver.addAttribute. (If that's not enough information,
I can try to construct a test case, though I simply worked around it by
making sure there was a prefix.)
Be seeing you,
norm
--
Norman Walsh <ndw@...> | Progress isn't made by early risers. | It's made by lazy men trying to find
| easier ways to do something.--Robert
| Heinlein
On 02/01/2012 21:59, Norman Walsh wrote:
> The constructor for an InscopeNamespaceResolver is:
>
> public InscopeNamespaceResolver(NodeInfo node) {
> if (node.getNodeKind() == Type.ELEMENT) {
> this.node = node;
> } else {
> this.node = node.getParent();
> }
> }
>
> If the node in question happens to be a document node, then this.node
> will be null and all heck will break loose later on...
>
>").
Michael Kay
Saxonica
On 02/01/2012 17:44, Norman Walsh wrote:
> Hi,
>
>?
Michael Kay
Saxonica
>
> In XML Calabash, a user can specify an attribute with a namespace URI
> without specifying a prefix. Saxon 9.3 used to generate _1:
> automatically.
>
> I also had a bug where I was accidentally creating an xml:base
> attribute without making the xml: prefix explicit. Saxon 9.3 used to
> generate xml: for me.
>
> Be seeing you,
> norm
>
>
>
> ------------------------------------------------------------------------------
>!
>
>
> _______________________________________________
> saxon-help mailing list archived at
> saxon-help@...
> | http://sourceforge.net/p/saxon/mailman/saxon-help/?viewmonth=201201&viewday=3 | CC-MAIN-2015-48 | refinedweb | 304 | 67.76 |
Need help cloning? Visit
Bitbucket 101.
Atlassian SourceTree
is a free Git and Mercurial client for Windows.
Atlassian SourceTree
is a free Git and Mercurial client for Mac.
result.update([(key, data[key]) for key in attrs])
return result
-def equal_lists(left, right):
- """
- Compares two lists and returs True if they contain the same elements, but
- doesn't require that they have the same order.
- right = list(right)
- if len(left) != len(right):
- return False
- for item in left:
- if item in right:
- del right[right.index(item)]
- else:
- return False
- return True
-
def object_list_to_table(headings, dict_list):
"""
Converts objects to table-style list of rows with heading: | https://bitbucket.org/wkornewald/djangotoolbox/diff/djangotoolbox/utils.py?diff2=a824b82f4300&at=pullrequest-1 | CC-MAIN-2015-27 | refinedweb | 107 | 67.96 |
U.
First introduced in iOS 3.2 (or should we call it iPhone OS 3.2, given the early date?),
UIText does exactly what it says: it checks text. Read on to learn how you can use this class for spell checking and text completion.
Spell CheckingSpell Checking
What happens if you mistype a word in iOS? Type “hipstar” into a text field and iOS will offer to autocorrect to “hipster” most of the time.
We can find the same suggested substitution using
UIText:
import UIKit let str = "hipstar" let text
Checker = UITextChecker = UIText Checker() let misspelledChecker()") if misspelledAt: 0, wrap: false, language: "en_US") if misspelled Range.location != NSNotRange.location != NSNot Found, let firstFound, let first Guess = textGuess = text Checker.guesses(forChecker.guesses(for WordWord Range: misspelledRange: misspelled Range, in: str, language: "en_US")?.first { print("First guess: \(firstRange, in: str, language: "en_US")?.first { print("First guess: \(first Guess)") // First guess: hipster } else { print("Not found") }Guess)") // First guess: hipster } else { print("Not found") }
The returned array of strings might look like this one:
["hipster", "hip star", "hip-star", "hips tar", "hips-tar"]
Or it might not—
UIText produces context- and device-specific guesses. According to the documentation,
guesses “returns an array of strings, in the order in which they should be presented, representing guesses for words that might have been intended in place of the misspelled word at the given range in the given string.”
So no guarantee of idempotence or correctness, which makes sense for a method with
guesses... in the name. How can NSHipsters trust a method that changes its return value? We’ll find the answer if we dig further.
Learning New WordsLearning New Words
Let’s assume that you want your users to be able to type
"hipstar" exactly. Let your app know that by telling it to learn the word, using the
UIText class method:
UIText
Checker.learnChecker.learn Word(str)Word(str)
"hipstar" is now a recognized word for the whole device and won’t show up as misspelled in further checks.") misspelledAt: 0, wrap: false, language: "en_US") misspelled Range.location == NSNotRange.location == NSNot Found // trueFound // true
As expected, the search above returns
NSNot, for
UIText has learned the word we created.
UIText also provides class methods for checking and unlearning words:
UIText and
UIText.
Suggesting CompletionsSuggesting Completions
There’s one more
UIText API, this time for finding possible completions for a partial word:
let partial = "hipst" let completions = text
Checker.completions( forChecker.completions( for PartialPartial WordWord Range: NSRange(0..<partial.utf16.count), in: partial, language: "en_US" ) completions == ["hipster", "hipsters", "hipster's"] // trueRange: NSRange(0..<partial.utf16.count), in: partial, language: "en_US" ) completions == ["hipster", "hipsters", "hipster's"] // true
completions gives you an array of possible words from a group of initial characters. Although the documentation states that the returned array of strings will be sorted by probability,
UIText only sorts the completions alphabetically.
UIText’s OS X-based sibling,
NSSpell, does behave as it describes.
You won’t see any of the custom words you’ve taught
UITextshow up as possible completions. Why not? Since vocabulary added via
CheckerChecker
UITextis global to the device, this prevents your app’s words from showing up in another app’s autocorrections.
Checker.learnChecker.learn Word(_:)Word(_:)
Building an app that leans heavily on a textual interface? Use
UIText to make sure the system isn’t flagging your own vocabulary. Writing a keyboard extension? With
UIText and
UILexicon, which provides common and user-defined words from the system-wide dictionary and first and last names from the user’s address book, you can support nearly any language without creating your own dictionaries! | https://nshipster.com/uitextchecker/?utm_source=andybargh-newsletter-20160503&utm_medium=email&utm_campaign=andybargh-newsletter | CC-MAIN-2021-49 | refinedweb | 606 | 55.54 |
Embarcadero Controls: The Frame
Introduction
A frame is a type of control container that resembles
a form. Like a form, when you create a frame, it possesses its own unit
where its children can be programmatically managed. Unlike a form, and
like all the other containers we will review after this one except the
data module, a frame should be embedded on a form that would act as its
ultimate parent. Unlike most other containers except for the data module,
users do not see a frame and are not aware of its presence. It is used
only by the programmer.
A frame is used for better management of controls
because, like a form, a frame is created as a separate entity with a body
independent of a form.
Practical
Learning: Introducing Frames
Frame Creation
There are two general steps to making a frame available
to your application
After creating and embedding a frame, you can change its
controls in either the form or the frame. Anything you do in one, such as
adding, removing, or resizing controls, would be automatically updated on
the other.
When a frame has focus at design time, you can change
its controls as you see fit. From the form on which a frame is embedded, to
programmatically access a control placed on that frame, do so indirectly
through the frame. For example, the following code would change to blue the
background color of an edit control named Edit2 that is placed on a frame
named Frame21 and created in Unit2:
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "Unit1.h"
#include "Unit2.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "Unit2"
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormDblClick(TObject *Sender)
{
Frame21->Edit2->Color = clBlue;
}
//---------------------------------------------------------------------------
A frame control is based on the TFrame class
which is in turn based on TCustomtFrame.
Practical
Learning: Using Frames | http://www.functionx.com/cppbuilder/controls/frame.htm | CC-MAIN-2013-20 | refinedweb | 314 | 60.75 |
Could you help me understand why
print(truth(prog.match(text, 0, 6)))
import re
from operator import truth
prog = re.compile(r'<HTML>$')
text = "<HTML> "
print("Last symbol: {}".format(len('<HTML>')-1))
print(truth(prog.match(text, 0, 6)))
print(truth(prog.match(text)))
If you use the
match(text, startpos, endpos) method of a compiled regex, it will act as if you've passed
match(text[startpos:endpos]) (well, not exactly, but for the purposes of
$, it is). This means that it'll think
<HTML> is at the end of the input (which is what
$ matches).
However, when this is not the case the extra whitespace at the end of
text will prevent
$ from matching, so no match is found. | https://codedump.io/share/kMhRwwu5uNpQ/1/regex-can39t-understand-the-endpos | CC-MAIN-2017-13 | refinedweb | 122 | 65.83 |
When debugging a project line-by-line in Visual Studio, you may receive this error:
Step into: Stepping over method without symbols ‘namespace’
This error occurs when you attempt to debug a DLL or EXE that is lacking a symbols (.pdb) file.
Check the project’s binDebug folder to ensure the DLL/EXE in question has a corresponding pdb file. If not, be sure to build the DLL/EXE with its project configuration set to “Debug” so that it will generate a pdb file.
If the problem occurs with a third-party library, you may be out of luck because most third-party libraries do not include a pdb file, and therefore you cannot debug into them.
A StackOverflow article says this error may also occur if you attempt to debug a yield expression in a method that returns an IEnumerable, though I have not confirmed this.
Ran into this exact situation because of a yield statement within the method. When I added test code using a List to force immediated execution, the code stepped into the method as expected. See actual example below.
A StackOverflow article says this error may also occur if you attempt to debug a yield expression in a method that returns an IEnumerable, though I have not confirmed this.
Stepping over method without symbols – How to step into?
Actual example:
// Code would not step into ReadData method because it had yield statement contained within it. IEnumerable ie = ReadData(fileName, null, fileDescription);
// For testing, added following line to force immediate evaluation as noted above.
// Code then stepped into the method as desired. List list = ReadData(fileName, null, fileDescription).ToList();
I am having the above described issue, my DLLs have a corresponding pdb file and I am not using IEnumerable in any of my DLL code | http://www.csharp411.com/step-into-stepping-over-method-without-symbols/ | CC-MAIN-2016-22 | refinedweb | 299 | 60.35 |
XmImMbLookupString(library call) XmImMbLookupString(library call)
NAME [Toc] [Back]
XmImMbLookupString - An input manager function that retrieves a
composed string from an input method
SYNOPSIS [Toc] [Back]
#include <Xm/XmIm.h>
int XmImMbLookupString(
Widget widget,
XKeyPressedEvent *event,
char *buffer_return,
int bytes_buffer,
KeySym *keysym_return,
int *status_return);
DESCRIPTION [Toc] [Back].
widget Specifies the ID of the widget registered with the input
manager
event Specifies the key press event
buffer_return
Specifies the buffer in which the string is returned
bytes_buffer
Specifies the size of the buffer in bytes
keysym_return
Specifies a pointer to the KeySym returned if one exists
status_return
Specifies the status values returned by the function. These
status values are the same as those for the XmbLookupString
function. The possible status values are:
XBufferOverflow [Toc] [Back]
The size of the buffer was insufficient to handle
the returned string. The contents of buffer_return
and keysym_return are not modified. The required
buffer size is returned as a value of the
function. The client should repeat the call with a
larger buffer size to receive the string.
- 1 - Formatted: January 24, 2005
XmImMbLookupString(library call) XmImMbLookupString(library call)
XLookupNone [Toc] [Back]
No consistent input was composed. The contents of
buffer_return and keysym_return are not modified
and the function returns a value of 0.
XLookupChars [Toc] [Back]
Some input characters were composed and returned
in buffer_return. The content of keysym_return is
not modified. The function returns the length of
the string in bytes.
XLookupKeysym [Toc] [Back]
A keysym value was returned instead of a string.
The content of buffer_return is not modified and
the function returns a value of 0.
XLookupBoth [Toc] [Back]
A keysym value and a string were returned. The
keysym value may not necessarily correspond to the
string returned. The function returns the length
of the string in bytes.
RETURN [Toc] [Back]
Return values depend on the status returned by the function. Refer to
the description of status values above.
RELATED [Toc] [Back]
XmImGetXIM(3), XmImGetXIC(3), XmImRegister(3), XmImSetValues(3), and
XmImUnregister(3).
- 2 - Formatted: January 24, 2005 | http://nixdoc.net/man-pages/HP-UX/man3/XmImMbLookupString.3.html | CC-MAIN-2013-20 | refinedweb | 336 | 56.45 |
It looks like you're new here. If you want to get involved, click one of these buttons!
May I know how to read file in drc deck, for example, I defined layers in a file, then in the main drc deck, i directly read the layer file, no need define again. Or create a drc deck with some common rules, then in other deck, i directly ready the file, no need define those rules again.
I find using following commands does not work.
file=File.open("layer_filename")
file_data=file.readlines
file.close
Thank you very much!
@TryAndTry DRC decks are basically Ruby code. Layer are only Ruby variables.
You can basically use Ruby features to organize your code (classes, procedures etc.). But as this needs some level of planning beyond linear code, I have created a lean feature to include other files without caring for namespace isolation etc. You can find the details here:
Matthias | https://www.klayout.de/forum/discussion/2084/how-to-read-other-file-in-drc-deck | CC-MAIN-2022-33 | refinedweb | 156 | 74.69 |
Hello again.
This is about commander again.
Basicly, this is a question about what you want in a interface that links the user with the system commands. How would it look, how would you like to view files on your computer?
Printable View
Hello again.
This is about commander again.
Basicly, this is a question about what you want in a interface that links the user with the system commands. How would it look, how would you like to view files on your computer?
Hi.
The most effective such system would be console based. You would be presented with a console window (command line) as a sort of popup window which can be set as "always on top". You would be able to quickly duplicate the window in its current state and tile it at the edge of the current window with system commands.
All system commands would have a uniform naming standard. Documentation for all system names would be available from the command line. Documentation on all system commands would be available from the command line.
Important to such a system would be word completion: not only for files in the current directory, but for all partially-entered paths. Instead of always completing with the next best match, an alternative key command would present the user with an inline, scrollable list of the files/folders in the directory your partial path is currently at (ala msvc++ editor).
Not only this, but such a system would, by another set of key combinations do word completion from past commands entered into the console rather than completion for paths; the two varieties of completion found with paths would be here as well. Separating path completion from command completion would be important to increase effeciency.
This popup method would also be essential for finding something in the current directory where a ls or dir would return a list too long to fit on the screen.
Additionally, these popup lists could be forced to stay on the screen by moving the mouse over them and issuing a key combination (and allowed to leave the same way).
The benefit of this is for another element of the system. This is that scripts would be written via a popup launched by a key combination and which would compile right into the allow console instances (kind of like a Forth frontend). Any language system that impledmented the particular API could be used, but preferrably it would be Perl with all system commands (mentioned above) in the global namespace.
Now, this would not be a command-line only system. Applications would, when launched from the console, run visually much as they do on current systems with a GUI, but managing their use of the screen would be greatly improved.
Minimizing, Closing, Maximizing, Positioning, Locking in Position, Docking, and Tiling would be done through a combination of the mouse and keyboard so as to allow maximum effeciency. A simple operation would be holding the mouse anywhere over a window and pressing a key combination to activate one of these; those requiring motion (dock to which direction, move to which direction) would be accompanied by a mouse "gesture".
No time wasted trying to grab the edges of windows, or to line them up just right. Why use one hand when you can use two? You, with both hands, issue commands to the windows as fast as you can move a mouse over them and hit the keyboard combination.
To perform operations on a set of windows, another key combination would be used to add the window which the mouse is currently over to a pool of windows on which to operate (sort of like a clipboard). This would be useful for minimizing, closing, or tiling a number of windows.
Note that this same system would be used on minimized windows (which would goto a taskbar on the bottom of the screen).
There would be no application icons or start menu or clock wasting screen space, but rather there would only be a taskbar. Often used applications would be launched via keyboard shortcuts for those most often used. For those less frequently used but still common, they would be stored in directories accesible by the console. However, this would not be tedious, as you could create console keyword shortcuts to these directores, such that cd "directory-shortcut-name" would change to that directory.
Every visible containment box is a window and can be maniuplated via keyboard commands combined with mouse gestures.
Additonally, you would of course be able to create new virtual desktops through another keyboard shortcut. Multiple desktops are navigable via keyboard shortcuts alone, but they are not just floating somewhere unknown, but are logically positioned relative to the desktop from which they are launched. This allows an alternative means of navigation. Through a mouse gesture combined with a keyboard shortcut you can scroll seamlessly between your desktops, or quickly flip (with a flick mouse gesture) to desktops logically postiioned around you. This gives you a very intuitive feel of where things are; above you, left of you, over to the right of the open text document, down below you, etc.
Would all these desktop space be a hassle? No, you can always bring up the overal map to quickly navigated to any specific area. Additionally, you can tie any window, particularly open console windows to a key combinations on the fly so that when you navigating around your desktop space, you can summon the window, preferrably a command window, to appear for you on top of the currently visible desktop space.
What about movign windows around all of this? Of course in the map view you can manipulate windows in all of the same ways you can on the single view via keyboard commands and mouse gestures. If you do not like this approach, you can also add a number of windows to your pool of windows, and via a keyboard shrotcut, drag them with you where you go when you scroll to or navigate to other areas of the desktop with keyboard shortcuts and mouse gestures.
In some cases what you have is just too big to fit on one screen, but you need quick access to both. In this case you can bookmark any desktop area so that you can traverse between them with a system key and one of the function keys to which you assigned it. Also there is a simple forward/back traversal of these bookmarks. Need what you have at one bookmark to where you are now? Just pool up the windows there, switch bookmarks, and summon them.
You are the master of your computer, commanding your virtual desktops and windows with both hands, always with both hands. You give the orders and they are obeyed immediately and in an orderly and effecient fashion.
Wow,
Thanks heaps! I really wasn't thinking of someone to write that much of what they wanted. That's a huge help, thanks again.
Yes, console based is a huge thing that is going into the interface, that's where the name commander has come from, and command line based gui. Although i would like console only, it wouldn't be supported by all. It will be an optional gui however, so for those who rather get a few extra fps in quake or unreal, they can do so. Basicly, the console is much the same to common games today, where you can drop down the console with a hit of the ~ key. I like the idea of two hands alot, and understand where you're coming from the more i think about it. It's like when doom first came out, people all used the keyboard, now we are on to more sophisticated games, we need the action of our mouse.
So thanks again, I'll try very hard to include all of what you've said.
Darren | http://cboard.cprogramming.com/brief-history-cprogramming-com/22570-what-would-you-like-interface-printable-thread.html | CC-MAIN-2015-18 | refinedweb | 1,321 | 67.99 |
Among common Python exceptions, the most infamous and time consuming one to solve is no doubt the “ModuleNotFoundError” but actually is pretty simple to fix once you understand a couple of concepts.
Fundamentally it can be raised for three reasons:
1. A typo or a wrong path specified in the import statement
This is the most easy to spot, and if you are using an IDE like PyCharm you will notice it immediately before running your code.
In order to reproduce the exception, let’s consider a project structure like:
/proj /foo __init__.py bar.py main.py
A
main.py containing:
from fo.bar import BarClass c = BarClass()
and
bar.py containing:
class BarClass: pass
By using /proj as a current working directory and by running:
python main.py
We will obtain the following exception:
Traceback (most recent call last): File "/Users/dave/PycharmProjects/proj/main.py", line 1, in <module> from fo.bar import BarClass ModuleNotFoundError: No module named 'fo'
To solve the problem, we have simply to change the import in order to match the right path (“foo.bar” instead of “fo.bar”):
from foo.bar import BarClass c = BarClass()
So far, so easy… but let’s go on with scenario N.2
2. Execution context which requires an entry addition in
sys.path that has not been satisfied
This one occurs when we are executing a python script with an import statement in a directory from which the interpreter cannot resolve the path to the required module defined in the import statement due to missing or bad configuration of the
sys.path.
And, here you have first to understand how Python lookup for modules works, so I report the official documentation:
When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named
spam.pyin a list of directories given by the variable
sys.path.
sys.pathis initialized from these locations:
- The directory containing the input script (or the current directory when no file is specified).
- PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
- The installation-dependent default.
Let’s keep the structure of the scenario N.1, but with
main.py containing:
class BaseClass: pass
and
bar.py containing:
from main import BaseClass c = BaseClass()
but now let’s change the working directory to “foo”, and launch the command:
python bar.py
We will obtain the following exception:
Traceback (most recent call last): File "bar.py", line 1, in <module> from main import BaseClass ModuleNotFoundError: No module named 'main'
Because since we are in the “foo” directory and we didn’t update the
sys.path, Python is looking for a
main.py file in that directory and obviously is not the case!
We can fix this issue in two ways: by using the
PYTHONPATH environment variable or by extending the
sys.path list.
To use the
PYTHONPATH in a single shot, we can launch the script with the following command:
PYTHONPATH=../ python bar.py
In this way, we are practically saying “hey python, please consider also the parent directory for the module lookup”.
The same can be specified programmatically in this way:
import sys sys.path.append('../')
Of course the code above must be written before the other import statement. Anyway my advice is to avoid such approach and to relay only on the
PYTHONPATH environment variable.
Use
sys.path instead to debug your current path resolution in this way:
import sys for p in sys.path: print(p)
3. Circular dependency
This one is the most hateful that you can face. It happens when a module A requires something from a module B and in turn, the module B requires something from module A, thus generating a “deadly” circular reference.
In most cases it happens after an automatic refactoring with PyCharm (typically if you use the logging framework in the classical way)*, if it happens for other reasons it’s a signal that your software design is not sound and that you must review it carefully.
* for a classical usage of the logging framework I mean:
import logging log = logging.getLogger(__name__) class MyClass: def my_method(self): log.info('My method invoked')
then after moving
MyClass to another module (via automatic refactoring), PyCharm tends to include an import of
log (which 1. is not required since each module has its logger, 2. may cause the circular dependency).
To manually reproduce the exception, let’s consider a super simple structure like the following:
/proj a.py b.py
With
a.py containing:
from b import ClassB class ClassA: def __init__(self): self.b = ClassB()
and
b.py containing:
from a import ClassA class ClassB: pass a = ClassA()
By running
python a.py in the project root, we will get the following exception:
Traceback (most recent call last): File "/Users/dave/PycharmProjects/proj/a.py", line 1, in <module> from b import ClassB File "/Users/dave/PycharmProjects/proj/b.py", line 1, in <module> from a import ClassA File "/Users/dave/PycharmProjects/proj/a.py", line 1, in <module> from b import ClassB ImportError: cannot import name 'ClassB'
If we pay attention we can quite easily spot that this time we are facing a circular reference issue, since the stack trace is longer that the previous ones, and it prints a “ping-pong” between
a.py and
b.py. | http://www.daveoncode.com/2017/03/07/how-to-solve-python-modulenotfound-no-module-named-import-error/ | CC-MAIN-2017-43 | refinedweb | 907 | 56.35 |
How to machine / make a custom sonic screwdriver out of aluminum with Arduino inside.
This Instructable documents the creation of two custom Sonic Screwdrivers for two very special people in my life. They are huge Doctor Whofans and I could not resist making this for them.
Please note this project made use of metal working machinery (Mill and Lathe).
Technical Specifications:
Material: 6061 aluminum, black delrin (acetal) and glass
Electronics: ATTiny85, custom PCB, 4 AG13 batteries, ear bud speakers, 2 SMD LEDs
Programming platform: Arduino
Here is a video
Step 1: Fabrication
Places to look for machining tools:
Harbor Freight
Grizzly Tools
Taig
Sherline
Step 2: Update Tracker Page
UPDATE - 12/3/2013: Auction ended. No more sonics available to sell. I am out of material to make more. Thanks Everyone for your interest.
***********************************************************
UPDATE- 5/2/13 : I do not feel that this instructable is yet complete. So, I am building TWO(2) more sonics and taking a lot more pictures. My goal is to explain how this was done in excruciating detail. I will even dissect the Arduino Sketch so everyone will know what to modify to customize the sound and lights to their liking. I will also be providing Eagle files and schematics as well as gerber files so as to reach more people. Please check back often.
UPDATE - 5/4/2013 : "May the Fourth Be With You"
Added "Step 2: Update Tracker"
Added "Step 5: Usign a Lathe" - This page will detail setting up the piece to be cut on a lathe, the actual turning of the piece, and even making custom tool bits to get the job done. Yes, a lot to cover on one page. there are lots of pictures.
UPDATE - 5/5/2013 : "Feliz Cinco de Mayo!"
10:00 am - Added three more pictures in Step 5.
Added one new picture in Step 8.
1:30 PM - Added "Step 6: Turning other parts" - This page has a lot of before and after pictures. I hope people like them.
UPDATE - 5/7/2013
Added Eagle gerber files and schematics to "Step 11 - Circuit Board". Added a second PCB design as well. Please check it out.
Added new Step. "Step 10 - Arduino Sketch picked apart." the Arduino sketch (program) is dissected and each section is explained to make it easier for everyone to customize the sound and lights to their liking.
Minor UPDATE - 5/14/2013
Made minor change in text on Step 10. I am hoping that this instructables becomes a comunity project and modify the arduino code to make different sound effects.
Please comment if there is anything else that needs pictures or more explanation.
Minor UPDATE - 8/5/2013
Thank you everyone for looking at this instructable. I was a FINALIST for the Epilog Contest. I won a runner up prize pack. THANK YOU INSTRUCTABLES for this great website and for the contests.
UPDATE - 11/6/2013: I have made two more sonics screwdrivers. They have potential buyers already.. I have someone helping me make a few more with the materials I have left. I hope to have completed sonics for sale soon.
UPDATE - 11/11/2013: Added more pictures. Auction for one of three sonics starting November 14, 2013.
UPDATE - 11/25/2013: Auction for my last fully built sonic screwdriver for sale is here.
UPDATE - 12/3/2013: Auction ended. No more sonics available to sell. I am out of material to make more.
Step 3: Materials and Tools
I went shopping at OnlineMetals.com for most of my raw materials.
Assorted aluminum round tubes and rods
For this build I purchased 12 or 24 inches of each:
- 1” dia. solid round stock
- 0.5” OD x 0.083” wall tube
- 0.75” OD x 0.065” wall tube
- 0.625” OD x 0.065” wall tube
For this build I purchased 12 inches of each:
- 1” dia. Black solid Acetal (delrin) round stock
- .75” Nylotron (nylon) round stock.
1 Attiny85
breadboard
High intensity LEDs
Blank PCB
Solder
Wires
150 Ohm Resistor (I used this site)
Very small speakers (got mine from broken ear buds)
1 tactile button, low profile
Screws
1 ball bearing
A small piece of semi-rigid plastic (water bottle?)
Superglue (cyanoacrylate)
5 minute epoxy
Shrink tubing
Electric tape
Tools:
Computer with Arduino installed
Lathe (sorry if you don’t have this)
Mill (sorry if you don’t have this either)
Drill press
Chop saw or hack saw
PCB etching kit (chemical or mechanical)
Assorted drill bits
Assorted screw taps
Assorted end mills
Assorted lathe tools
Rotary tool or grinder
Dial indicator and magnetic base
Digitial Caliper
a good ruler
Safety glasses (Safety first)
Raw materials were purchased from:
Step 4: Crude Assembly and Test Fitting
One of the Sonic Screwdrivers cut dimensions:
- 0.75" OD tube cut to 5.5 inches length for the main body.
- 0.625" OD tube cut to 2 inches length for the inner sleeve
- 0.5" OD tube cut to 2 inches length for the neck
- 1" solid bar cut to 1.25" for the emitter
- 1" solid Delrin cut to 1.25" length for the end cap
Do whatever is necessary to make the parts fit together. In my case, I had to reduce the outside diameter (OD) of the .625” tube to slide freely inside the .75” OD tube. I then had to reduce the OD of the .5” tube a quarter inch from the tip so it would fit snugly into the .625” tube. I bore a hole in a section of 1” round stock so the other end of the .5” tube fits snugly into that. All of the above gave me a crude sonic screwdriver shape.
I am not sure any of the above could get done precisely without a lathe.
I will cover all of the above in more detail on the next page.
Step 5: Using a Lathe
Using a lathe is fairly straight forward: you clamp an object in a chuck; the chuck spins; a tool is brought up to the spinning object and material is cut/scraped away. There are a lot of online instructions to explain it all. Here are a few links. If planning on purchasing a lathe, read these. (I like Sherline and wish I had the money to buy one).
On this step I will show through the images how I chucked a piece, centered it on the chuck, then made the cuts. The longest process is the setup, which involves making sure the piece is centered and balanced, choosing the correct cutting tool, and making sure the cutting tool is the correct height. Choosing the right tool and setting the tool height is covered in a lot of tutorials and is often about user preference. But centering the piece to be cut is not open to interpretation. The piece is either centered and the end result looks good, or the piece is off center the the end product is ugly.
As part of the setup, I realized my cutters were to large to make the hole for the glass marble and I had to make a cutting tool (boring bar). I will provide links to show you how that is done too.
First piece to shape is the emitter head. I chucked a piece of 1 inch round rod. I tightened the chuck just enough to hold the piece firmly in place but not tight enough to actually start turning (cutting) it. To help visualize how to center and balance it, i colored stock red and the other side blue. I attached my dial indicator to the magnetic base and put that on the slide. I put the tip of the dial indicator probe a 1/4 inch from the tip of the piece on the chuck. I started turning the chuck by hand slowly and watched the dial indicator needle swing wildly across the dial face. I made a mental note of the highest value and the lowest value. I then rotated the chuck so that the dial needle was at its highest value. I then took a large allen wrench and tapped the top of the work piece as I watched the dial needle move to a lower value with each tap. I was trying to bring the dial needle to the middle of the highest value and the lowest value. Once I have it close (about 3-5 thousands of an inch) I rotated the chuck by hand again, making a mental note of the highest value and lowest value again. the second time rotating the chuck by hand the dial indicator was not moving as much. Again, I rotate the piece to the highest value on the dial indicator and tap the top of the workpiece to move the dial needle between the highest value and lowest value. Rotate by hand again and the needle should now either stay steady or only move one thousands of an inch. Tighten the chuck completely. This whole process used to take me anywhere from 10 to 15 minutes because i learned on my own and no one explained it to me. Now I can center an object in a chuck in about 2 minutes. Remove the dial indicator.
The piece is now centered and is ready to be turned.
I rotated my tool holder to the 20 degree position and turned the top of the emitter. I then rotated the tool holder to zero degrees and made my other cut. I attached a drill chuck to the tail stock and put a 1/2 inch drill bit on. Using plenty of WD40, i bore a hole through the center of the emitter. Cutting oil or tapping oil works too.
The cutting tools I have are 1/2" cutters. they are way too big to fit inside the center hole. But I needed to make the hole bigger to make the marble fit. What I did was get a 1/8" square HSS tool blank and shaped it into a boring bar. I followed these two instructions.
It is a lot easier than it looks. Just make sure to have a cup of water nearby and cool the tool blank frequently.
Once the hole for the marble was done, i removed the piece from the chuck, rotated it end over end 180 degrees, and re-chucked it. I did the setup process again and turned the piece to its final shape.
The neck, inner sleeve, and main body followed the exact same process above. once all the pieces were turned. I did a crude test fit.
I hope everyone enjoys the pictures.
Step 6: Turning Other Parts
The emitter is done being turned on the lathe. It will get some milling work done.
The next piece to be turned on the lathe is the inner sleeve. The outside diameter is reduced so that is slides easily inside the main body tube. Something to remember when turning metal is that the amount removed is doubled. This is because I am taking material away from both sides as the material turns. So if I remove .25 inch of material I reduce the diameter by .50 inch. It makes a huge difference if I forget that fact. And unfortunately it is a whole lot easier to remove material than it is to add it back on.
The neck is next to be turned. 1/4" of the end is turned to reduce the diameter so that it would fit snugly into the inner sleeve. Then grooves are made for decorative reasons.
Finally the main body is turned on the lathe. This is done to clean up the ends. Grooves and cuts are made for decorative reasons.
The pieces are then put together for a crude fitting.
Step 7: The Details
Cut a slot along the top of the .75” tube. We will call the .75" tube the main body. This slot will contain the sliding switch to extend and retract the sonic screwdriver. The length of this slot should equal the length of the sonic screwdriver’s neck.
Cut, etch or dremel grooves and pattern onto the surface of the .75” tube. Get creative with your design. A laser etching device would have been great at this point. Imagine the fine details I could have created if I could have laser etched the metal. I could have made alien hieroglyphs, mystic patterns, or fine traces of circuitry. Make designs on the 0.5" diameter tube (the neck) too.
Shape the button going into the slot out of plastic, wood or aluminum. I went with aluminum. Drill a hole through it to hold a rod/stem that will push down on a tactile switch on the sonic screwdriver circuit board.
insert the inner sleeve inside the main mody. Attach the button you made above (we will call it the "switch assembly") to the inner sleeve inside the slot. Move the switch along the slot to make sure it is not binding. Remove the switch assembly and the inner sleeve.
Shape the emitter head as you see fit. Add grooves and slots to maximize the light coming out of the LED. Superglue or epoxy the marble in place. Shape the bottom plug as you see fit. Consider maybe drilling a small hole or several small holes for sound to come out. I made this part out of black delrin.
Test fit everything again. Perhaps now would be a good time to drill holes and tap them for the screws that will hold everything in place. I used 4-40 set screws to hold most of my pieces together. The only exceptions would be the brass screws holding the ball detent (more on that on the next page) and socket screws to hold the switch.
Step 8: The Locking Mechanism or Ball Detent
This part is really not necessary but adds fine detail to the sonic screwdriver. The ball detent mechanism basically locks the sonic screwdriver in the extended and retracted position. It also adds a satisfying “click” when sonic screwdriver is moved into those positions.
First cut a section .75” tube about 2” in length. Next cut out a “T” section that is about 2/3 of the circumference of the tube (on one of mine it looks more like an “L”).
now take that T section and press it onto a section of .75” tube using a vise. This will mold the inside diameter of the T to be .75”.
Drill holes on the extremities of the T. Attach this T section of aluminum onto your sonic screwdriver main body about centered along the length of the slot. Temporarily secure with screws. Look inside the main body and see how much the screws protrude inside. Make a note of it. You will need to cut or grind down the screws so it is flush with the inside wall of the main body.
Measure out a good spot under the T where you will drill a hole in the main body that is the same diameter as the ball bearing. Remove the T. Drill the hole for the ball bearing.
Put the inner sleeve back into the main body and attach the switch again. Get a Sharpie (permanent marker) and insert it into the bearing hole. Slide the switch all the way to the top of the slot and all the way to the bottom. Make sure the marker is marking the inner sleeve. Remove the switch then remove the inner sleeve from the main body.
Using you mill, make a slot on the inner sleeve along the marker line about 1/32” deep. On the ends of the slot use a drill bit to make a dimple 1/16” inch deep. The bearing will ride along this slot and will fall into the dimples to lock the sleeve in place.
On the inside of the T make a pocket 1/16” deep that lines up with the bearing hole in main body. Make the pocket twice as large as the bearing hole. Cut a piece of plastic twice as large as the pocket and super glue it over the pocket. This will act as the “spring” that will put downward pressure on the ball bearing. Put axle grease or lithium grease on the plastic.
Insert the inner sleeve into the main body, attach the switch, insert the ball bearing into the ball detent hole, and attach the T over the whole thing. Do not over-tighten the screws holding the T in place. Slide the switch along the slot to test for binding. Loosen the screws holding the T to remove any binding. Tighten the screws if the movement is too lose or does not lock. Movement should feel smooth and should snap or click at the ends of the slot.
Great! let's move on
Step 9: Arduino Sketch
I followed these directions to use Arduino on an ATTiny85:
Attached is the Arduino sketch I used to make the sound and lights. Feel free to modify the sketch so you get the pitch and modulation you want as well as the blink pattern you want. In the sketch I used two(2) output pins to control two LEDs.
I used an Arduino Uno to program the ATTiny85. Please follow the links above to find out how to program an ATTiny85 as an Arduino microcontroller.
I set up two breadboards. one breadboard is to program the chip. the other breadboard is to test the program.
The code build on the example code -
created 21 Jan 2010, modified 30 Aug 2011, by Tom Igoe
(I give credit where credit is due. If using my code, please do the same)
Here is the TONE TUTORIAL in Arduino
the sketch looks like this:
/*
* Sonic Screwdriver
* Version History
*
* Version M 2.5
* For ATTiny85 16Mhz
*/
#include "pitches.h"
int melody[] = {
NOTE_F7, NOTE_G4, NOTE_A2};
int noteDurations[] = {
9,12,7 };
int x = 0;
int led1 = 3;
int led2 = 2;
void setup() {
pinMode (led1, OUTPUT);
pinMode (led2, OUTPUT);
}
void loop() {;
}
for (int thisNote = 0; thisNote < 3; thisNote++) {
int noteDuration = 1000/noteDurations[thisNote];
tone(4, melody[thisNote],noteDuration);
int pauseBetweenNotes = noteDuration * .14;
delay(pauseBetweenNotes);
noTone(4);
}
}
On the next step will will look at the code above in more detail.
Step 10: Arduino Sketch Picked Apart
/*
* Version M 2.5
* For ATTiny85 16Mhz
*/
#include "pitches.h"
int melody[] = {int melody[] = {
This line includes the pitch tab into the code. The pitch.h tab contains the different pitch - we will call them "NOTE" from now on.
NOTE_F7, NOTE_G4, NOTE_A2};
int noteDurations[] = { 9,12,7 };int noteDurations[] = { 9,12,7 };
This array “melody” holds the notes that will be played and the order they will be played in. I experimented with 2 to 5 notes. For my project i felt 3 notes made a good warble or chirping noise for the sonics i was making. I had a musician buddy analyze the real sound from the TV show and he told me the predominant note was in the G scale. Please mess with this array by adding and removing notes, changing the notes and arranging the order until you get the sound that you like.
int x = 0;int x = 0;
Note duration. Musical notes are typically full note, half note, quarter note, and 8th note. This is represented in the code as 1,2,4,8 meaning 1 second divided by 1,2,4, or 8. However, we are not making music. We are making a warbly, chirpy noise. So I played with non-conventional note durations like notes durations 1/15th of a second long or 1/6th or 1/12th. The array “noteDuration” below states that NOTE_F7 will be played at 1/9th duration, NOTE_G4 plays for 1/12th, and NOTE_A2 at 1/7th. A note duration must be specified for each note in the “melody” array. Play with noteDuration to get the right rhythm for your sonic.
int led1 = 3;int led1 = 3;
This is just a variable to be used as a counter
int led2 = 2;
void setup() {
pinMode (led1, OUTPUT);
pinMode (led2, OUTPUT);
}
This two variables define the pin numbers for our LED output. If you really wanted to you can add two more LEDs since not all the pins on the ATTiny85 is being used. But I think two is enough.
void loop() {
Main loop. With each run through the main loop, only ONE note is played at the specified duration followed by a pause (more on pauses below).;
}
This section defines the LED blink pattern. Use any logic you like to make the blink pattern you like. Mine uses “x” as a counter with a range of 0-10. At the lower range LED1 is on and LED2 is off. Then in the middle range of “x” Both LEDs are on. At the upper range of “x” LED1 is OFF and LED2 is on.
for (int thisNote = 0; thisNote < 3; thisNote++) {
int noteDuration = 1000/noteDurations[thisNote];
The above code goes through and plays the notes in the melody array one note at a time. The part where it states “thisNote < 3” the value must equal the number of notes in the array. So if "melody" has four notes then "thisNote<4". The rest of the code figures out the note duration in milliseconds.
tone(4, melody[thisNote],noteDuration);
This is where the tone is actually outputed to the speaker. In this example the output is on pin 4.
int pauseBetweenNotes = noteDuration * .14;
delay(pauseBetweenNotes);
noTone(4);
A pause between notes has to be inserted otherwise the notes run together and it sounds like a bad screeching noise. The pause duration cannot be a fixed amount of time (like 1/4 second between each note) but must be based on the note duration to sound right. The code below sets the pause time as a percentage of the note duration. Play with the decimal value to get a good pause time between notes. I found a value between .09-.21 to be a good amount of pause. The last line "noTone(4)" turns off the output to pin 4.
}
}
END of code
Step 11: Circuit Board
Attached is the circuit board I made to hold the ATTiny85.
The file was made on CamBam. My PCBs where mechanically etched using an CNC router. Chemical etching would probably be easier.
Also attached is RAR file called "EagleFilesAndSchematics" which has the Eagle files and as well as the PDF for a two layer board layout ( BOARD2.pdf) and the schematics ( SCH2.pdf) pictured above.
Please download those if you are used to using Eagle for electronics design.
I had an electrical engineer with decades of experience look over my design and confirm it is sound. He designed the schematics for me on Eagle. He did make a change to my design in that the schematic has the switch attached to the POSITIVE terminal of the battery to complete the circuit to 8th leg of the ATTiny85 (VCC). Also his PCB design is double-sided. Both PCBs are 0.5 inch by 1.5 inch.
The PCB can be made to fit inside the inner sleeve. If the PCB design is too large, let me know and I can shrink it down some more. The only limitation is the size of the ATTiny85 itself.
Here is the Datasheet for the ATTiny85:
Please pay a lot of attention to the ATTiny85 datasheet "Pinout" diagram. The physical legs are NOT corresponding to the pinout numbers. That is PIN 2 is NOT LEG 2 on the DIP chip. The pinout mapping is as follows:
PIN1 = leg6
PIN2 = leg7
PIN3 = leg2
PIN4 = leg3
Leg 4 is GROUND
Leg 8 is VCC (positive to battery)
Here is a video of me making a PCB mechanically:
The PCB etching is mirrored because the chip and most of the components will be on the back side of the PCB. This is why the "1" is backwards.
Step 12: Solder the Components
Use a good soldering iron to solder all the components to the PCB. Save the LEDs for last. Perhaps, don’t solder the LED’s until you know their final position and know how you are going to route the wires.
Please do not linger on the ATTiny85 legs. Use a real hot iron and a solder that flows well. Touch on each leg as briefly as possible. It may even be a good idea to take a break after soldering 4 legs, let the chip cool down then solder the rest. It would be sad if you get the ATTiny85 all programmed and working on a breadboard only to burn it up once it is permanently soldered to the PCB.
Apply power and make sure you have lights and sound.
I could not figure out how to make a battery holder in such a confined space. My solution was to shrink wrap four batteries together and attach the wires to the end. The wires are held in place with tightly wrapped electric tape.
Test fit the PCB to make sure the tactile switch is underneath and centered on the sliding switch assembly. If you are sure about the fit and function of the PCB, apply a small amount of epoxy on the edge of the PCB and slide it into place inside the inner sleeve. Let the glue set.
Step 13: Final Assembly
Put everything together and take pictures. Enjoy saving worlds and history with your very own sonic screwdriver.
The two i made were given away as gifts. They were received with great joy and much surprise. The effort that went into this project was well worth it on seeing their reactions. I also made a gift box for it.
and now, another video:
Runner Up in the
Epilog Challenge V
131 Discussions
2 years ago
Hi Mr Tinkerer
Just wondering if you are still making
The sonic screwdriver i'm keen to buy one if you can let me know my email is Dan-1@live.com.au thanks mate
Reply 2 years ago
I am trying to find time to actually start making these again. I have just been real busy.
3 years ago
is there and easier and cheaper way to make this? if so, make another post plz?
Reply 3 years ago
Hello,
Ways to make it cheaper:
1. Use plastic instead of metal
2. Use hand tools instead of power tools and shop tools.
3. used preformed parts and found objects instead of custom making parts.
That's about all I can think of to make it cheaper.
Reply 3 years ago
thanks, I'm guns try it out now! I appreate it! FOR WHOVIANS!
3 years ago
do you know what type of resistors you used on the testing board if you do then can you tell me the colors on it?
Reply 3 years ago
the resistors are for LED's. The resistance value is determined by the type of LED you are using. So the value of the resistor is dependent on what you are using. There are many LED resistance calculators on the web. Google "LED resistor calculator" and use the one that you feel comfortable with. Some even show you the color code of the resistor.
5 years ago on Introduction
could you sell me one? contact me for info and other things!
Reply 5 years ago on Introduction
PLEASE? i could buy it for about $20?!
Reply 5 years ago on Introduction
I am trying to make some now. No, it will not be $20, sorry.
Reply 3 years ago
I realize this message is 3 years old, but seriously, $20?? People just have no idea what it takes to actually make something with their hands. They're so used to cheap plastic knock-offs that their standards are completely skewed.
These items ended up selling on Ebay for over $200 and worth every penny.
Reply 3 years ago
i sold 5. The very last one on ebay the winning bid was past $500. I think $149 for one of my creations is not unreasonable.
After material cost, my hourly wage after selling one for $149 is roughly $4.50 per hour for each sonic screwdriver. Well below minimum wage.
3 years ago
Do you have drawings that you went off of, or did you just wing it? If you have drawings that you wouldn't mind sharing, I could make some 3D models of the metal pieces for a 3D printer.
Reply 3 years ago
Sorry, no drawings that I kept. I did sketch some rough ideas on scratch paper, did some dimension calculations but I did not keep any of it. Sorry.
3 years ago
Making the Sonic Screwdriver out of metal is a bit of work. You can try using plastic which is easer to work with, then cover it with plating or just paint. I wonder how BBC did the units that the real Dr.Who uses on the show.
Reply 3 years ago
Actually it's just as easy to machine aluminum on a lathe as it is plastic, and plastic is probably more expensive if you use something that's high density. Also, I think for an item like this the "heft" of metal is part of the attraction.
3 years ago
also, about how big is it?
Reply 3 years ago
outside diameter of body is about .75" (19mm). inside diameter is about .6" (15.5mm). Over all length retracted to 6.5" (16.5cm), extended 7.5" (19cm). There is not much room inside.
3 years ago
Do you think I could buy just the outside? I can't afford the tools, but i wanted to make a tv remote out of it
Reply 3 years ago
Sorry, i currently do not have time to make more. | https://www.instructables.com/id/Metal-Doctor-Who-Sonic-Screwdriver-with-Arduino/ | CC-MAIN-2019-26 | refinedweb | 4,984 | 83.15 |
FileInfo.AppendText Method
.NET Framework 4.5
Creates a StreamWriter that appends text to the file represented by this instance of the FileInfo.
Namespace: System.IONamespace: System.IO
Assembly: mscorlib (in mscorlib.dll)
The following example appends text to a file and reads from the file.
using System; using System.IO; class Test { public static void Main() { FileInfo fi = new FileInfo(@"c:\MyTest.txt"); // This text is added only once to the file. if (!fi.Exists) { //Create a file to write to. using (StreamWriter sw = fi.CreateText()) { sw.WriteLine("Hello"); sw.WriteLine("And"); sw.WriteLine("Welcome"); } } // This text will always be added, making the file longer over time // if it is not deleted. using (StreamWriter sw = fi.AppendText()) { sw.WriteLine("This"); sw.WriteLine("is Extra"); sw.WriteLine("Text"); } //Open the file to read from. using (StreamReader sr = fi.OpenText()) { string s = ""; while ((s = sr.ReadLine()) != null) { Console.WriteLine(s); } } } } //This code produces output similar to the following; //results may vary based on the computer/file structure/etc.: // //Hello //And //Welcome //This //is Extra //Text //When you run this application a second time, you will see the following output: // //Hello //And //Welcome //This //is Extra //Text //This //is Extra //Text
The following example demonstrates appending text to the end of a file and also displays the result of the append operation to the console. The first time this routine is called, the file is created if it does not exist. After that, the specified text is appended to the file.
using System; using System.IO; public class AppendTextTest { public static void Main() {. // Remember that the file might have other lines if it already existed....
- FileIOPermission
for reading and appending to files. Associated enumerations: FileIOPermissionAccess.Read, FileIOPermissionAccess.Append
Show: | https://msdn.microsoft.com/en-us/library/system.io.fileinfo.appendtext.aspx | CC-MAIN-2015-18 | refinedweb | 287 | 52.26 |
Wiki
SCons / SconsVersion
The SCons wiki has moved to
How to retrieve the version of SCons from your script ?
Ah! We don't really have a defined, public interface for this. We should have. In the meantime, you can use:
import SCons print SCons.__version__
(Where, of course, you can do whatever you like with the
SCons.__version__ string, not just print it.)
If you are looking to ensure a certain version of SCons, use:
EnsureSConsVersion()
For example, using
EnsureSConsVersion(0, 96, 93) will exit SCons with an appropriate error message if the version of SCons is not at least 0.96.93
Credits: StevenKnight, TaybinRutkin
Updated | https://bitbucket.org/scons/scons/wiki/SconsVersion?action=AttachFile | CC-MAIN-2018-17 | refinedweb | 107 | 75.61 |
Recently when I started to use for-comprehensions with monadic structures like Task a lot, I've noticed that this is not a valid Scala syntax
def app: Task[Unit] =
for {
implicit foo <- createFoo
implicit bar = createBarWithImplicitFoo
_ <- runWithImplicitBar
} yield ()
How hard would it be to make this valid Scala code?Desugared version should look like this (and it compiles just fine)
createFoo.flatMap { implicit foo =>
createBarWithImplicitFoo
}.flatMap { implicit bar =>
runWithImplicitBar
} (dates back to an era when the bug tracker was a mix of bugs and feature requests)
Oh, I see, there are so many issues linked I've lost a track. What blocks this feature from merging?
the story so far seems to end in the comments on
Actually, this is stuck because it requires a SIP and it's missing a SIP champion. More details on. | https://contributors.scala-lang.org/t/implicit-keyword-in-lhs-of-for-comprehension/725 | CC-MAIN-2017-43 | refinedweb | 138 | 60.95 |
I checked out tomcat from the HEAD and found the following information in
the WebAppClassloader:
I see now that the WebAppClassLoader does "intend" to have a cache for the
loaded Resources (some day).
---- code snip ----
WebappClassLoader - Line 1211
...
// (0) Check for a cached copy of this resource
stream = findLoadedResource(name);
...
---- code snip ----
It does this by examining the ResourcEntry(s) in the resourceEntries Hashmap
and checking binaryContent (null vs not null).
---- code snip ----
WebappClassLoader - Line 1898
...
/**
* Finds the resource with the given name if it has previously been
* loaded and cached by this class loader, and return an input stream
* to the resource data. If this resource has not been cached, return
* <code>null</code>.
*
* @param name Name of the resource to return
*/
protected InputStream findLoadedResource(String name) {
ResourceEntry entry = (ResourceEntry) resourceEntries.get(name);
if (entry != null) {
if (entry.binaryContent != null)
return new ByteArrayInputStream(entry.binaryContent);
}
return (null);
}
}
...
---- code snip ----
But, there is no caching going on when the resources are loaded. So, the
code is executing with no purpose? Matter of fact the code has //FIX ME
cache??? statements intermingled with the ClassLoader delegation.
---- code snip ----
WebappClassLoader - Line 1219
...
// (1) Delegate to parent if requested
if (delegate) {
if (debug >= 3)
log(" Delegating to parent classloader");
ClassLoader loader = parent;
if (loader == null)
loader = system;
stream = loader.getResourceAsStream(name);
if (stream != null) {
// FIXME - cache???
if (debug >= 2)
log(" --> Returning stream from parent");
return (stream);
}
}
// (2) Search local repositories
if (debug >= 3)
log(" Searching local repositories");
URL url = findResource(name);
if (url != null) {
// FIXME - cache???
if (debug >= 2)
log(" --> Returning stream from local");
stream = findLoadedResource(name);
try {
if (hasExternalRepositories && (stream == null))
stream = url.openStream();
} catch (IOException e) {
; // Ignore
}
if (stream != null)
return (stream);
}
// (3) Delegate to parent unconditionally
if (!delegate) {
if (debug >= 3)
log(" Delegating to parent classloader");
ClassLoader loader = parent;
if (loader == null)
loader = system;
stream = loader.getResourceAsStream(name);
if (stream != null) {
// FIXME - cache???
if (debug >= 2)
log(" --> Returning stream from parent");
return (stream);
}
}
// (4) Resource was not found
if (debug >= 2)
log(" --> Resource not found, returning null");
return (null);
...
---- code snip ---
So there are three things that I can conclude as a result of seeing this
code.
1) My getResourceAsStream loading problems are NOT caused by Tomcat because
Tomcat is grabbing the resource fresh each time.
2) Resource caching still needs to be implemented in Tomcat
3) The caching check in Tomcat does not check resource Timestamps. So, even
if the cache was working it would not reload resources upon file changes.
(only binaryContent is being checked. eg null or not null).
Are my observations correct?
Brandon Goodin
-----Original Message-----
From: Shapira, Yoav [mailto:Yoav.Shapira@mpi.com]
Sent: Thursday, June 05, 2003 12:49 PM
To: Tomcat Users List
Subject: RE: [SOLVED]RE: getResourceAsStream cached by Tomcat's
Classloader?
How unit. | http://mail-archives.apache.org/mod_mbox/tomcat-users/200306.mbox/%3CMCEFJGLDHNNMPENCIDECKEGLFLAA.mail@phase.ws%3E | CC-MAIN-2015-18 | refinedweb | 462 | 59.8 |
<ac:macro ac:<ac:plain-text-body><![CDATA[
Ajax Helper should provide methods to build Ajax Requests using the jQuery Helper.
Zend Framework: ZendX_JQuery_View_Helper_JQuery Component Proposal
Table of Contents
1. Overview
2. References
3. Component Requirements, Constraints, and Acceptance Criteria
helper allows to simplify the setup of an enviroment that uses jQuery as Javascript library and provides the possibilty to construct a wide range of ajax calls.
- MUST be a single view helper with multiple methods
- MUST be able to render as string
- MUST support direct deployment via CDN (Google Ajax Library API), using specified version
- MUST support using local install, via path
- SHOULD default to CDN if no path specified
- MUST have method for requiring plugin files (js and css)
- SHOULD be base component for further jQuery Plugins that use its infrastructure methods
The jQuery Ajax Helper should provide methods to build Ajax Requests using the jQuery Helper.
- MUST integrate with jQuery Library to append requests to onLoad Event.
- MUST add value to simply using jQuery Ajax Requests (Auto building most wanted callbacks)
- SHOULD allow inlining Javascript, but MUST default to stack Javascript to onLoad
4. Dependencies on Other Framework Components
- Zend_View_Exception
- Zend_Json
5. Theory of Operation
Theory of Operation:
Using the jQuery Helper enables one to setup an jQuery enviroment in a ZF MVC implementation very fast, specifing helper methods to include jQuery Javascript Files and additional plugin requirements.
The jQuery Link Helper allows to construct simple ajax calls from within a view template. The following call signature is proposed:
6. Milestones / Tasks
- Milestone 1: Finish First Proposal [DONE]
- Milestone 2: Community Review [DONE]
- Milestone 3: Finish First Implementation DONE (SVN:)
- Milestone 4: Complete Unit Test Coverage [DONE]
- Milestone 5: Finish Component
- Milestone 6: Documentation
7. Class Index
- ZendX_JQuery
- ZendX_JQuery_View_Helper_JQuery
- ZendX_JQuery_View_Helper_JqLink
8. Use Cases
results to:
additional line in jquery onLoad (See jQuery Helper addOnLoad()):
results to:
results to:
Leads to a jQuery onLoad Code of:
This loads jQuery and jQuery UI from Googles CDN and adds an onLoad
effect that highlights #test on clicking '.highlightTest':
26 Commentscomments.show.hide
Jul 14, 2008
Benjamin Eberlei
<p>On the problem of the jQuery Plugin architecture i have already written two entries on my blog:</p>
<p><a class="external-link" href=""></a>
<a class="external-link" href=""></a></p>
<p>and the question is, how a ZF jQuery component could support additional components like the jQuery<br />
UI Library, Zend_JQuery_Form that uses a jQuery plugin or a jQuery Autocomplete View Helper. All<br />
of which would need additional downloads of JS and Stylesheets (No CDN available). They would<br />
add lots of additional value to people who want to construct ZF MVC projects with ajax support<br />
in a fast way with no direct concerns about the javascript overhead (But: Refactoring all the auto-build code is supported of course).</p>
<p>Because of the complexity of jQuery requirements (when deadling with additions) I included lots of<br />
helper methods that cope with this problem, deadling with js and css include directory, adding<br />
js and css files. All this stuff will be built into HTML markup, when <?php echo $this->jQuery(); ?> is called. I don't use headScript() and headStyle() for the same reasons as Matthew did not in his Dojo proposal, to group all the jQuery stuff together and make it independant, allowing for specific disabling of all the jQuery output, when refactoring occured.</p>
<p>Additionally I have also tested around a little bit already and have implementations of the DatePicker and Autocomplete components working that depend on a first jQuery View Helper implementation. They require the additional includes and stylesheets I talked about, so I won't add them to the proposal just yet.</p>
Jul 14, 2008
Cristian Bichis
<p>Congrats for idea and for work on this component. jQuery is a must to for ZF since jQuery is highly used by developers...</p>
Jul 15, 2008
Jean-Marc Fontaine
<p>A jQuery view helper will be a great addition to the Zend Framework since many of its user, including me, use this library. Thank you!</p>
Jul 15, 2008
Matthew Weier O'Phinney
<p>A few notes, based on the dojo version: please try and mimic the dojo method names as much as possible so that we can start determining what might be put into an abstract class and/or interface. For example:</p>
<ul>
<li>setLibraryPath() -> setLocalPath() (this one also better encapsulates the distinction between a <em>remote</em> CDN resource vs. a <em>local</em> resource)</li>
<li>addStyleSheet() -> addStylesheet() (same goes for the get variant)</li>
</ul>
<p>I'd also recommend extending the new Zend_View_Helper_Abstract, which will negate the need for the setView() method. (note to self: must do this for the dojo() helper as well!)</p>
<p>Additionally, I'll just get this out of the way now: start using the ZendX prefix. We've already determined and publically stated that any JS toolkits outside of Dojo will be in the extras library. As such, you should show a use case indicating how you would attach the view helper to the view object ($view->addHelperPath('ZendX/View/Helper/', 'ZendX_View_Helper')).</p>
<p>Finally, do you think it likely that there would be additional jQuery components outside the view helpers at any point? If so, I'm going to recommend using a top-level namespace: ZendX_JQuery. The rationales are that it keeps all jQuery components grouped, making them easy to locate in the tree; it promotes encapsulation; and it promotes the idea of use-at-will.</p>
<p>Nice work, and ping me if you have any questions or would like help with identifying abstraction points (for a generic JS view helper interface or abstract class).</p>
Jul 15, 2008
Benjamin Eberlei
<p>Thanks for the feedback. I will add all the changes to the method body tonight. Also i will claim ZendX_Jquery then. (or can it be JQuery? ZF Coding Standards Puzzle me on this specific application of the CamelCase rule).</p>
<p>Additional components are possible, ajaxForm, Autocomplete and such stuff. But at first i plan to implement this Helper and the basic jQuery Ajax Functionality and then maybe extend the functonality to include additional features.</p>
Jul 15, 2008
Matthew Weier O'Phinney
<p>We discussed CamelCasing yesterday internally, and I made the case that it's confusing to users when our CamelCasing rules conflict with known standard names. The one caveat is that the first letter following an underscore <em>always</em> has to be Uppercase to ensure class name lookups will work.</p>
<p>So, short answer: JQuery as a classname segment is fine.</p>
<p>Looking forward to seeing what other features you propose later!</p>
Jul 16, 2008
Joó Ádám
<p>Please consider the above: personally, I really like that I don't have to know or think upon the name of a component, just the rules. ZendX_Jquery would be a better choice.</p>
Jul 16, 2008
Matthew Weier O'Phinney
<p>The library is called jQuery, and jQuery users are used to seeing the capital Q. This is also true of services like OpenID and OAuth. It's more confusing to have a disconnect between the widely know and accepted name and how it is named internally in ZF.</p>
Jul 17, 2008
Matthew Ratzloff
<p>I will always value a single convention over different rules based on context, but I can see Matthew's argument here as well. I do think this is something probably best left to the community. Also, the framework should have consistent naming rules for method names as well. So, for example, isXmlHttpRequest() would become isXMLHttpRequest() instead.</p>
Jul 16, 2008
Benjamin Eberlei
<p>From the way jQuery is written I have to stick with JQuery as class names. As an application developer you propably won't come accross calling the class anyways, except in your layout view to output the collected onLoad/include statements. The jQuery helper is really just a helper to bundle all jQuery-releated helpers required output together.</p>
<p>If sticking to ZF conventions you might even only have to implement some derivation of UC-00 and UC-01. The helpers like jqLink are good to go then. The real importance comes when you want to build your own helper, see UC-02 for that.</p>
Jul 15, 2008
Bryce Lohr
<p>The use cases are a bit too abstract to see how this helper will actually be used in real application code. Is the idea to place calls to the methods such as <code>addJavascriptFile()</code> and <code>addStyleSheet()</code> in view scripts for specific controllers, and then place a single call to <code>jQuery()</code> in the head of the layout? I think fleshing out the examples will clarify this.</p>
<p>Also, how would you go about configuring things such as the library path, etc. just once (in some central place, such as the bootstrap or a plugin), or is this concern not even applicable?</p>
Jul 15, 2008
Benjamin Eberlei
<p>You're right, the UC are to abstract. I will refine them tonight.</p>
<p>The calls to addJavascriptfile and addStylesheet are supposed to be called in addional helpers that facilitate the jQuery Helper. For example if you write your own View Helper that uses jQuery, you can make sure that the appropriate additional javascript libraries are loaded.</p>
<p>One central place to define the paths and directory variables is recommended. I can clarify this in an additional Use Case.</p>
Jul 15, 2008
Benjamin Eberlei
<p>I have incorporated Bryces and Matthews suggestions into the proposal. For anyone who has already seen the uses cases, please re-look at Use Cases 00, 01 and 02.</p>
<p>@Bryce: The new UC-02 clarifies your questions about calling addJavascriptFile() and addStylesheet().</p>
<p>@Matthew: UC-00 shows how to initialize the jQuery Helper using addHelperPath().</p>
Jul 17, 2008
Bryce Lohr
<p>The updated use cases are clearer, thank you!</p>
Jul 15, 2008
Vladimir Michailenko
<p>Maybe these links will be helpfull:
<a class="external-link" href=""></a>
<a class="external-link" href=""></a></p>
Jul 15, 2008
Till Klampaeckel
<p>Good to see that someone is working on this.</p>
<p>A small suggestion, please try to replace private with protected. private visibility is really limited to your helper otherwise. If I extended your helper, I couldn't access private methods and variables.</p>
Jul 15, 2008
Benjamin Eberlei
<p>You are right. I've already done this. Thanks for the suggestion.</p>
Jul 15, 2008
Benjamin Eberlei
<p>Question to all the jQuery people, would you like to have an infrastructure helper for the jQuery Events? Or should this be left out for further extensions of the component so far? I want to push the component to 1.7 which will be released soon after 1.6, so maybe there shouldn't be too much fucntionality in this proposal just yet to get it through the process?</p>
<p>That would be a helper that can be included in more practical helpers like the first proposed practical helper "jqLink" or any future implementations may they be called jqForm, jqAutocomplete, jqDatePicker (NOT included in this proposal) and so on to register/inject global and local ajax events or the common javascript events like onClick, onSubmit and so on into the ZendX_JQuery_View_Helper_JQuery::addOnLoad method.</p>
<p>Also, what are your suggestions on the jqLink() method header, escpecilly the $options Array. Are default effects like loading, flashing, disabling (or any others) on the wishlist?</p>
Jul 16, 2008
Joó Ádám
<p>'inline' True or false, wheater to inline the javascript in onClick="" atttribute or append it to jQuery onLoad Stack.</p>
<p><promotingBestPractices></p>
<p>I would suggest not to have the ability of using inline JavaScript.</p>
<p></promotingBestPractices></p>
Jul 16, 2008
Till Klampaeckel
<p>I second this (I think), no inline JS rather have jquery assign it all by itself.</p>
Jul 16, 2008
Benjamin Eberlei
<p>I dont like inline JS aswell, but someone might. Since the difference between inline or onLoad/grouped javascript ist in my opinion just a small difference and not at all something you have to restrict, I leave it in as optional argument. Also the documentation will provide hints why not to use inline javascript and what difficulties might occur (escaping).</p>
Jul 17, 2008
Till Klampaeckel
<p>People like all kinds of things, but I think "inline" is not best practice, and the component should adhere to that. At least IMHO. <ac:emoticon ac:</p>
Aug 08, 2008
Marcus Welz
<p>I agree that best practice is not having inline JavaScript code.</p>
<p>Consider these scenarios:</p>
<p>1. Inline JavaScript, for instance an anchor with onclick attribute, will be clickable before the page has finished loading, but it may attempt to trigger code that has yet to initialize or otherwise result in an error.</p>
<p>2. At the same time, there may be situations where you'd want to inline something, simply because you want it to be clickable before the page has finished loading completely. That could be the case if a page has lots of images and/or third party integration that results in the page being visible and (to the visitor) usable, but is not yet fully loaded.</p>
<p>So I agree with Benjamin and think it would be worth having the flexibility to generate either, but to default to what most would consider best practice; onload/grouped javascript.</p>
<p>The flexibility and loosely-coupled nature of the Zend Framework is what makes it so attractive.</p>
Aug 15, 2008
Benjamin Eberlei
<p>Thank you all for the feedback, i have finished a new version of the component (see SVN <a class="external-link" href=""></a>) and integrated all your thoughts as good as possible. Open Questions (to me) are now:</p>
<p>1.) Should jqLink be renamed to something more insightful? jurl? (like url Helper), or jLink or something?</p>
<p>2.) Should jqLink use the Url helper as parent class? Or should it be standalone? (Not inheriting the MVC route match of the Url helper).</p>
<p>3.) Its the $options array layout "ok"? or are there any thoughts? (See Point 5 Theory of Operation with jqLink DocComment)</p>
<p>I move this proposal to the next stage now, since this are questions that are more likely to match the later proposal stages.</p>
Aug 17, 2008
Benjamin Eberlei
<p>i am sorry, i had to change the proposal at this late stage to include the functions for the jQuery UI library, that are needed to integrate the jQuery UI library smoothly.</p>
<p>I also added the docblocks I have for all the functions to clarify the functionality.</p>
Sep 04, 2008
Matthew Weier O'Phinney
<ac:macro ac:<ac:parameter ac:Zend Comments</ac:parameter><ac:rich-text-body>
<p>This proposal is approved for immediate development in the extras/incubator, with the following feedback:</p>
<ul>
<li>Please include a Zend_JQuery class with enableView() and enableForm() static methods for setting up appropriate plugin paths in those objects (as a convenience feature)<br />
We are very pleased with this proposal and how closely it mirrors Zend_Dojo; it will serve as an excellent blueprint for additional JS offerings in the future.</li>
</ul>
</ac:rich-text-body></ac:macro> | http://framework.zend.com/wiki/display/ZFPROP/ZendX_JQuery_View_Helper_JQuery+-+Benjamin+Eberlei?focusedCommentId=5112320 | CC-MAIN-2014-10 | refinedweb | 2,584 | 60.55 |
Iterating a dictionary key value and averaging with known count
As a beginner in python,Im still trying to grasp the concept of dictionary count/loops better. So i've created a sample data to get my question across clearly. Below i have an unordered list of dictionaries containing the revenue information of a few shops. My question is, how do i get the average revenue of each shop - based on the count of reported revenue, reported by these shops?
#Given data revenue_list_of_dictionaries: [{'shop_ID': 1, 'revenue': 15000}, {'shop_ID': 2, 'revenue': 12000}, {'shop_ID': 1, 'revenue': 8500}, {'shop_ID': 3, 'revenue': 5000} {'shop_ID': 1, 'revenue': 3500}] data = revenue_list_of_dictionaries result = {} # Executing code to find total revenue for each shop ID for revenue_list in data: shop_ID = revenue_list['shop_ID'] revenue_per_month = revenue_list['revenue'] if shop_ID not in result: result[shop_ID] = revenue_per_month else: result[shop_ID] += revenue_per_month
Running the code above will give me:
{'1':27000, '2':12000, '3':5000}
Based on each shop reporting count:
{'1':3, '2':1, '3':1}
How do i find the average of each revenue reported so that my output will return the following:
{'1': 9000, '2': 12000, '3': 5000}
If the total revenue is called
a and the count
b and they both have the same keys (which they have to), you can use a dict comprehension to calculate the average revenue
c:
c = {key: value/b[key] for key, value in a.items()}
Counting the Number of keywords in a dictionary in python, How do you count the number of items in a dictionary? How to Iterate Through a Dictionary in Python: The Basics. Dictionaries are an useful and widely used data structure in Python. As a Python coder, you’ll often be in situations where you’ll need to iterate through a dictionary in Python, while you perform some actions on its key-value pairs.
If you want to manipulate your current approach to work, then user8408080's approach will work just fine.
Otherwise, as mentioned in the comments by @Chris_Rands, you can collect the revenues with a
collections.defaultdict(), storing them as lists, then calculate the mean at the end:
from collections import defaultdict from statistics import mean revenues = [ {"shop_ID": 1, "revenue": 15000}, {"shop_ID": 2, "revenue": 12000}, {"shop_ID": 1, "revenue": 8500}, {"shop_ID": 3, "revenue": 5000}, {"shop_ID": 1, "revenue": 3500}, ] counts = defaultdict(list) for revenue in revenues: counts[revenue['shop_ID']].append(revenue['revenue']) print({k: mean(v) for k, v in counts.items()}) # {1: 9000, 2: 12000, 3: 5000}
You could also have a
collections.defaultdict() of
collections.Counter(), and store the revenues and counts simultaneously:
from collections import defaultdict from collections import Counter revenues = [ {"shop_ID": 1, "revenue": 15000}, {"shop_ID": 2, "revenue": 12000}, {"shop_ID": 1, "revenue": 8500}, {"shop_ID": 3, "revenue": 5000}, {"shop_ID": 1, "revenue": 3500}, ] counts = defaultdict(Counter) for revenue in revenues: shp, rev = revenue['shop_ID'], revenue['revenue'] counts[shp]['revenue'] += rev counts[shp]['count'] += 1 print({k: v['revenue'] / v['count'] for k, v in counts.items()}) # {1: 9000.0, 2: 12000.0, 3: 5000.0}
Note: In the first example I used
statistic.median() to calculate the mean. You can also use
sum(v) / len(v) if you want to.
Which method in a dictionary object gives you a list of the values in , works, and is faster than building an iterator, d. In this post, we will discuss how to iterate over a dictionary in C#. 1. foreach loop We can loop through all KeyValuePair<K,V>> in the dictionary and print the corresponding Key and Value from each pair. [crayon-5ed501105c2db363924910/] We can also iterate over the collection of keys and fetch the value using the …
You can do it without python packages, as follows:
result = {} CountList = [] for dic in revenue_list_of_dictionaries: result.setdefault(dic.values()[0], 0) result[dic.values()[0]] += dic.values()[1] CountList.append(dic.values()[0]) #returning an average of all shop_Id revenues for k, value in result.items(): result[k] = value/CountList.count(k) print result #{1: 9000, 2: 12000, 3: 5000}
Python - can a dict have a value that is a list?, Which method in a dictionary object gives you a list of the values in the dictionary? This dictionary has 4 key-value pairs. The first key-value pair is age:24. The second key-value pair is height:170cm. The third key-value pair is weight:170lbs The fouth key-value pair is gender:male However, we write code just to get the keys of this dictionary. So we create a for loop that goes through all of the keys of this dictionary, Gregory.
Python, How do you add a key value pair to a dictionary? Key : three , Value : 3. Key : four , Value : 4. Key : one , Value : 1 Key : two , Value : 2 Key : three , Value : 3 Key : four , Value : 4. Key : one , Value : 1 Key : two , Value : 2 Key : three , Value : 3 Key : four , Value : 4. As you can see that all keys and values are printed out.
Python, This problem can be solved using naive method of loop. In this we just iterate through each key in dictionary and when a match is found, the counter is increased Our profilin gDictionary variable contains 11,998,949 Key-Value records. The three most popular way of iterating over Dictionary variables in your C# program are discussed below: Method 1 (for loop, not foreach iteration)
python iterate dictionary key value Code Example, Python | Count number of items in a dictionary value that is a list Dictionaries are written with curly brackets, and they have keys and values. It return a boolean whether the object is an instance of the given class or not. Python | Delete items from dictionary while iterating · Python - Sorted order Dictionary items pairing Python | Increment value in dictionary Sometimes, while working with dictionaries, we can have a use-case in which we require to increment a particular key’s value in dictionary. It may seem a quite straight forward problem, but catch comes when the existence of a key is not known, hence becomes a 2 step process at times. | http://thetopsites.net/article/53376997.shtml | CC-MAIN-2020-34 | refinedweb | 1,003 | 60.55 |
The method
split() is used for splitting a String into its substrings based on the given delimiter/regular expression. This method has two variants:
String[] split(String regex): It returns an array of strings after splitting an input String based on the delimiting regular expression.
String[] split(String regex, int limit): The only difference between above variation and this one is that it limits the number of strings returned after split up. For e.g.
split("anydelimiter", 3) would return the array of only 3 strings even through the delimiter is present in the string more than 3 times. If the limit is negative then the returned array would be having as many substrings as possible however when the limit is zero then the returned array would be having all the substrings excluding the trailing empty Strings.
It throws
PatternSyntaxException if the syntax of specified regular expression is not valid.
Example: split() method
public class SplitExample{ public static void main(String args[]){ String str = new String("28/12/2013"); System.out.println("split(String regex):"); String array1[]= str.split("/"); for (String temp: array1){ System.out.println(temp); } System.out.println("split(String regex, int limit) with limit=2:"); String array2[]= str.split("/", 2); for (String temp: array2){ System.out.println(temp); } System.out.println("split(String regex, int limit) with limit=0:"); String array3[]= str.split("/", 0); for (String temp: array3){ System.out.println(temp); } System.out.println("split(String regex, int limit) with limit=-5:"); String array4[]= str.split("/", -5); for (String temp: array4){ System.out.println(temp); } } }
Output:
split(String regex): 28 12 2013 split(String regex, int limit) with limit=2: 28 12/2013 split(String regex, int limit) with limit=0: 28 12 2013 split(String regex, int limit) with limit=-5: 28 12 2013
In the above example split(“/”,0) and split(“/”,-5) returned same value however in some cases the result would be different. Lets see with the help of an example:
String s="bbaaccaa"; String arr1[]= s.split("a", -1); String arr2[]= s.split("a", 0);
In this case arr1 would be having {“bb”, ” “, “cc”, ” “, ” “} However arr2 would be having {“bb”, ” “, “cc”} because limit zero excludes trialing empty Strings. | http://beginnersbook.com/2013/12/java-string-split-method-example/ | CC-MAIN-2016-50 | refinedweb | 366 | 55.03 |
Join us for Code @ Think 2019 | San Francisco | February 12 – 15 Register now Limited availability
Article
By Venkat Subramaniam | Published February 15, 2017 - Updated February 24, 2017
Java
Java™ developers are well accustomed to imperative and object-oriented programming, as these styles have been supported by the Java language since its first release. In Java 8, we gained access to a set of powerful new functional features and syntax. Functional programming has been around for decades, and it’s generally more concise and expressive, less error prone, and easier to parallelize than object-oriented programming. So there are good reasons to introduce functional features into your Java programs. Still, programming in the functional style requires some changes in how you design your code.
Java 8 is the most significant update to the Java language since its inception — packed so full of new features that you might wonder where to start. In this series, author and educator Venkat Subramaniam offers an idiomatic approach to Java 8: short explorations that invite you to rethink the Java conventions you’ve come to take for granted, while gradually integrating new techniques and syntax into your programs.
I’ve found that thinking declaratively, rather than imperatively, can ease the transition to a more functional style of programming. In this first article in the new Java 8 idioms series, I explain the difference and overlap between imperative, declarative, and functional programming styles. Then, I show you how to use declarative thinking to gradually integrate functional techniques into your Java programs.
Developers trained in the imperative style of programming are accustomed to telling programs what to do, as well as how to do it. Here’s a simple example:
import java.util.*;
public class FindNemo {
public static void main(String[] args) {
List<String> names =
Arrays.asList("Dory", "Gill", "Bruce", "Nemo", "Darla", "Marlin", "Jacques");
findNemo(names);
}
public static void findNemo(List<String> names) {
boolean found = false;
for(String name : names) {
if(name.equals("Nemo")) {
found = true;
break;
}
}
if(found)
System.out.println("Found Nemo");
else
System.out.println("Sorry, Nemo not found");
}
}
The findNemo() method starts by initializing a mutable flag variable, also known as a garbage variable. Developers often give such variables throwaway names like f, t, or temp, conveying our general attitude that they shouldn’t exist. In this case, the variable is named found.
findNemo()
f
t
temp
found
Next, the program loops through one element at a time in the given names list. It checks whether the name at hand equals the value that it’s looking for, in this case, Nemo. If the value matches, it sets the flag to true and instructs the flow of control to “break” out of the loop.
names
Nemo
true
Because this is an imperative-style program — the most familiar style for many Java developers — you define every step of the program: you tell it to iterate over each element, compare the value, set the flag, and break out of the loop. The imperative style gives you full control, which is sometimes a good thing. On the other hand, you do all the work. In many cases, you could be more productive by doing less.
Declarative programming means that you still tell the program what to do, but you leave the implementation details to the underlying library of functions. Let’s see what happens when we rework the findNemo method from Listing 1 using the declarative style:
findNemo
public static void findNemo(List<String> names) {
if(names.contains("Nemo"))
System.out.println("Found Nemo");
else
System.out.println("Sorry, Nemo not found");
}
Note first that you don’t have any garbage variables in this version. You are also not wasting effort on looping through the collection. Instead, you let the built-in contains() method do the work. You’ve still told the program what to do — check whether the collection holds the value we’re seeking — but you’ve left the details to the underlying method.
contains()
In the imperative example, you controlled the iteration and the program did exactly as instructed. In the declarative version, you don’t care how the work happens, as long as it gets done. The implementation of contains() may vary, but as long as the result is what you expect, you are happy with that. Less effort to get the same result.
Training yourself to think in a declarative style will greatly ease your transition to functional programming in Java. The reason? The functional style builds on the declarative style. Thinking declaratively offers a gradual transition from imperative to functional programming.
While programming in a functional style is always declarative, simply using a declarative style doesn’t equate to functional programming. This is because functional programming combines declarative methods with higher order functions. Figure 1 visualizes the relationships between the imperative, declarative, and functional programming styles.
In Java, you pass objects to methods, create objects within methods, and return objects from methods. You can do the same with functions. That is, you can pass functions to methods, create functions within methods, and return functions from methods.
In this context, a method is part of a class — static or instance — but a function can be local to a method and cannot be intentionally associated with a class or an instance. A method or a function that can receive, create, or return a function is considered a higher order function.
Adopting a new programming style requires changing how you think about your programs. It’s a process that you can practice with simple examples, building up to more complex programs.
import java.util.*;
public class UseMap {
public static void main(String[] args) {
Map<String, Integer> pageVisits = new HashMap<>();
String page = "";
incrementPageVisit(pageVisits, page);
incrementPageVisit(pageVisits, page);
System.out.println(pageVisits.get(page));
}
public static void incrementPageVisit(Map<String, Integer> pageVisits, String page) {
if(!pageVisits.containsKey(page)) {
pageVisits.put(page, 0);
}
pageVisits.put(page, pageVisits.get(page) + 1);
}
}
In Listing 3, the main() function creates a HashMap that holds the number of page visits for a website. Meanwhile, the incrementPageVisit() method increases a count for each visit to the given page. We’ll focus on this method.
main()
HashMap
incrementPageVisit()
The incrementPageVisit() method is written in an imperative style: Its job is to increment a count for the given page, which it stores in the Map. The method doesn’t know if there’s already a count for the given page, so it first checks to see if a count exists. If not, it inserts a “0” as the count for that page. It then gets the count, increments it, and stores the new value in the Map.
Map
Thinking declaratively requires you to shift the design of this method from “how” to “what.” When the method incrementPageVisit() is called, you want to either initialize the count for the given page to 1 or increment the running value by one count. That’s the what.
Because you’re programming declaratively, the next step is to scan the JDK library for methods in the Map interface that can accomplish your goal — that is, you’re looking for a built-in method that knows how to accomplish your given task.
It turns out that the merge() method suits your purposes perfectly. Listing 4 uses your new declarative approach to modify the incrementPageVisit() method from Listing 3. In this case, however, you’re not just adopting a more declarative style by choosing a smarter method; because merge() is a higher order function, the new code is actually a good example of the functional style:
merge()
public static void incrementPageVisit(Map<String, Integer> pageVisits, String page) {
pageVisits.merge(page, 1, (oldValue, value) ‑> oldValue + value);
}
In Listing 4, page is passed as the first argument to merge(): the key whose value should be updated. The second argument serves as the initial value that will be given for that key if it doesn’t already exist in the Map (in this case, “1”). The third argument, a lambda expression, receives as parameters the current value in the map for the key and a variable holding the value passed as the second argument to merge. The lambda expression returns the sum of its parameters, in effect incrementing the count. (Editorial note: Thanks to IstvC!n KovC!cs for correcting an error in the code.)
page
Compare the single line of code in the incrementPageVisit() method in Listing 4 with the multiple lines of code from Listing 3. While the program in Listing 4 is an example of the functional style, thinking through the problem declaratively helped us make the leap.
You have much to gain from adopting functional techniques and syntax in your Java programs: the code is concise, more expressive, has fewer moving parts, is easier to parallelize, and is generally easier to understand than object-oriented code. The challenge is to change your thinking from the imperative style of programming — which is familiar to the vast majority of developers — to thinking declaratively.
While there’s nothing easy or straightforward about functional programming, you can take a big leap by learning to focus on what you want your programs to do, rather than how you want it done. By allowing the underlying library of functions to manage execution, you will gradually and intuitively get to know the higher order functions that are the building blocks of functional programming.
Conference
January 9, 2019
API ManagementBlockchain+
JavaJava Platform
Meetup
January 22, 2019
ContainersDatabases+
Back to top | https://developer.ibm.com/articles/j-java8idioms1/ | CC-MAIN-2019-04 | refinedweb | 1,574 | 52.6 |
ktrace - process tracing
Standard C Library (libc, -lc)
#include <sys/types.h>
#include <sys/ktrace.h>
int
ktrace(const char *tracefile, int ops, int trpoints, pid_t pid);
int
fktrace(int fd, int ops, int trpoints, pid_t pid);
The ktrace() function enables or disables tracing of one or more processes. parameter generate
much output).
KTRFAC_PSIG Trace posted signals.
KTRFAC_CSW Trace context switch points.
KTRFAC_EMUL Trace emulation changes. */
caddr_t ktr_buf;
};() translating
the pathname.
[EIO] An I/O error occurred while reading from or writing to
the file system.
kdump(1), ktrace(1)
A ktrace function call first appeared in 4.4BSD.
BSD June 4, 1993 BSD | https://nixdoc.net/man-pages/NetBSD/man2/ktrace.2.html | CC-MAIN-2021-39 | refinedweb | 104 | 71.31 |
creating index for xml files - XML
cases, more than one file may have same name. So, my index file would be like...creating index for xml files I would like to create an index file for xml files which exist in some directory.
Say, my xml file is like below
my question
my question "Write a C/C++ program to show the stored procedure PROCRESETMAIL" on database "USER_NOTIFY
my question - EJB
my question is it possiable to create web application using java beans & EJB's with out implementing Servlets and jsps in that java beans and EJB's
solve my question shortly
solve my question shortly <html>
<head>
<script>
function checkphoneNumber(number){
if(/[^\d ]/.test(number)){
alert('It should contain numbers [0-9] only!');
document.getElementById
z-index always on top
z-index always on top Hi,
How to make my div always on top using the z-index property?
Thanks
Hi,
You can use the following code:
.mydiv
{
z-index:9999;
}
Thanks
error:Parameter index out of range (1 > number of parameters, which is 0).
error:Parameter index out of range (1 > number of parameters, which is 0). my code:String org=request.getParameter("Org"); String desg... the ? (question mark) to assign a value. So edit your sql string as follows
clarify my question - Java Beginners
clarify my question Dear Sirs/Expert,
Thanks for writing back.
Yes. I want a page to use id of parents to do the search for the match.
So... the matching tutors to the parent.
I was telling you that my degree
index
question
question Sir ,
i have a starting trouble to start my search engine project , please help me to start my project , please send me some relevant java codes
QUESTION
QUESTION please atach java tutorial to my email
Hello Friend,
Please visit the following link:
Java Tutorial
Thanks
PHP Based Chatserver - Design concepts & design patterns
PHP Based Chatserver Hey i want to create a Chat server like this one : could someone plz tell me were can i get a chatserver
question
question Sir,
how to display web snippets for a perticular query
for eg:web snippets for apple
how to implement this concept in my java project
please help me
question
question i am using this code in my project
response.sendRedirect("LoginForm1.jsp?msg=Username or Password is incorrect!");
but i wan't to hide this message from url.please help me Sir,
i am developing a video streaming PC server to j2me client system that the j2me player can playing video from PC server .if have any code for video streaming then send to my email address as soon as possible
question
to develop my java project
question
question i need to mark employees as half day absent who came after 10'o clock in my web project,so i need to know who are all late entry.if you have any idea using jsp and mysql please help me
question
/) is not available.**
how tdo i solve this.please help me to run my project
please give
question
question i am using this code in my project
response.sendRedirect("LoginForm1.jsp?msg=Username or Password is incorrect!");
but i wan't to hide this message from url.please help me.
you gave me the response Hi Jamsiya
question
question following is my code to sent mail but i couldn't work with eclipse ,that have some errors .need i any set up in eclipse or tell to what can i do to work code properly.
<%@ page import="java.io." import="java.lang.
question
;/tr>
</table>
this is my jsp page
package servlet;
import java.io.
Clarify my last question's answer - Java Beginners
Clarify my last question's answer Dear expert,
I've tried out... did not specify my question too clearly.
Here's my 2 database... and parents contain other fields like name, address, email, contact numbers etc.
My
Some additions for my previous question - Java Beginners
Some additions for my previous question This is the question I posted several hours ago:
"I'm trying to write a program that has a text field... for the GUI. Could anyone please help?"
So my other two questions are:
1
Pointing last index of the Matcher
Pointing last index of the Matcher
... and also indicate the last index of the matcher using expression.For this we..._end.java are described below:-
String text = "My name is Tim.In October Tim
Java question - Swing AWT
be displayed. PLEASE SOLVE MY PROBLEM AS SOON AS POSSIBLE. Hi Friend,
Try... GetData(JTable table, int row_index, int col_index){
return table.getModel().getValueAt(row_index, col_index);
}
}
Thanks
to know my answer
to know my answer hi,
this is pinki, i can't solve my question "how to change rupee to dollar,pound and viceversa using wrapper class in java." will u help me
PLEASE HELP WITH MY JAVA
PLEASE HELP WITH MY JAVA Hey my name is Gavin and im a student at school that takes IT. my teacher has gave me a problem and i can't figure it out please help!!!!!!!!
it is a for-loop question:
Display the first 5 multiples
What is Index?
What is Index? What is Index
Further advice needed on my last question - JSP-Servlet
Further advice needed on my last question Dear Experts,
I refer to your last solution regarding my matching codes.
After I tried out your... errors
Here are my codes which I modified but basically followed your logic
Please clarify my doubt
[] args)
{
new Deadlock();
}
}
My question is that class A has 2...Please clarify my doubt /here is my sample code for deadlock/
class A
{
synchronized void foo(B b)
{
String name
Help With My Java Project?
Help With My Java Project? Write a console program that repeatedly... these steps:
display: As Entered
for each entry in the array, display the index... a bubble sort, for each entry in the array, display the original index
java question :)
java question :) write java program to use vector in ArrayList with add, remove,sort
import java.util.Vector;
public class... element by index number
vc.remove(3);
// remove Vector element by Object
Paypal integration to my website - Struts
the payment details(acknowledgement)....My question is.....instead of getting...Paypal integration to my website Hi there,
I am working on paypal.My question is....I have one webiste and in that I kept a button called
index of javaprogram
index of javaprogram what is the step of learning java. i am not asking syllabus am i am asking the step of program to teach a pesonal student.
To learn java, please visit the following link:
Java Tutorial
Netbeans Question.
Netbeans Question. Ok here is my code-
*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import...]);
}
}
}
This is what I am trying to get my program to due- using a two-dimensional array
Android Question
Android Question how can i use pre-defined table in my application
Zend question
Zend question How to change action in zend framework??
suppose i want to add data in DB so my logic is that form view code in my indexAction() and insert process in addAction so how to go addAction() part in cilck on submit
Search index
Jdbc Question
Jdbc Question Hi.
In Jdbc, if i am pointing to the database of some other machine, i mean instead of local-host i give the ip of that machine and that machine is shut down, Will my connection still work
java question
java question i have a string like "My name is arvind.i live in bangalore.i study in college.".the problem is that i hav to break this string into three seperate lines
JAVA QUESTION
THE DYNAVALIDATORACTIONFORM THIS WILL BE SUCCESFULL.
NOW MY REQUIERMENT IS TO GET DATA FROM DATABASE
Addition to my previous post - Java Beginners
Addition to my previous post Addition to my previous question about the address book program.
I need to have separate classes:
CmdLineAddressBook.java
AddressBook.java
Contact.java
Address.java
Name.java
servlet question
servlet question sir please provide a web apps program in which it has a button through which i can download my uploaded image.
Here is a code to upload and download the file.
1)page.jsp:
<%@ page language="java
Drop Index
Drop Index
Drop Index is used to remove one or more indexes from the current database.
Understand with Example
The Tutorial illustrate an example from Drop Index
Query Question 2
Query Question 2 Want to displays the name and ID of all departments with the names of the employees in that department. SELECT * FROM employee is my result
array, index, string
array, index, string how can i make dictionary using array...please help
question about database
question about database sir i have made a drop down button using html..now i want to retrieve values from database so that they my appear in my drop down button..how can i do this....i have taken many fields such as type,ward id
$
doubt in my program code - Java Beginners
doubt in my program code i have developed a web browser with the help of standard widget toolkit(swt) and java. i creted some buttons such as GO... we can see as the name of all the buttons.my question is i need to change
Probblems with printing if my innput of text file is correct..
Probblems with printing if my innput of text file is correct.. I am...();
}
}
void initCitiesDist (int index, int len) {
for (int i = 0; i < len; i++) {
cities[index].citiesDists[i] = new
java question 15/03/2014
java question 15/03/2014 Hi
Q)my array size is 10, then how can i identify class A object from array.
Q) how jvm know a particular object is serialize or not .
Q) i have a table in that table some data duplicate than how
checking index in prepared statement
checking index in prepared statement If we write as follows:
String query = "insert into st_details values(?,?,?)";
PreparedStatement ps = con.prepareStatement(query);
then after query has been prepared, can we check the index
can't read my xml file in java
can't read my xml file in java i've a xml file like this :
<..._COMMENT>
//nothing ... in this row
and my some java codes...();
}
the codes can't read the xml file bcz i want to append the whole xml in my gui
JavaScript array index of
JavaScript array index of
In this Tutorial we want to describe that makes you to easy to understand
JavaScript array index of. We are using JavaScript... line.
1)index of( ) - This return the position of the value that is hold
My Base Class is Changing every time in my code. How I can overcome this?
My Base Class is Changing every time in my code. How I can overcome this? I have had the below question asked in interview, i'm curious to learn... by Generator. The question I was asked was about creating a new base class
question
question sir plz tell me what should i give in title box. just i want java program for the question typed in this area
string related question
string related question *q.1>how i dispaly the reference of string variableS ?
eg:-String s1="my name";
Sring s2="your name";
here what is address of variable s1 and s2
alter table create index mysql
alter table create index mysql Hi,
What is the query for altering table and adding index on a table field?
Thanks
Hi,
Query is:
ALTER TABLE account ADD INDEX (accounttype);
Thanks
index - Java Beginners
This Question was UnComplete - Java Beginners
This Question was UnComplete Implement a standalone procedure to read in a file containing words and white space and produce a compressed version... preserve lines. Hi Alhisnawy,
Below is my version of code. Hope it fulfills
JAVASCRIPT insert Question -
JAVASCRIPT insert Question It is easy to transmit information from HOST program (in my case PHP program) to JAVASCRIPT insert.
How may I reverse this, passing YES/NO information from a CONFIRM BOX
back to the PHP program
Data base related question
Data base related question sir my table has only one element(that is pno),i am using ms-access as backend.
i put only one element i want to retrieve... csee my code
import java.sql.*;
class raja
{
int regd1;
public int k()
{
try
JSP Login Page Question
JSP Login Page Question hey..i have a login page where different users first registered and then after they can login.
my question is how a user can see only his data after login where different users data are stored
Java arraylist index() Function
Java arrayList has index for each added element. This index starts from 0.
arrayList values can be retrieved by the get(index) method.
Example of Java Arraylist Index() Function
import
referring to question Person.. - Java Beginners
referring to question Person.. Hi!firstly i want to thank to someone who always answer my questions, i really appreciate it..emm may i know what...=gender;
this is base on previous question (Person)..can u explain to me
question
Question
Advertisements
If you enjoyed this post then why not add us on Google+? Add us to your Circles | http://www.roseindia.net/tutorialhelp/comment/80616 | CC-MAIN-2015-48 | refinedweb | 2,216 | 62.98 |
¶
-.1 Changelog
- Next: 0.9 Changelog
- Up: Home
- On this page:
- 1.0 Changel
1.0 Changelog¶
1.0.19.
1.0.18¶Released: July 24, 2017.
tests¶
Fixed issue in testing fixtures which was incompatible with a change made as of Python 3.6.2 involving context managers.
1.0.17¶Released: January 17, 2017
orm¶
misc¶
Fixed Python 3.6 DeprecationWarnings related to escaped strings without the ‘r’ modifier, and added test coverage for Python 3.6.
1.0.16¶Released: November 15, 2016
orm¶
Fixed bug in
Session.bulk_update_mappings()where an alternate-named primary key attribute would not track properly into the UPDATE statement.
Fixed bug where joined eager loading would fail for a polymorphically- loaded mapper, where the polymorphic_on was set to an un-mapped expression such as a CASE expression.
Fixed bug where the ArgumentError raised for an invalid bind sent to a Session via
Session.bind_mapper(),
Session.bind_table(), or the constructor would fail to be correctly raised.
Fixed bug in
Session.bulk_save()where an UPDATE would not function correctly in conjunction with a mapping that implements a version id counter.
Fixed bug where the
Mapper.attrs,
Mapper.all_orm_descriptorsand other derived attributes would fail to refresh when mapper properties or other ORM constructs were added to the mapper/class after these accessors were first called..
Updated the server version info scheme for pyodbc to use SQL Server SERVERPROPERTY(), rather than relying upon pyodbc.SQL_DBMS_VER, which continues to be unreliable particularly with FreeTDS.
Added error code 20017 “unexpected EOF from the server” to the list of disconnect exceptions that result in a connection pool reset. Pull request courtesy Ken Robbins..
misc¶
Fixed bug where setting up a single-table inh subclass of a joined-table subclass which included an extra column would corrupt the foreign keys collection of the mapped table, thereby interfering with the initialization of relationships.
1.0.15¶Released: September 1, 2016
orm¶
Fixed bug in subquery eager loading where a subqueryload of an “of_type()” object linked to a second subqueryload of a plain mapped class, or a longer chain of several “of_type()” attributes, would fail to link the joins correctly.
sql¶
mysql¶
Added support for parsing MySQL/Connector boolean and integer arguments within the URL query string: connection_timeout, connect_timeout, pool_size, get_warnings, raise_on_warnings, raw, consume_results, ssl_verify_cert, force_ipv6, pool_reset_session, compress, allow_local_infile, use_pure.
misc¶
Fixed bug in
sqlalchemy.ext.bakedwhere the unbaking of a subquery eager loader query would fail due to a variable scoping issue, when multiple subquery loaders were involved. Pull request courtesy Mark Hahnenberg.
1.0.14¶Released: July 6, 2016
examples¶
Fixed a regression that occurred in the examples/vertical/dictlike-polymorphic.py example which prevented it from running.
engine¶
Fixed bug in cross-schema foreign key reflection in conjunction with the
MetaData.schemaargument, where a referenced table that is present in the “default” schema would fail since there would be no way to indicate a
Tablethat has “blank” for a schema. The special symbol
sqlalchemy.schema.BLANK_SCHEMAhas been added as an available value for
Table.schemaand
Sequence.schema, indicating that the schema name should be forced to be
Noneeven if
MetaData.schemais specified.
sql¶
Fixed issue in SQL math negation operator where the type of the expression would no longer be the numeric type of the original. This would cause issues where the type determined result set behaviors.
Fixed bug whereby the
__getstate__/
__setstate__methods for sqlalchemy.util.Properties were non-working due to the transition in the 1.0 series to
__slots__. The issue potentially impacted some third-party applications. Pull request courtesy Pieter Mulder.
FromClause.count()is pending deprecation for 1.1. This function makes use of an arbitrary column in the table and is not reliable; for Core use,
func.count()should be preferred.().
Fixed bug whereby
Table.tometadata()would make a duplicate
UniqueConstraintfor each
Columnobject that featured the
unique=Trueparameter.
postgresql¶
Fixed bug whereby
TypeDecoratorand
Varianttypes were not deeply inspected enough by the PostgreSQL dialect to determine if SMALLSERIAL or BIGSERIAL needed to be rendered rather than SERIAL..
1.0.13¶Released: May 16, 2016
orm¶
Fixed bug in “evaluate” strategy of
Query.update()and
Query.delete()which would fail to accommodate a bound parameter with a “callable” value, as which occurs when filtering by a many-to-one equality expression along a relationship.
Fixed bug whereby the event listeners used for backrefs could be inadvertently applied multiple times, when using a deep class inheritance hierarchy in conjunction with multiple mapper configuration steps.
Fixed bug whereby passing a
text()construct to the
Query.group_by()method would raise an error, instead of interpreting the object as a SQL fragment..
Fixed regression appearing in the 1.0 series in ORM loading where the exception raised for an expected column missing would incorrectly be a
NoneTypeerror, rather than the expected
NoSuchColumnError.
examples¶
Changed the “directed graph” example to no longer consider integer identifiers of nodes as significant; the “higher” / “lower” references now allow mutual edges in both directions.
sql¶
Fixed bug where when using
case_sensitive=Falsewith an
Engine, the result set would fail to correctly accommodate for duplicate column names in the result set, causing an error when the statement is executed in 1.0, and preventing the “ambiguous column” exception from functioning in 1.1.
Fixed bug where the negation of an EXISTS expression would not be properly typed as boolean in the result, and also would fail to be anonymously aliased in a SELECT list as is the case with a non-negated EXISTS construct.
Fixed bug where “unconsumed column names” exception would fail to be raised in the case where
Insert.values()were called with a list of parameter mappings, instead of a single mapping of parameters. Pull request courtesy Athena Yao.
postgresql¶
Added disconnect detection support for the error string “SSL error: decryption failed or bad record mac”. Pull request courtesy Iuri de Silvio.
mssql¶
Fixed bug where by ROW_NUMBER OVER clause applied for OFFSET selects in SQL Server would inappropriately substitute a plain column from the local statement that overlaps with a label name used by the ORDER BY criteria of the statement..
oracle¶.
misc¶
Fixed bug in “to_list” conversion where a single bytes object would be turned into a list of individual characters. This would impact among other things using the
Query.get()method on a primary key that’s a bytes object.
1.0.12¶Released: February 15, 2016
orm¶.
Fixed regression since 0.9 where the 0.9 style loader options system failed to accommodate for multiple
undefer_group()loader options in a single query. Multiple
undefer_group()options will now be taken into account even against the same entity.
engine¶
Sessionand
Connection, and taking place for operations such as a failure on “RELEASE SAVEPOINT”. Previously, the fix was only in place for a specific path within the ORM flush/commit process; it now takes place for all transactional context managers as well.
sql¶
Fixed issue where the “literal_binds” flag was not propagated for
insert(),
update()or
delete()constructs when compiled to string SQL. Pull request courtesy Tim Tate..
postgresql¶
mssql¶
Fixed the syntax of the
extract()function when used on MSSQL against a datetime value; the quotes around the keyword are removed. Pull request courtesy Guillaume Doumenc..
oracle¶
Fixed a small issue in the Jython Oracle compiler involving the rendering of “RETURNING” which allows this currently unsupported/untested dialect to work rudimentarily with the 1.0 series. Pull request courtesy Carlos Rivas.
misc¶
Fixed bug where some exception re-raise scenarios would attach the exception to itself as the “cause”; while the Python 3 interpreter is OK with this, it could cause endless loops in iPython.
1.0.11¶Released: December 22, 2015
orm¶
Fixed regression caused in 1.0.10 by the fix for #3593 where the check added for a polymorphic joinedload from a poly_subclass->class->poly_baseclass connection would fail for the scenario of class->poly_subclass->class..
Major fixes to the
Mapper.eager_defaultsflag, this flag would not be honored correctly in the case that multiple UPDATE statements were to be emitted, either as part of a flush or a bulk update operation. Additionally, RETURNING would be emitted unnecessarily within update statements.
Fixed bug where use of the
Query.select_from()method would cause a subsequent call to the
Query.with_parent()method to fail.
sql¶
Fixed bug in
Update.return_defaults()which would cause all insert-default holding columns not otherwise included in the SET clause (such as primary key cols) to get rendered into the RETURNING even though this is an UPDATE.
mysql¶
An adjustment to the regular expression used to parse MySQL views, such that we no longer assume the “ALGORITHM” keyword is present in the reflected view source, as some users have reported this not being present in some Amazon RDS environments.
Added new reserved words for MySQL 5.7 to the MySQL dialect, including ‘generated’, ‘optimizer_costs’, ‘stored’, ‘virtual’. Pull request courtesy Hanno Schlichting.
misc¶
Further fixes to #3605, pop method on
MutableDict, where the “default” argument was not included..
1.0.10¶Released: December 11, 2015
orm¶
Fixed issue where post_update on a many-to-one relationship would fail to emit an UPDATE in the case where the attribute were set to None and not previously loaded..
orm declarative¶
Fixed bug where in Py2K a unicode literal would not be accepted as the string name of a class or other argument within declarative using
backref()on
relationship(). Pull request courtesy Nils Philippsen.
sql¶
Added support for parameter-ordered SET clauses in an UPDATE statement. This feature is available by passing the
update.
Fixed bug where CREATE TABLE with a no-column table, but a constraint such as a CHECK constraint would render an erroneous comma in the definition; this scenario can occur such as with a PostgreSQL INHERITS table that has no columns of its own.
postgresql¶
Fixed issue where the “FOR UPDATE OF” PostgreSQL-specific SELECT modifier would fail if the referred table had a schema qualifier; PG needs the schema name to be omitted. Pull request courtesy Diana Clarke.
Fixed bug where some varieties of SQL expression passed to the “where” clause of
ExcludeConstraintwould fail to be accepted correctly. Pull request courtesy aisch.
Fixed the
.python_typeattribute of
INTERVALto return
datetime.timedeltain the same way as that of
python_type, rather than raising
NotImplementedError.
mysql¶
mssql¶
Added the error “20006: Write to the server failed” to the list of disconnect errors for the pymssql driver, as this has been observed to render a connection unusable.
A descriptive ValueError is now raised in the event that SQL server returns an invalid date or time format from a DATE or TIME column, rather than failing with a NoneType error. Pull request courtesy Ed Avis.
Fixed issue where DDL generated for the MSSQL types DATETIME2, TIME and DATETIMEOFFSET with a precision of “zero” would not generate the precision field. Pull request courtesy Jacobo de Vera.
tests¶
The ORM and Core tutorials, which have always been in doctest format, are now exercised within the normal unit test suite in both Python 2 and Python 3.
misc¶
Added support for the
dict.pop()and
dict.popitem()methods to the
MutableDictclass..
1.0.9¶Released: October 20, 2015
orm¶
Added new method
Query.one_or_none(); same as
Query.one()but returns None if no row found. Pull request courtesy esiegerman..
Fixed rare TypeError which could occur when stringifying certain kinds of internal column loader options within internal logging.
Fixed bug in
Session.bulk_save_objects()where a mapped column that had some kind of “fetch on update” value and was not locally present in the given object would cause an AttributeError within the operation.
Fixed 1.0 regression where the “noload” loader strategy would fail to function for a many-to-one relationship. The loader used an API to place “None” into the dictionary which no longer actually writes a value; this is a side effect of #3061.
examples¶
Fixed two issues in the “history_meta” example where history tracking could encounter empty history, and where a column keyed to an alternate attribute name would fail to track properly. Fixes courtesy Alex Fraser.
sql¶
postgresql¶.
oracle¶.
This change is also backported to: 0.7.0b1.
misc¶
Added the
AssociationProxy.infoparameter to the
AssociationProxyconstructor, to suit the
AssociationProxy.infoaccessor that was added in #2971. This is possible because
AssociationProxyis constructed explicitly, unlike a hybrid which is constructed implicitly via the decorator syntax..
1.0.8¶Released: July 22, 2015
engine¶.
This change is also backported to: 0.7.0b1
sqlite¶
Fixed bug in SQLite dialect where reflection of UNIQUE constraints that included non-alphabetic characters in the names, like dots or spaces, would not be reflected with their name.
This change is also backported to: 0.9.10
misc¶.
1.0.7¶Released: July 20, 2015
orm¶.
orm declarative¶.
engine¶.
Fixed regression where
ResultProxy.keys()would return un-adjusted internal symbol names for “anonymous” labels, which are the “foo_1” types of labels we see generated for SQL functions without labels and similar. This was a side effect of the performance enhancements implemented as part of #918.
sql¶
Added a
ColumnElement.cast()method which performs the same purpose as the standalone
cast()function. Pull request courtesy Sebastian Bank.
Fixed bug where coercion of literal
Trueor
Falseconstant in conjunction with
and_()or
or_()would fail with an AttributeError.
Fixed potential issue where a custom subclass of
FunctionElementor other column element that incorrectly states ‘None’ or any other invalid object as the
.typeattribute will report this exception instead of recursion overflow.
Fixed bug where the modulus SQL operator wouldn’t work in reverse due to a missing
__rmod__method. Pull request courtesy dan-gittik.
schema¶
Added support for the MINVALUE, MAXVALUE, NO MINVALUE, NO MAXVALUE, and CYCLE arguments for CREATE SEQUENCE as supported by PostgreSQL and Oracle. Pull request courtesy jakeogh.
1.0.6¶Released: June 25, 2015
orm¶.
Fixed 1.0 regression where the enhanced behavior of single-inheritance joins of #3222 takes place inappropriately for a JOIN along explicit join criteria with a single-inheritance subclass that does not make use of any discriminator, resulting in an additional “AND NULL” clause.
Fixed bug in new
Session.bulk_update_mappings()feature where the primary key columns used in the WHERE clause to locate the row would also be included in the SET clause, setting their value to themselves unnecessarily. Pull request courtesy Patrick Hayes..
sql¶.
postgresql¶.
Repaired the
ExcludeConstraintconstruct to support common features that other objects like
Indexnow do, that the column expression may be specified as an arbitrary SQL expression such as
castor
text.
mssql¶.
misc¶
Fixed an internal “memoization” routine for method types such that a Python descriptor is no longer used; repairs inspectability of these methods including support for Sphinx documentation.
1.0.5¶Released: June 7, 2015
orm¶.
The “lightweight named tuple” used when a
Queryreturns rows failed to implement
__slots__correctly such that it still had a
__dict__. This is resolved, but in the extremely unlikely case someone was assigning values to the returned tuples, that will no longer work.
engine¶
Added new engine event
ConnectionEvents.engine_disposed(). Called after the
Engine.dispose()method is called.
Adjustments to the engine plugin hook, such that the
URL.get_dialect()method will continue to return the ultimate
Dialectobject when a dialect plugin is used, without the need for the caller to be aware of the
Dialect.get_dialect_cls()method.
Fixed bug where known boolean values used by
engine_from_config()were not being parsed correctly; these included
pool_threadlocaland the psycopg2 argument
use_native_unicode..
mssql¶
Added support for
*argsto be passed to the baked query initial callable, in the same way that
*argsare supported for the
BakedQuery.add_criteria()and
BakedQuery.with_criteria()methods. Initial PR courtesy Naoki INADA..
1.0.4¶Released: May 7, 2015
orm¶.
schema¶
tests¶
Fixed an import that prevented “pypy setup.py test” from working correctly.
This change is also backported to: 0.9.10
misc¶
Fixed bug where when using extended attribute instrumentation system, the correct exception would not be raised when
class_mapper()were called with an invalid input that also happened to not be weak referencable, such as an integer.
This change is also backported to: 0.9.10
1.0.3¶Released: April 30, 2015
orm¶
Fixed regression from 0.9.10 prior to release due to #3349 where the check for query state on
Query.update()or
Query.delete()compared the empty tuple to itself using
is, which fails on PyPy to produce
Truein this case; this would erroneously emit a warning in 0.9 and raise an exception in 1.0.
Fixed regression from 0.9.10 prior to release where the new addition of
entityto the
Query.column_descriptionsaccessor would fail if the target entity was produced from a core selectable such as a
Tableor
CTEobject.
Fixed regression within the flush process when an attribute were set to a SQL expression for an UPDATE, and the SQL expression when compared to the previous value of the attribute would produce a SQL comparison other than.
Fixed issue in new
QueryEvents.before_compile()event where changes made to the
Queryobject’s collection of entities to load within the event would render in the SQL, but would not be reflected during the loading process.
engine¶()is added to complement it.
Also added new flag
ExceptionContext.invalidate_pool_on_disconnect. Allows an error handler within
ConnectionEvents.handle_error()to maintain a “disconnect” condition, but to handle calling invalidate on individual connections in a specific manner within the event.
Added new event
do_connect, which allows interception / replacement of when the
Dialect.connect()hook is called to create a DBAPI connection. Also added dialect plugin hooks
Dialect.get_dialect_cls()and
Dialect.engine_created()which allow external plugins to add events to existing dialects using entry points.
sql¶
Added a placeholder method
TypeEngine.compare_against_backend()which is now consumed by Alembic migrations as of 0.7.6. User-defined types can implement this method to assist in the comparison of a type against one reflected from the database..
misc¶
Fixed bug in association proxy where an any()/has() on an relationship->scalar non-object attribute comparison would fail, e.g.
filter(Parent.some_collection_to_attribute.any(Child.attr == 'foo'))
1.0.2¶Released: April 24, 2015
orm declarative¶
Fixed unexpected use regression regarding the declarative
__declare_first__and
__declare_last__accessors where these would no longer be called on the superclass of the declarative base.
sql¶
Labelconstruct that is also present in the columns clause. Additionally, no backend will emit GROUP BY against the simple label name only when passed a
Labelconstruct.
1.0.1¶Released: April 23, 2015
orm¶
Fixed unexpected use regression cause by #3061 where the NEVER_SET symbol could leak into relationship-oriented queries, including.
engine¶
Added the string value
"none"to those accepted by the
Pool.reset_on_returnparameter as a synonym for
None, so that string values can be used for all settings, allowing utilities like
engine_from_config()to be usable without issue.
This change is also backported to: 0.9.10
sql¶()).
sqlite¶
Fixed a regression due to #3034 where limit/offset clauses were not properly interpreted by the Firebird dialect. Pull request courtesy effem-git.
Fixed support for “literal_binds” mode when using limit/offset with Firebird, so that the values are again rendered inline when this is selected. Related to #3034.
1.0.0¶Released: April 16, 2015
orm¶
Added new argument
Query.update.update_argswhich allows kw arguments such as
mysql_limitto be passed to the underlying
Updateconstruct. Pull request courtesy Amir Sadoughi..
sql¶
The topological sorting used to sort.
Fixed issue where a
MetaDataobject that used a naming convention would not properly work with pickle. The attribute was skipped leading to inconsistencies and failures if the unpickled
MetaDataobject were used to base additional tables from.
This change is also backported to: 0.9.10
postgresql¶
Fixed a long-standing bug where the
Enumtype as used with the psycopg2 dialect in conjunction with non-ascii values and
native_enum=Falsewould fail to decode return results properly. This stemmed from when the PG
ENUMtype used to be a standalone type without a “non native” option.
This change is also backported to: 0.9.10
mssql¶.
Using the
Binaryconstructor now present in pymssql rather than patching one in. Pull request courtesy Ramiro Morales.
tests¶.
1.0.0b5¶Released: April 3, 2015
orm¶.
This change is also backported to: 0.9.10.
Added a list() call around a weak dictionary used within the commit phase of the session, which without it could cause a “dictionary changed size during iter” error if garbage collection interacted within the process. Change was introduced by #3139..
sql¶.
postgresql¶
1.0.0b4¶Released: March 29, 2015
sql¶
Fixed bug in new “label resolution” feature of #2992 where a label that was anonymous, then labeled again with a name, would fail to be locatable via a textual label. This situation occurs naturally when a mapped
column_property()is given an explicit label in a query.
Fixed bug in new “label resolution” feature of #2992 where the string label placed in the order_by() or group_by() of a statement would place higher priority on the name as found inside the FROM clause instead of a more locally available name inside the columns clause.
schema¶
mysql¶
Repaired the commit for issue #2771 which was inadvertently commented out.
1.0.0b2¶Released: March 20, 2015
orm¶
Fixed unexpected use regression from pullreq github:137 where Py2K unicode literals (e.g.
u"") would not be accepted by the
relationship.cascadeoption. Pull request courtesy Julien Castets.
orm declarative¶.
engine¶
The “auto close” for
ResultProxyis now a “soft” close. That is, after exhausting
Fixed the
BITtype on Py3K which was not using the
ord()function correctly. Pull request courtesy David Marin.
This change is also backported to: 0.9.10
Structural memory use has been improved via much more significant use of
_.
The
__module__attribute is now set for all those SQL and ORM functions that are derived as “public factory” symbols, which should assist with documentation tools being able to report on the target module..
The subquery wrapping which occurs when joined eager loading is used with a one-to-many query that also features LIMIT, OFFSET, or DISTINCT has been disabled in the case of a one-to-one relationship, that is a one-to-many with
relationship.uselistset to False. This will produce more efficient queries in these cases..
A new series of
Sessionmethods
Added a parameter
Query.join.isouterwhich is synonymous with calling
Query.outerjoin(); this flag is to provide a more consistent interface compared to Core
FromClause.join(). Pull request courtesy Jonathan Vanasco.
Added new event handlers
AttributeEvents.init_collection()and
AttributeEvents.dispose_collection(), which track when a collection is first associated with an instance and when it is replaced. These handlers supersede the
collection.linker()annotation. The old hook remains supported through an event adapter.
The().
A new implementation for
KeyedTupleused by the
Queryobject offers dramatic speed improvements when fetching large numbers of column-oriented rows.
The behavior of
joinedload.innerjoinas well as
relationship.innerjoinis now to use “nested” inner joins, that is, right-nested, as the default behavior when an inner join joined eager load is chained to an outer join eager load..
The
infoparameter has been added to the constructor for
SynonymPropertyand
ComparableProperty.
The
InspectionAttr.infocollection is now moved down to
InspectionAttr, where in addition to being available on all
MapperPropertyobjects, it is also now available on hybrid properties, association proxies, when accessed via
Mapper.all_orm_descriptors..
The
proc()callable passed to the
create_row_processor()method of custom
Bundleclasses now accepts only a single “row” argument.
Deprecated event hooks removed:
populate_instance,
create_instance,
translate_row,
append_result
See also
Deprecated ORM Event Hooks Removed.9.5,.9.5, 0.8.7.
This change is also backported to: 0.9.9
Fixed bug where internal assertion would fail in the case where an
after_rollback()handler for a
Sessionincorrectly adds state to that
Sessionwithin the handler, and the task to warn and remove this state (established by #2389) attempts to proceed.
This change is also backported to: 0.9.9
Fixed bug where TypeError raised when
Query.join()called with unknown kw arguments would raise its own TypeError due to broken formatting. Pull request courtesy Malthe Borch.
Fixed bug regarding expression mutations which could express itself as a “Could not locate column” error when using
Queryto select from multiple, anonymous column entities when querying against SQLite, as a side effect of the “join rewriting” feature used by the SQLite dialect.
This change is also backported to: 0.9.9
Fixed bug where the ON clause for
Query.join(), and
Query.outerjoin()to a single-inheritance subclass using
of_type()would not render the “single table criteria” in the ON clause if the
from_joinpoint=Trueflag were set.
This change is also backported to: 0.9.9.
This change is also backported to: 0.9.8.
This change is also backported to: 0.9.8
Fixed warning that would emit when a complex self-referential primaryjoin contained functions, while at the same time remote_side was specified; the warning would suggest setting “remote side”. It now only emits if remote_side isn’t present.
This change is also backported to: 0.9.8.
This change is also backported to: 0.9.7.
This change is also backported to: 0.9.7
Fixed bug where items that were persisted, deleted, or had a primary key change within a savepoint block would not participate in being restored to their former state (not in session, in session, previous PK) after the outer transaction were rolled back.
This change is also backported to: 0.9.7
Fixed bug in subquery eager loading in conjunction with
with_polymorphic(), the targeting of entities and columns in the subquery load has been made more accurate with respect to this type of entity and others.
This change is also backported to: 0.
This change is also backported to: 0.9.5.
This change is also backported to: 0.9.5.
This change is also backported to: 0.9.5.
This change is also backported to: 0.9.5
Fixed bug in SQLite join rewriting where anonymized column names due to repeats would not correctly be rewritten in subqueries. This would affect SELECT queries with any kind of subquery + join.
This change is also backported to: 0.9.5.
This change is also backported to: 0.9.5
Fixed bug where the session attachment error “object is already attached to session X” would fail to prevent the object from also being attached to the new session, in the case that execution continued after the error raise occurred.
The primary.
Repaired support of the
copy.deepcopy()call when used by the
CascadeOptionsargument, which occurs if
copy.deepcopy()is being used with
relationship()(not an officially supported use case). Pull request courtesy duesenfranz.
Fixed bug where
Session.expunge()would not fully detach the given object if the object had been subject to a delete operation that was flushed, but not committed. This would also affect related operations like
make_transient().
The.
Improvements to the mechanism used by
Sessionto locate “binds” (e.g. engines to use), such engines can be associated with mixin classes, concrete subclasses, as well as a wider variety of table metadata such as joined inheritance tables..
The ON clause rendered when using
Query.join(),
Query.outerjoin(), or the standalone
join()/.
A major rework to the behavior of expression labels, most specifically when used with ColumnProperty constructs with custom SQL expressions and in conjunction with the “order by labels” logic first introduced in 0.9. Fixes include that an.
Changed the approach by which the “single inheritance criterion” is applied, when using.
The “resurrect” ORM event has been removed. This event hook had no purpose since the old “mutable attribute” system was removed in 0.8..
The
IdentityMapexposed from
Session.identity_mapnow returns lists for
items()and
values()in Py3K. Early porting to Py3K here had these returning iterators, when they technically should be “iterable views”..for now, lists are OK.
The.
Fixed “‘NoneType’ object has no attribute ‘concrete’” error when using
AbstractConcreteBasein conjunction with a subclass that declares
__abstract__.
This change is also backported to: 0.9.8
Fixed bug where using an
__abstract__mixin in the middle of a declarative inheritance hierarchy would prevent attributes and configuration being correctly propagated from the base class to the inheriting class.
A relationship set up with
declared_attron a
AbstractConcreteBasebase class will now be configured on the abstract base mapping automatically, in addition to being set up on descendant concrete classes as usual.
examples¶
Added a new example illustrating materialized paths, using the latest relationship features. Example courtesy Jack Zhou.
This change is also backported to: 0.9.5.
This change is also backported to: 0.9.9
Fixed a bug in the examples/generic_associations/discriminator_on_association.py example, where the subclasses of AddressAssociation were not being mapped as “single table inheritance”, leading to problems when trying to use the mappings further.
This change is also backported to: 0.9.9
engine¶
Added new user-space accessors for viewing transaction isolation levels;
Connection.get_isolation_level(),
Connection.default_isolation_level.
This change is also backported to: 0.9.9
Added new event
ConnectionEvents.handle_error(), a more fully featured and comprehensive replacement for
ConnectionEvents.dbapi_error().
This change is also backported to: 0.9.7
The engine-level error handling and wrapping routines will now take effect in all engine connection use cases, including when user-custom connect routines are used via the
create_engine.creatorparameter, as well as when the
Connectionencounters a connection error on revalidation.
Removing (or adding) an event listener at the same time that the event is being run itself, either from inside the listener or from a concurrent thread, now raises a RuntimeError, as the collection used is now an instance of
collections.deque()and does not support changes while being iterated. Previously, a plain Python list was used where removal from inside the event itself would produce silent failures.().
This change is also backported to: 0.9.5.
This change is also backported to: 0.9.5.
Literal values within a
DefaultClause, which is invoked when using the
Column.server_defaultparameter, will now be rendered using the “inline” compiler, so that they are rendered as-is, rather than as bound parameters.
The type of expression is reported when an object passed to a SQL expression unit can’t be interpreted as a SQL fragment; pull request courtesy Ryan P. Kelly..
Insert.from_select()now includes Python and SQL-expression defaults if otherwise unspecified; the limitation where non- server column defaults aren’t included in an INSERT FROM SELECT is now lifted and these expressions are rendered as constants into the SELECT statement..
Added new method
Select.with_statement_hint()and ORM method
Query.with_statement_hint()to support statement-level hints that are not specific to a table.
The
infoparameter has been added as a constructor argument to all schema constructs including
MetaData,
Index,
ForeignKey,
ForeignKeyConstraint,
UniqueConstraint,
PrimaryKeyConstraint,
CheckConstraint.
The
Table.autoload_withflag now implies that
Table.autoloadshould be
True. Pull request courtesy Malik Diarra.,
The
column()and
table()constructs are now importable from the “from sqlalchemy” namespace, just like every other Core construct.
The implicit conversion of strings to
text()constructs when passed to most builder methods of
select()as well as.
Fixed bug in
Enumand other
SchemaTypesubclasses where direct association of the type with a
MetaDatawould lead to a hang when events (like create events) were emitted on the
MetaData.
This change is also backported to: 0.9.7, 0.8.7
Fixed a bug within the custom operator plus
TypeEngine.with_variant()system, whereby using a
TypeDecoratorin conjunction with variant would fail with an MRO error when a comparison operator was used.
This change is also backported to: 0.9.7, 0.8.7
Fixed bug in INSERT..FROM SELECT construct where selecting from a UNION would wrap the union in an anonymous (e.g. unlabeled) subquery.
This change is also backported to: 0.9.5, 0.8.7
Fixed bug where
Table.update()and
Table.delete()would produce an empty WHERE clause when an empty
and_()or
or_()or other blank expression were applied. This is now consistent with that of
This change is also backported to: 0.9.5, 0.8.7
Added the
native_enumflag to the
__repr__()output of
Enum, which is mostly important when using it with Alembic autogenerate. Pull request courtesy Dimitris Theodorou.
This change is also backported to: 0.9.9.
This change is also backported to: 0.9.9.
This change is also backported to: 0.9.9
Fixed bug where a fair number of SQL elements within the sql package would fail to
__repr__()successfully, due to a missing
descriptionattribute that would then invoke a recursion overflow when an internal AttributeError would then re-invoke
__repr__().
This change is also backported to: 0.9.8
An adjustment to table/index reflection such that if an index reports a column that isn’t found to be present in the table, a warning is emitted and the column is skipped. This can occur for some special system column situations as has been observed with Oracle.
This change is also backported to: 0.9.8
Fixed bug in CTE where
literal_bindscompiler argument would not be always be correctly propagated when one CTE referred to another aliased CTE in a statement.
This change is also backported to: 0.9.8
Fixed 0.9.7 regression caused by #3067 in conjunction with a mis-named unit test such that so-called “schema” types like
Booleanand
Enumcould no longer be pickled.
This change is also backported to: 0.9.8.
This change is also backported to: 0.9.7
Fixed bug in common table expressions whereby positional bound parameters could be expressed in the wrong final order when CTEs were nested in certain ways.
This change is also backported to: 0.9.7
Fixed bug where multi-valued
Insertconstruct would fail to check subsequent values entries beyond the first one given for literal SQL expressions.
This change is also backported to: 0.9.7
Added a “str()” step to the dialect_kwargs iteration for Python version < 2.6.5, working around the “no unicode keyword arg” bug as these args are passed along as keyword args within some reflection processes.
This change is also backported to: 0.9.7
The
TypeEngine.with_variant()method will now accept a type class as an argument which is internally converted to an instance, using the same convention long established by other constructs such as
Column.
This change is also backported to: 0.
This change is also backported to: 0.9.5
Fixed bug where the
Operators.__and__(),
Operators.__or__()and
Operators.__invert__()operator overload methods could not be overridden within a custom
Comparatorimplementation.
This change is also backported to: 0.9.5
Fixed bug in new
DialectKWArgs.argument_for()method where adding an argument for a construct not previously included for any special arguments would fail.
This change is also backported to: 0.9.5
Fixed regression introduced in 0.9 where new “ORDER BY <labelname>” feature from #1068 would not apply quoting rules to the label name as rendered in the ORDER BY.
This change is also backported to: 0.9.5
Restored the import for
Functionto the
sqlalchemy.sql.expressionimport namespace, which was removed at the beginning of 0.9.
This change is also backported to: 0.9.5
The multi-values version of.
Fixed bug in
Table.tometadata()method where the
CheckConstraintassociated with a
Booleanor
Enumtype object would be doubled in the target table. The copy process now tracks the production of this constraint object as local to a type object.
The behavioral contract of the
ForeignKeyConstraint.columnscollection has been made consistent; this attribute is now a
ColumnCollectionlike that of all other constraints and is initialized at the point when the constraint is associated with a
Table..
Fixed the name of the
PoolEvents.reset.dbapi_connectionparameter as passed to this event; in particular this affects usage of the “named” argument style for this event. Pull request courtesy Jason Goldberger.
Reversing a change that was made in 0.9, the “singleton” nature of the “constants”
null(),
true(), and
false()has been reverted. These functions returning a “singleton” object had the effect that different instances would be treated as the same regardless of lexical use, which in particular would impact the rendering of the columns clause of a SELECT statement..
Using
Insert.from_select()now implies
inline=Trueaccessor does not apply. Previously, there was a documentation note that one may prefer
inline=Truew..
schema¶
The DDL generation system of.
Added a new accessor
Table.foreign_key_constraintsto complement the
Table.foreign_keyscollection, as well as
ForeignKeyConstraint.referred_table.
The
Added support for the
CONCURRENTLYkeyword with PostgreSQL indexes, established using
postgresql_concurrently. Pull request courtesy Iuri de Silvio.
See also
Indexes with CONCURRENTLY
This change is also backported to: 0.9.9
Support is added for “sane multi row count” with the pg8000 driver, which applies mostly to when using versioning with the ORM. The feature is version-detected based on pg8000 1.9.14 or greater in use. Pull request courtesy Tony Locke.
This change is also backported to: 0.9.8
Added kw argument
postgresql_regconfigto the
ColumnOperators.match()operator, allows the “reg config” argument to be specified to the
to_tsquery()function emitted. Pull request courtesy Jonathan Vanasco.
This change is also backported to: 0.9.7
Added support for PostgreSQL JSONB via
JSONB. Pull request courtesy Damian Dimmich.
This change is also backported to: 0.9.7
Added support for AUTOCOMMIT isolation level when using the pg8000 DBAPI. Pull request courtesy Tony Locke.
This change is also backported to: 0.9.5.
This change is also backported to: 0.9.5
The PG8000 dialect now supports the
create_engine.encodingparameter, by setting up the client encoding on the connection which is then intercepted by pg8000. Pull request courtesy Tony Locke.
Added support for PG8000’s native JSONB feature. Pull request courtesy Tony Locke.
Added support for the psycopg2cffi DBAPI on pypy. Pull request courtesy shauns.
Added support for the FILTER keyword as applied to aggregate functions, supported by PostgreSQL 9.4. Pull request courtesy Ilja Everilä.
See also
PostgreSQL FILTER keyword
Support has been added for reflection of materialized views and foreign tables, as well as support for materialized views within
Inspector.get_view_names(), and a new method
PGInspector.get_foreign_table_names()available on the PostgreSQL version of
Inspector. Pull request courtesy Rodrigo Menezes.
Added support for PG table options TABLESPACE, ON COMMIT, WITH(OUT) OIDS, and INHERITS, when rendering DDL via the
Tableconstruct. Pull request courtesy malikdiarra.
See also
Added new method
PGInspector.get_enums(), when using the inspector for PostgreSQL will provide a list of ENUM types. Pull request courtesy Ilya Pekelny..9.5, 0.8.7
Added a new “disconnect” message “connection has been closed unexpectedly”. This appears to be related to newer versions of SSL. Pull request courtesy Antti Haapala.
Fixed bug in
arrayobject where comparison to a plain Python list would fail to use the correct array constructor. Pull request courtesy Andrew.
This change is also backported to: 0.9.8.
This change is also backported to: 0.9.8
Fixed bug introduced in 0.9.5 by new pg8000 isolation level feature where engine-level isolation level parameter would raise an error on connect.
This change is also backported to: 0.
This change is also backported to: 0.9.5
The.
The
The MySQL dialect now renders TIMESTAMP with NULL / NOT NULL in all cases, so that MySQL 5.6.6 with the
explicit_defaults_for_timestampflag enabled will will allow TIMESTAMP to continue to work as expected when
nullable=False. Existing applications are unaffected as SQLAlchemy has always emitted NULL for a TIMESTAMP column that is
nullable=True..
The
gaerdbmsdialect is no longer necessary, and emits a deprecation warning. Google now recommends using the MySQLdb dialect directly.
This change is also backported to: 0.9.9.9.7, 0.8.7.9.5, 0.8.7
Added support for reflecting tables where an index includes KEY_BLOCK_SIZE using an equal sign. Pull request courtesy Sean McGivern.
This change is also backported to: 0.9.5, 0.8.7
Added a version check to the MySQLdb dialect surrounding the check for ‘utf8_bin’ collation, as this fails on MySQL server < 5.0.
This change is also backported to: 0.9.9
This change is also backported to: 0.9.8
Unicode SQL is now passed for MySQLconnector version 2.0 and above; for Py2k and MySQL < 2.0, strings are encoded.
This change is also backported to: 0.9.8
The MySQL dialect now supports CAST on types that are constructed as
TypeDecoratorobjects..
The
SETthat actually wants to include the blank value
SET.retrieve_as_bitwiseflag, which will persist and retrieve values unambiguously using their bitflag positioning. Storage and retrieval of unicode values for driver configurations that aren’t converting unicode natively is also repaired.
true()and
false()symbols again produce the keywords “true” and “false”, so that an expression like
column.is_(true())again works on MySQL.
The MySQL dialect will now disable
ConnectionEvents.handle_error()events from firing for those statements which it uses internally to detect if a table exists or not. This is achieved using an execution option
skip_user_error_eventsthat” to False for MySQLconnector. This was set at True for some reason. The “buffered” flag unfortunately must stay at True as MySQLconnector does not allow a cursor to be closed unless all results are fully fetched.
sqlite¶
Added support for partial indexes (e.g. with a WHERE clause) on SQLite. Pull request courtesy Kai Groner.
See also
This change is also backported to: 0.9.9
UNIQUE and FOREIGN KEY constraints are now fully reflected on SQLite both with and without names. Previously, foreign key names were ignored and unnamed unique constraints were skipped. Thanks to Jon Nelson for assistance with this.
The SQLite dialect, when using the
DATE,
TIME, or.
Added
Enabled “multivalues insert” for SQL Server 2008. Pull request courtesy Albert Cervin. Also expanded the checks for “IDENTITY INSERT” mode to include when the identity key is present in the VALUEs clause of the statement.
This change is also backported to: 0.9.7
Fixed the version string detection in the pymssql dialect to work with Microsoft SQL Azure, which changes the word “SQL Server” to “SQL Azure”.
This change is also backported to: 0.9.8
Revised the query used to determine the current default schema name to use the
database_principal_id()function in conjunction with the
sys.database_principalsview so that we can determine the default schema independently of the type of login in progress (e.g., SQL Server, Windows, etc).
This change is also backported to: 0.9.5
oracle¶
Added support for cx_oracle connections to a specific service name, as opposed to a tns name, by passing
?service_name=<name>to the URL. Pull request courtesy Sławomir Ehlert.
New Oracle DDL features for tables, indexes: COMPRESS, BITMAP. Patch courtesy Gabor Gombas.
Added support for the Oracle table option ON COMMIT.
Fixed long-standing bug in Oracle dialect where bound parameter names that started with numbers would not be quoted, as Oracle doesn’t like numerics in bound parameter names.
This change is also backported to: 0.9.8
Fixed bug in oracle dialect test suite where in one test, ‘username’ was assumed to be in the database URL, even though this might not be the case.
This change is also backported to: 0.9.7
An alias name will be properly quoted when referred to using the
%(name)stoken inside the
Select.with_hint()method. Previously, the Oracle backend hadn’t implemented this quoting.
tests¶
Fixed bug where “python setup.py test” wasn’t calling into distutils appropriately, and errors would be emitted at the end of the test suite.
This change is also backported to: 0.9.7
Corrected for some deprecation warnings involving the
impmodule and Python 3.3 or greater, when running tests. Pull request courtesy Matt Chisholm.
This change is also backported to: 0.9.5
misc¶
Added a new extension suite
sqlalchemy.ext.baked. This simple but unusual system allows for a dramatic savings in Python overhead for the construction and processing of orm
Queryobjects, from query construction up through rendering of a string SQL statement.
See also
The
sqlalchemy.ext.automapextension will now set
cascade="all, delete-orphan"automatically on a one-to-many relationship/backref where the foreign key is detected as containing one or more non-nullable columns. This argument is present in the keywords passed..9.5, 0.8.7
Fixed bug in mutable extension where
MutableDictdid not report change events for the
setdefault()dictionary operation.
This change is also backported to: 0.9.5, 0.8.7
Fixed bug where
MutableDict.setdefault()didn’t return the existing or new value (this bug was not released in any 0.8 version). Pull request courtesy Thomas Hervé.
This change is also backported to: 0.9.5, 0.8.7
Fixed bug where the association proxy list class would not interpret slices correctly under Py3K. Pull request courtesy Gilles Dartiguelongue.
This change is also backported to: 0.9.9.
This change is also backported to: 0.9.8
Fixed bug in ordering list where the order of items would be thrown off during a collection replace event, if the reorder_on_append flag were set to True. The fix ensures that the ordering list only impacts the list that is explicitly associated with the object.
This change is also backported to: 0.9.8
Fixed bug where
MutableDictfailed to implement the
update()dictionary method, thus not catching changes. Pull request courtesy Matt Chisholm.
This change is also backported to: 0.9.8
Fixed bug where a custom subclass of
MutableDictwould not show up in a “coerce” operation, and would instead return a plain
MutableDict. Pull request courtesy Matt Chisholm.
This change is also backported to: 0.9.8.
This change is also backported to: 0.9.8
Fixed bug when the declarative
__abstract__flag was not being distinguished for when it was actually the value
False. The
__abstract__flag needs to actually evaluate to a True value at the level being tested.
This change is also backported to: 0.9.7
In public test suite, changed to use of
String(40)from less-supported
Textin
StringTest.test_literal_backslashes. Pullreq courtesy Jan.
This change is also backported to: 0.9.5
The Drizzle dialect has been removed from the Core; it is now available as sqlalchemy-drizzle, an independent, third party dialect. The dialect is still based almost entirely off of the MySQL dialect present in SQLAlchemy.
flambé! the dragon and The Alchemist image designs created and generously donated by Rotem Yaari.Created using Sphinx 4.5.0. | https://docs.sqlalchemy.org/en/14/changelog/changelog_10.html | CC-MAIN-2022-21 | refinedweb | 7,741 | 50.23 |
lurtrnxr a kilixb, ruwuber.' .
tiEO. W. JIANYItNNV, Editor.
COI4TJMBUS. OHIO.
8ATURDAY MORNING, JULY SO. 1861.
Democratic State Convention.
At iTmeetlng of the Democratic. Slate Ceo-
tral Committee held Id Columbui, on the 5th
day of Jaly, 1861, it was
RettUtd, Tbat It I expedient to bold a Demo
Oralis otet Convention tt Commons, 00
Wednesday, Augaat 71I1, 13G1
ii nominate a Democratio State Ticket, to be
aurmnrtad ml tha Oatober eleetion.' ' ".'
&svtW, farther, That all the electors of the
Stat of Ohio, wbo are In favor of perpetuating
ihe principle! npon which our Uuiun tu founii
ed, and are convinced that the present 8tate
and National Administrations are wholly in
competent to manage the government In its
present critical oondition. si well as all who are
ODooaed to the nroea extravagance and corrup
tioo now so alarminglv prevalent io public af
. fairs, bs earnestly Invited to unite with the
Damooricv in tbia hour of our country's pei II,
and tbns redeem the State, and place its ad
ministration in competent bands.
Remind, further, that the basis of rcpresen
tation iii said Convention be one delegate lor
evert 600 vote", and an additional delegate '
a traction of H&U ana upwarae, cats iur . ox
J. S. Smith, for Supreme Judge ut ibe October
ir.iinnin iNfif) .nd that it be recommended
that the counius elect their delegates on this
basis.
The Democracy of Ohio and all other oon-
s ervatlve Union men, who are willing to co-oper
ate with them on the above bisis, are requested
to meet in their respective counties at euoh time
as the local committees may designate! and ap
point delegates to the Democratio Convention
An tha 7th ct Anemt. to nominate a State
ticket to be supported at the October election
It ts preiumed that no lover of hi oooutrj
will require prompting at this time to induce
him to discharge his duty, aud therefore the
Committee is impressed with the belief that the
counties will eagerly respond to this call, sno
that an Imposing Convection will assemble in
Columbus at the time designated above, and
pnt In nomination a ticket of good and true
men, to be supported for the various State of
does on the Sd Tuesday in October next.
WM. MOUNT, Chairman.
WM. J. JACKSON, Secretary.
The Union and the Democracy.
The Democratic party of tins country has
beeo, and is a Union party. While embracing
within itself all the elements of true national
progress, It Is, by Instinct and from principle,
jscntlally conservative. This baa been abund
antly proved by the past political history of our
country; for in the days of peril and disaater,
when the stability of the Union was threatened
by foreign and domestic foe9, the Democratio
party hat been the bulwark cf the nation's safe
ty. To that grand old party, illustrated by the
deeds of a Jirrrr.BON, a Jackso, and other
patriotic leaders, is the country indebted for the
preservation of tbeUoion,aLd the maintenance
of the rights of the Slates.
The great object of the enemies of the Union,
as It was formed by the Constitution of '87, has
been, from.tbe reign of Federalism under John
Adams to the domlnancy of Republicanism
under Abmham Lihcuh, by dividing, to weak
en and demoralite the Democratio party. No
thing has stood eo directly in the way of the
toes of the Union and the enemies of State
Rights, or been so much dreaded by them as
the compact organization of the Democrary.
Tbe disunlonlsta, North and South, have always
felt the absolute necessity of breaking op this
orgauizition, in order to insure the accomplish
ment of their scheme- la this, they have bad
a common object and worked to a cemmon end.
This plan of dividicg and distracting the
Democracy, in order to prepare the way for tbe
final dismemberment of the Union, has been, at
different periods in our national history, put in
operation, and been partially. successful. Bat
tbe old national party has, hitherto, rallied in
its native strength and unity of purpose, and
saved tbe Union by maintaining tbe integrity of
the States. But the conspiracy for dividing the
Democracy, and by that means effecting a sep
aratloa of tbe States, if not their annihilation,
has of late assumed more gigantic proportions
and become more alarming than at any former
period In our national history. The secession
Uts succeeded in tbe last Presidential campaign
ia producing a division in the Democratic ranks,
and the dlsuoionists in the North carried tbe
election of a sectional candidate for the Presl
dency, npon a sectional platform, and both plaj-
Ins into each other's hands, have involved the
country In a civil war.
In the midst of tbe darkness end uncertainty
overhanging the future, there is a prospeot that
tbe same gallant party which won to many vie
I rlts In tbe past, thereby earing tbe Union,
may again nobly come to the rescue, and by
consolidating tbe tree friends of the Union,
North and South, eo mould and direct public
opinion to both sections, as to bring this fratrl
cldal war to a speedy conclusion, and restore
tbe old harmony and fraternity of feeling be
tween the citizens of the now belligerent States.
This wonld bams the cherished scheme alike ol
the rebel secessionists at the South and the
fanatical dlannlonists at. the North. Their
common objeot, therefore, is to prevent, at this
momentous juncture, the rallying and uniting
of tbe Democracy.
To this end, the Southern disunloniats have
inaugurated a "Reign of Terror" in their sec
tion, while their brother disonlonists in the
North, acting as their pliant tools, yet affecting
to hold them in abhorrence, are laboring inoes
easily, openly and in secret, to seduce Demo
crat! from their allegiance to the Union and to,
the party, by pretending that to criticise any of
the acts of the present Administration, and not
consent to amalgamate with tbe Republican
party, Is treason to the country. Out of sec
tlonalitts and disunionists, leading such dupes
as tbey can find, tbey would form what they
would christen a new Uulon party. Then, with
DO organized opposition of any account, they
ooold carry on a war for tbe extermination ot
slavery, Involve the country in foreign wars,
and end the great tragedy la the dissolution of
tbe Union, the destruction of the State govern
ments, the ruin of the country, and the establish
Bant fully of two ar three military despot-
ta. , '
Two Moat of our assortment of lawyer Brig,
adiers have touched bottom. Gen. Hill, of To
ledo, has shown himself Incapable of obeviog
a plain order Intelligently. And Gen. Hurl
bart, of Bslvldtre, Illinois, has finished bis ca
reer with his first proclamation. There are
eevsral more who thould 10 down ''like lead in
the mighty waters." Cm. Cemnivciul..
Tbis Gmmrfittl has the most summary man-
ner of disposing of Out-military officers. It
kills more of ear military men, and more Gov
ernors, than the rebels do. Wonder where
they bury their victims? The editor merely
dashes a senteoee or two with his quill, tod
down goes a victim. It Is absolutely dangerous
to hats such syW.i(T; military men as editors.
Democratic Nominee for Governor.
An esteemed friend calls our attention to the
faot that in our notice of those gentlemen who
had been named In connection with the nomine
tlon for Governor, we emitted Stanmv Mat
thiws, Esq. We thank our friend for calling
our attention o this omission; which"..! "nnin
tentlonal on our part, aud we cheerfully make
the correction. Col. Matthiws is no on duty
atCamp Chase. His worth, capacity and abil
ity for any publio. station will b conceded by all
who know him;-.:- a v"
Resolution of Thanks to Gen. McClellan.
Cleliau...
The House of Representatives on the 15th
DiMad a raaolntion of thanks, unanimously to
Gan. McClillaw and' the men under his com
,.,,. rn. h iwlea of brilliant sod decisive
victories which they bare, by their skill and
hr.. .ohlaved over the rebels and traitors
in the army on tbe battle fields of Western Vir
ginia." ' V'-;;' ' '- -'' ;'
Ben. Wade.
In 1855 this bitter Abolition agitator went on
a sooutlne expedition through the New fcog
land States, for the purpose of intensifying the
people of the North egainst the South, with the
premeditated design of producing the very state
of thines we now have.,. - . . :.'
In a speech somewhere "down in the btate 01
Maine." he said:
"There was really hoUnion now between the
Vnvlh .nrl Ann th. and ha believed no two na
tions upon the earth entertained feelings of
more bitter rancor toirard each other than moss
two seotioos of the Republic. The only salva
tion nt th Union.' therefore, was, to be
freed from all taint ol slavery. There was no
Union with the South. Let us have a Union,
or let us Sweep away this remnant wucu
called a Union. : I go for a Union where
men are equal, or.no Union at all." ,
This "bitter rancor toward eaoh other" was
produced by just such fellows as Wadc, and
tbey rejoiced that It was to.' ; In" their hearts
they rejoice at tbe war now going oil, believing
it will end in the abolition ot slavery and the
division of the Union.
Tn Baiois roa th Pusidikt and Cadi
nit. Tbe country will be made bappy by
knowing that the two barges for tbe President
and Cabinet, of wbicb we spoke a day or two
siuoe, are in a process of early solution.- The
white and tbe blue paint are being compounded
by an asoompliabed artist, and tbe upholsterer's
damask will be delicately and daintily adjusted.
We bespeak for tbs regatta favoring gales and
halcyon seas. Next to flag raising, when the
country is amid tbe Calamity of wr,; commend
us to state gondolas and oarsmen In livery
Cor. Tribune. - v
Tbe people of tbe country will no doubt bt re
joiced to know that the officials at .Washington
are enjoying themselves eo gloriously in state
gondolas snd oarsmen dressed In' livery. What
are we' coming' to? ' The'icountry bleeding at
every pore, and Lincoln and the Cabinet rowed
about by men in uviar! - - '
Small Bosmiss. The General Western
Aeent of tbe Associated Press. Geo. B Hicks,
of Cleveland, Ohio, has notified tbe Editors of
tbe etafesaiaa that the reports or tbe Associa
tion will not be delivered to them any longer.
Tbe reason assigned is. that the editor has abas
ed tbe Associated Press ia the colamns of that
paper. Magnanimous association! Splendid
effort! Wonder if they will survive this exhi
bition of littleness In this would-be-great man
Hicks? We venture the assertion that be is
totally unfitted for the place be occupies.
Columbui Quelle. 1 .' ' "
Is this not entirely too "outspoken"? This
Hicks may have power' to stop Uhgraph dis
patches, but there is 09 danger of bim other
wise. We are glad he has it nof4n bis power
to Injure the oatine of tbe uautte, in any
way, or be would do so.
HIT The notorious Abolitionist member of
Congress, Lovejoy, is actively engaged in get
ting Democratio Postmasters sod other Demo
cratic officials removed in bis district, which Is
the Third of Illinois. The account of these
removals might appropriately be named, "An
other Republican victory!" with some sueh sen
sation heading as "Gallant Exploit of an Abo
lition Commander Another .. Democratic
Stronghold Taken 'No more Party,' save for
the Republicans!" - "
LovejoT abould not be forgotten at the fierce
Abolitionist from Illinois, . who, in Congress,
took such an active part In organizing tbe "ir
repressible conflict" which precipitated the
country into civil war, but who takes no Inter-'
est In it it U will not result In the general abo
lition of slavery throughout tbe United States.
After having helped to get up the war, he has
carefully failed to trust his body In the ranks of
the army, to share its dangers, but continued
content to prowl around his political district and
olav ths office of executioner, whenever the
bead of an honest Democrat can be discovered
within the reach of. Montgomery Blair's guillo
tine. Cln. jirr.
Muskingum County.
Th County Central Committee of Masking'
urn county, have called a Mast Meeting of the
Union Democracy at Zanet vllle, 00 Eatuidat,
tba 3d of August, to appoint delegstes to the
State Convention. .,. . r
NoPaitt! "No partv! Forget party and
fight tbe battlee of tbe Union!" Such it the
theory of the Lincoln Republioant, but what is
their practice? Th Boston Putt illustrates it
in the following paragraph: 1
A little billet deux yesterday announced to
eight Inspectors and two aids In the Boston custom-house
ten able bodied men that tbs
country no loneer needed them, unless they In
oline to muskets and knapsacks.; . ' ., ; j
1 1 n 1
Markets for Produce.
The New York Timet, discussing th koottv
problem of tariff and revenue, saysi . -
"At tbe next session of Coosress, we hose to
set our present system uorougniy overhauled.
in times or peace, we can readily carry our ex
port up to S500.000.000. but not unless w on
import merchandise to an equal amounts This
we can never do under the present or proposed
tariff. Every portion of the country must be
equally favored. While we would protect man
ufacturers, wo would protect the farmer ot tbe
West, by securing to him a market which will
give value to his labor by taking its proceeds.
One State West oould feed all tbe manufactur
ers of tbe Eastern States."
Diath of tbk Hon. J. W. Jiwirr. The
Hon. Joshua W.Jiwitt, late Congressman from
Kentucky, departed tbia life at SbelbyviUe, Ky.,
on Saturday last, In tbe forty-ninth year of his
age. He was a brother of- H. J. Jswrrr of
Zanesvllle, President of the Central Ohio Rail
Road, and Thos. L. Jcwrrr, President of the
Steaubenville and Pittsburgh Rail Road-
CTThe Republicans of tbe United State
Senate held a Republican caucus, and nominated
a Republican for Clerk, and elected bim, but
the Democracy must not hold Conventions or
caucuses to nominate Drmoeritr.-Nop that
would be treasonable, unpatriotic! Get ont with
such nonsenses! . ad
Clermont County.
The Union Democracy ( ClermoK eonoty
appoint their delegates to the Btate Convention
on ihe 27th of this month. , . -. -r-o
Gallia County.
, , Tha Union Democrats ef Gallia county meet
at Oalllpolis, on Satdhda't, 'August' 3J, to ap
point delegates to the Btate Coaveation, and
also to appoint committee to collect oontriba-
tlonj t tha Dougiat Fond. "' ' :T V"'V
i
'I
The Battle in Western Virginia.
W extraot the following from the special
correspondence of the Cincinnati pmmtrtitl,
It will be found lnterstibgt ;. T?..
THE DEAD ON THE FIELD OF BATTLE.
Th dead presented a Rbaatlv "spectacle.
aevev eooeelved anything half so hideous.- No
nower of expression is adequate to describe It
It was a oomplpt ponoentration of horror' slf.
It 1 said Out th features of thou who dl by
other causes, are usually relieved by a faint
smil that suffer log It rarely left Imprinted on
the countenance of a corpse but that tbe coun
tenance of tbos wbd are shot have impressed
npon tbera tbe traces or pain. Those wbicn 1
saw. exhibited nothing but the revolting char
aoters of exquisit agony, Tber was not th
faintest glimmer of a lingering smile, not tbe
sligntest possible tint or soicnesa or mildness,
not a lineament of beauty remaining, to relieve
the harsh, borrid, distorted, agonized faces of
tbe dead of Rich Mountain. '. The. bright sun,
elaooing through the' parting leaves, lent no
Kindly ray to soften toe- ngiy outlines; melan
choly bad no sad, qnlst shadow, to mlogle with
the bard, forbidden aspect of th dead faces on
which I gactd with perfect horror. Had there
been even tract of angry passion, vindictive
neat, revenge, death could not have stared so
horribly as it did, ont of those ghastly linea
ments j wt con id nave fell tbai there was still
something human left in those human faces but
mere outlines.' ,-.,, .- - -: .
Tb face of our own "dead were as fearfully
forbidding as those of thair dead enemies. ' It
was impossible to drive from my mind reflec
tions upon tbe terrible Intensity of grief which
tbose wboeee-tb forbidding countenance of
dead loved one on th field of battle, must ex.
perience. I Imagine it must exoeed all other
grief ior tbe dead -because every feature 1 so
distorted and uonaturalrso entirely devoid of
tbe toss ot expression wblon friends bave loved
in tbe living feature.' Some were lying prone
on tbe field as tbey-had fallen, with limbs
sprawling, great thick' plotchea of coagulated
blood near, their bodies, their garments saturat
ed with tbe ensanguined flow, and their gaping
face and atony eyes, staring fall at the broad,
brazen sky. - On who bad been shot down In
the woods, above the breastwork, lav stark up
on bis face, one arm thrown with a convulsive
struggle around the ' limb of a fallen tree.
Clotted blood which had flowed out of bis side,
wat near him in thick lumps. But the most
hideous scene was that of twenty-nine dead
rebel packed horribly together In atrehob
most ot mem Wltn tearful orlncea perforating
their beads, through wbiob tbe brain oozed in
sickening clots; others with mini bole full In
their breast: com with shattered limbs, and
other with lacerated and mangled flesh, with
nere ana mere a splintered Don exhibiting it
elf. . Our own precious desd. but few in num
ber, bad been mort tenderly gatbrd, and kind
com races naa decently composed their stiffen
we iwms. 1 lilted tb covering which conceal
ed their inanimate feature, but saw nothing to
remove Horn my mind to lndelibl impression
of unmitigated ugliness of dead faces of men
Aet in battle..! ..- -
One poor lellow of the 13th Indiana wat shot
in tbe left eye bv a grape shot. it perforated
th brain and dislodged and disorganised tb
whole inner structure from th cranium down
ward, leaving a monstrous cavity of uulmsgin
able horror. .Tb ball left the eyelid perfect,
entering directly under tbe nose where it join
toe lorenead, witnoul dlstlgaring the nose In
tbe leutft perlectly clean, but very singular
wound. ,' : t v (.
Our own dead occupy separate graves on the
battle-field tbey to gallantlv won. Tbe bodies
of our brave but misguided to emeu wer care
fully laid Ia a common grave, and ar now rest
ing quietly where but yesterday tbey fought so
wen. - ... .- -i t : 1
THE WOUNDED.
own and tb rebel wounded lav ttrown
together in blankets' on the floors of Hart's
bouse. Every available space was covered
ith their convulsive and- uulvering bodies.
Down under tbe porch there was another line ot
wounded. There was no difference in tb
treatment of the sufferers. The severely wound
ed of tbe enemy were attended to before the
slightly injured of our own army. Moat of them
suffered in silenoe, a fw slept soundly, bnt tome
moaned with intense agony. One poor fellow,
n Indlanlan, thot through the tide of the head,
who could even yet stand on his feet with assist
ance, suffered excruciating agony. It he sur
vives it will be almost miraculous. Now and
then a wounded rebel would stare sullenly at
our people, but the majority appeared grateful
ly surprised at toe Kindness witn wbicn they
were treated. Indeed, everything possible was
done to mitigate their sufferings. I shall not
attempt to depiot the ghastly pictures of borrid
wounds ana snudderlng forms of poor victims,
to whom it would have been merciful if tbev
oould have died, bnt wbo lay on tbe cold, cold
ground, quivering with sgooy, with no chance
to survive, and yet could not eke out a last suf
fering gasp. , ,
INDIANA VOLUNTEERS KILLED AND WOUNDED AT
THE BATTLE OF RICH MOUNTAIN.
Col. Benton furnished me with the following
list of tbe killed end wounded of the 8th Indi
ana Regiment, at tbe battle of Riob Mountain.
viti
Killed Philander Wiaeheart. Co. B. Jo
seph Back, Co. G. - -
t Woondxd Co. A Franklin Stabeueh.
wounded in tbe groin. .
josepu runx, nesn wound in tbe calf of the
leg.
.. Wm. H. Rittler. flesh wound in shoulder.
Co. B Geo. W. Shane, severe wound In the
Dreast. . i -.! -
Henry L. Powell, flesh wound In ths ancle
Co. C Collier W. Reed, right leg broken
below tbe knee.
Andrew Wt Rldenour, flesh wound In the
right thigh.. s -.i.-. i
Asbury Kenwood, flesh wound in the brestt
ana arm.
John Walker, finger on left hand thot off.
Frederick Coppersmith, wounded in the right
wrm, ana umu wouoa. in toe necx. '
Co. E Park Btraban, wounded in the left
arm. - :
Samuel Williams, wounded in tb left tbltb
- Co. F William Lamb, wounded la th left
knee,
Co. G Beoj. Curtis, wounded In tb tbigh.
. Cor - H Lemuel Caalck, wounded in the
breast and arm. '
. Jaoob Sailors, wounded in the arm.
Jacob Berotb, slight wound tn tbe thigh.
Jess King, slight wound ia th tblgb.
Co, I M. M. . Steveason, woondtd ia the
right leg.-- -....r - . --. -.
; Jam Buchanan, slight flesh wound In the
right hip.
Andrew Stulzoan, wound In tb left koee.
Co. JC Frank Hall, wounded in tha rirht
taign.. ... .
oamuel Devaagba. wounded in th left
tnlgb.. ... .. . m. - . . . . ,
KILLS 0 AND WOCNDKS Or TMK
mm iDiA
- . aioiMirr.
Major Wilton of th Tenth Indiana wbo bv
th way, It mentioned as one wbo distinguished
himself by hi fgallant conduct In tb battle,
luroianee toe following net or casualties In tb
lento, vii: -
WoewDtn Lt. Col. t. M. Bryant, by con
cussion of a cannon ball. He is In a bad con
dition. ' ,
Major W. C. Wilson, shot In the calf of bis
leit leg, part of tbe bone being splintered off.
Major W., however, hat been constantly on
auty since tne trnttie. ,
, Fife MJor, Frank Pickard, very silently,
Co. A,Capt.Cbrls. Miller, dangerously. ,W.
Manburn, Chancy Thompson, Frank M.Bryant,
i nomas v.iruett ana noab vicK, badly, wax
Stoke, mottallv all from Lafavatta.
Co. C, Daniel London and Wm, Singleton,
Daaiyr ana nepoen yvesoo, engotiy all from
Clinton ennnt. .1 ! ' .
Clinton County,
Co. D. from Ltfavette. In'd.I' Llnt'' inhn
Brown, James W. Given, Aaron Trelleges, Joo.
Cunnlagbam and Henry Rank, badly. Henv
Yonnv. tlrhtto i 1. '
Co. F, Clay eou'nty.'Lteut. Sannder mil T,
Co, H, Putnam county, Capt. Cookltn, In the
rigni arm; Henry mcum, oadiy. , ' ,
,.Co. I, Boone county, Wm. M. Remington an
Frank M. Parish; slightly.
Co. K, Lafayette and Wayne counties, eo.
w. uroosr, baoiy; Keiiiy weoat, siigtrtiy. -,
KrLLfp Sergeadt Jmc"A. Taggtrt, Co.
A. of Lafavett: Wm. Yocnm. of Clav count i
. li.eiiingtonartyette. ; v
KILLED AND WOUNDED IN THE THIRTEENTH INDIANA
REGIMENT.
;.CoL J. furoUhad the. following tfiL
oil litt or Killed ana wounded in U reg.
lmont ox Indiana volunteers: . (..
XkiistBLtO. vAJwon juiMr,,vvasiiiMtoa
Co. B, Corporal Jobn Powell, Peru, I Cor
poral John T Warner, Lagrange, I. ' ' J" i
Co. B. Wm. Ruffls, Howard county, Ia. L i
Co. H, Allen Thompson, Terr HaUt, IsJ
Co. G. Patrick Welch. Salem. Lvi
Co. C. Josenh Cook, of Franklin county, la,
WoONDtn Co. E. Charle Crumbo, New
Albany Cha.,Poff. Howard county t- DurWa
Atatners. Howard county; ' "
Co. H, Isaac Thornbruffj Brhlaeport; Jsmet
Ctrnagsm. IndlantBolis. I i ' ) i !
Ii , T ot. ' A- V .1-.
-vo. j, i nompson, saiem; juo. i wujub
new rrovidenoe-., - ;,-lr.3.rf
-'-Co. D. Eli Wr Coolev: Saott oo.. slightly .
Few of tbt above are dangerously wounded
One, whose nam I cannot learn, bad bis right
arm amputated at tba shoulder. ;
RECAPITULATION.
in 8th Regiment, 9; in tbe 10th,'3 in
the 13th, 7; total, 13. Wounded In the 8th
Regiment, S3; in the 10th. 25; in tbe 13th, 7;
total, 65; of whom 9 are mortally wounded.
Many of the above bave received alight wounds,
ana but lew will b disabled.; - l ' -
NUMBER ENGAGED AT RICH MOUNTAIN.
exaggraud bit atrength at the battle of Rich
Mountain. H left Roaring Run with 1800
man not-wirva thnn .10.00 of whom were h
the mUou altogether., and -only 81)0 at .'onel
time.T ' r i .; -' 'I'
ll is impossible to estimate the force of. the
enemy.) They differ widely in their own ttte
menta. Som say three hundred, other offloere
say four hundred to four hundred and fifty. , Col.
Pegram informed me that he bad "nve com
panles" in action. Some of their wounded, re
ported Immediately after tbey were captarfd
tnat tney Dad Ave hundred to nine nuoorea.
Our own officer tav that. they iad between
nine nunured ana one tnootsna, oat tneir oreast-
works and batteries canalized tbe forces. Sev
eral of their officers lofrm me that tbe most
terrible fire tbev had that day was the two vol
ley by battalion fired by tba 19th Ohio,' . On
ef thsm said," we supposed your regular were
at work, and that it was no us to fight against
tbem." 1 bis is good testimony for tbe umo
boys. .General Roseorans himself said tbsy
were tbe only regiment wbo staid where he or
dered them to stay, and moved according to bis
orders. But I digress. The prisoners will be
quartered here for the present. . A detachment,
guided by rebel Lieutenant, is out ia, tb
mountains now looking for one hundred and
twenty-six more of Pegram's command, who are
famishing in the mountains. They are ordered
by tbelr commander to surrender. We bave
now seven hundred prisoners, with one thou
sand stand of arms, chiefly United States
muskets changed from flint to percussion locks.
The wounded of both parties are being re
moved from Rich Mountain to this place
Colonel Pegram it quilt ill, laving been seri
ously hurt by being thrown from his horse in
Datue. -v n :(
REVELRY.
Gen.Rosecrant'tbrigadtit here. Tbe town
It being converted into a great army store-bouse
To-morrow a guard wiii-bt tent .out with a
wagon train to open communication with- tbe
N. W. V. R. R., via Phllllppl. That route
will hereafter be the mode of army com muni
cation with civilisation. Webster will be tbe
railway depot for stores. Telegraphic commu
nication via Backbaonon. will be opened . to
Clarksburg and tbe rest of the world to-morrow
The New York Commission to Examine
into the Condition of the Men.
From a report made by Dr. Pitiks, assistant
to Dr. Alixamdkb Mott, of New York, and
published In th Tribune, w telect the1 follow
ing relative to the troops about .Washington:
The Commission found regiments seven or
eight miles from Washington supplied with
fresh meats three or four timet a week, and
fresh bread every day; While othert a mile and
a balf from Washington were atthe game time
almost starving for everything. . This wat owing
to tbe meffloiency or rascality of the quarter
masters. To illustrate how tbe men think of
tbe matter, the speech of a Major to Mr. Dors
beimer, a State officer appointed to see that all
these tallies are properly attended to, may be
given. Mr. Donheimer wa in the habit of
coming round, and asking, if "anything was
wanted," finishing up hi Inquiries briefly, and
departing, without leaving bis name of address,
which generally proved to bo the last of the
matter. The Major (belonging to the 17th
Regiment) in reply to this question, stepped
promptly forward and said, "Mr. Dorsheimer,
we nave oeen twinaiea in everyiaing irom new
York, and now, thank God, we are mustered
into the United States service. ' We do not
want anything from you, or from New York."
. Our Informant ia ooafidect that a large third
of the New York troops are comparatively de
moralized from bad treatment, a want of food,
and want of proper olothiog. Those who came
full of courage and zeal were now shame-faced
aud disgusted. Of thlt be is fully satisfied.
ur. Mott bad frequently oaiiea a meeting or su
tbe officers, having the Quartermaster present,
and instructed tbem as to their duty, telling
tbe respective officer for what tbey were re
sponsible in so far as it related to tbe work of
the commission. A great many captain wart
not before aware of certain items of duty thut
communicated, and of tbe redress to be sought
and found tn cases of negligent or culpable Inef-
aaency in departments alluded to.
Tbe Doctors round a great many of tbe army
Surgeon and Aeitant-3urgons completely in
competent end Inefficient, paying no attention
either they or their officer to tha cleanliness
cf the camos. tbe provision of sinks, etc. Tbev
lound som camp tbat bad been eight days es
tablished Where there was still to privy, tbt
men relieving tnemtuvee aaywnere, within a
few feet of their own tent. W ot only tbe sur
geons, but the captains and other officer, wer
to be held responsible in this case. About two-
thirds of the camps visited were, however, found
in perfect order, inspected by tbe proper officers.
and properly looked after by the surgeons at 4
o'clock dally, according to the regulations, A
large half of them were even neatly kept; the
street scrupulously swtpt clean; matters pre
senting tbe soldier's rough out-door life In a
more charming aspect.
Tb blanket served from tha btate of New
York were small in site, bad ia texture, and al
moat rotten, to tbat yon could poke your finger
through that. Tbey were not one third the
width tod ic of the army blanket. ' Tbe
aai sort of swindling wat apparent in tent,
blankets, elotbea, noe, etc. 1 bere wer many
men without shoes, or with only poor ones, and
their toe gaping out. This state of things bad
caused them to b shamefaced and dispirited.
A great many would cot ask for leave ot. absence
over tbelr own line for no other reason than
tbia. Tbey looked like convict hi th penlten
tiary, and worse than any bod -carrier with whom
on weald at. Tki waa trae With a third
at tbe Hew York troop. Aoy person could
it by taking th trouble to vhdt th camps,
aetag, or eoam, nrt sappuea iron neadqaar-
Mr vita tha rtqaialL portslasloa. Bat th
amp ware located nils apart, and tba public
sever went tanner uaa to vuu a law crack
regiment. , -
Many Colonels, it wa tbougbt, neglected
their regiment by "loafing" Io Waatuuguio,
sometime being away tor tow or five day
without returning to tee their men, while tbelr
abaence had nothing whatever to do with their
daty. ULaere -wer MtMoooa, evea to eseete
Thut torn rermottwT over-drilled. bUr
kept at bard work lor eight boera, well ate
aid not oevot to tnat tnnn.ni aaor tbs tore
or four boar a tUy. Oa a bet ay regiauatt
ware teen to drill for haw without owvosliig.
and then dismissed only five vt tea auIMa
not long euoogn to get a driak of wtr r u
which may would b called la tegimenUJ faisyd
for another hour or aa how end a t& Jo
of these men bad bea tonad almost ready tt
mutiayt but tbey wer very tOAm, a a iv
let of eourse, la the msncM eed aL
Some of tbe Colonel did act know lew to artii
al least they had beta told so or roaeg was
officer enl to assist it at, in the hmriug of
me commission. Bom of taa UHoaei a4
been eeen riding about on tiorttbaek. in V
Ing gow and slippers; othert war o th v
trary extreme, and wer Invariably appesriagla
th stiffeet uniform and cocked hat, Dover tree
putting on fatigt. r a.... v ,i --, i
. .The punithmenta resorted to wer very seri
ous. A bole wa out In tba bottom of a beef
barrel,' and thlt uncompromising garment was
potovef ea unluoky offender ia sooha manner
that only bit head wa exposed. Small squads
augni ot teen paraded about la mis way, snak
ing their heada at flies, i Other ware drilled
With bug logs of wood for musket; a couple
of sentinels with bayonet behind to force obo-
dleace to order. Other wer made to sun
lik a atatue on the top of a beef-barret for
three or four hours.. ' Othert were bucked and
f tgf td, ate j In mott ease of this tort a ttvtra
punishment bad been deserved. There was con
siderable fun around th camps. In. one regi
ment a hugs pig was gagged and put In the
guard-house by tb boy, th offense being th
making noise about th nvenjle.yTb Zou
aves dealt mora energetically with a similar of
fender by bayobeting him, and banding him pvej,
- eeog. - un a learrui munaer suower e
third of the 38th Regiment turned out to take a
shower-bath, going through tb double Quick
and varioiist gymfcalilct, playing leap-frog and
other flip-flaps, standing on tbelr beads, etc
i Some of me German regimenta' were perfect
model.. Tbe men erected arbor . before tbelr
tent. ; Tbe colonel andjoffioer had arbor ter
Uloly twenty fiv feet square, and 'elghteeibr
iwcuiy ieet uigo,oi evergreens, iwniy in Beau
tiful shapes, ventilated with Gothic .windows.
They were all thus in possession, of a delight
folly shaded enclosure, their tents ,.n, tbe rear.'
were always cool and comfortable, land took
tbelr meal pleasantly. .The German are gen
erally pretty well dressed and taken care, of.
Blanker' regiment n. particular, was fine.
They had good bands'of .miisip, slngiog aud
glee olubs, aud were bappy. . In Ope. case. .they
built a bug temporary oven Id a clay,. bank,
and were no dally, bakin; their, own bread,
la this way securing a great saving to the rcg-iment-.''1
From their extra rations eaoh company
saved from 860 to $70 per month. ; These .ex
tra amounts saved were used In purchasing la:
gerbeer, milk, tobacco, Ireah potatoes,1 greens',
string beans, boot bltcking,' soap, eto. Many
of tbem had procured Jsrgi coffee-roaster, a
big at a barrel, by means of which they made
delightful coffee. It Wat 'common to see them
bartering barrels Of pork, bags of coffee, bags
pf tagar, ste, wbloh bad been saved, for artl-
olea which suited tbelr German appetite bet
ter. Oa tb other hand, there are some regi
ments among whom It bad bsen openly and un
hesitatingly threatened, that their Quarter
master, or some outer obnoxious oocer-, tnouid
be shot oa th first occasion of an engagement.
Some of . these were- country regiments, and
made up of as good stuff as ever 'Went into an
army a- , i.;;; - i vc- ;'
' - " -''
Don't Want to Fight Us.
Wa had a pleasant conversation yesterday
with a gentleman oonneoted with the army in
Western Virginia, who told us tbat tnose people
In arms tbers did not really want to fight our
voop, tbai tay bad nothing against us to stim
ulate them to fight and that tbey preferred w
should be friend rather than enamlea. ' Tbat
be gathered from tbe people on the farm with
whom h conversed, and with the prisoner tak-
n by our troop. It it painful thai necessity or
circumstances should compel such a people to
be pot in a position to lose their own live, or
tak tbost of othert. Cin. Euquirer.
1 i
Mr.'Brecklnridee vesterdav In hit tDeech DOS-,
itlvely denied having telegraphed to Jeff. Davis
that Congreet would not be allowed to assemble
od tb 4'h of July, or that Kentucky would
furnish 7,000 men to fight against th National
Government. if, jr., mount, . , ..
A
FoaiTioH or rut Bwciadino Viisns.-We
learn at tbe Navy Pepsrtmeut tbat the Atlantlo
blocading squadron, Commodore Strlogbam,
consists of twenty-two vessel, three of which
the Iroquois, Dale, and Savannah ar in pur
suit of tbe pirate Jeff. Davis. The Minnesota,
the flag ship, 1 the only vessel now .at Hamp
ton Koadsi the Montlcello blockade James
Riven the Dawni York River, and tbe Mount
Vernon, the Rappahannock River. Two ves
sels attend to Chesapeake Bay; four haunt the
coast of North Carolina; tbe Wabash aud four
other vessel blocked Charleston and Sevan
nab, and ona vessel shut up Fernandlna. . The
Harriet Lane I repairing, and the Seminole
na not yet reported. 'mount wr. '
i Smut Grow Galuaha A. Grow. Sneaker
of tbe House of Representatives, is a native of
Asoiera, snagraauatea at Amherst College in
iota. ' lie nas been in congress since leou.
axenangt. J . r ,
' Amherst College wat not instituted at that
time, and Mr. Galosha A. Gaow was not born
for. about fonr years after that.' That must be
a telegraphic dispatch ' '
CT Chailis Fsancis Adams, our new Min
ister to England, (s taid to have gone to Court
in a dark blue coat, tba collar, cuffs .and flaps
embroidered with gold; white small .clothes,
white silk stockings, low shoes, and to have
carried a sword. . '
"Stimulating Okooint." Such is tho title
of a brilliantly compounded preparation (orig
inating with tbe famous Dr. Belllogham, of Lon
don) for Improving the growth, and beautifying
th condition of the human hair. We learn that
Messrs. Hersoe L. Hegeman fc Co-t .of. New
York, hava obtained the ebtire agency for the
American continent and we therefore lnrlte at'
teolion to their "Stimulating" announcement in
another column.
Holloway's Pills and Ointment—
Cancer.
ine days or "brillant operations" are no
more. Ths discovery of Holloway's Ointment
dispenied with the neoetslty of th knif,
wblcb frequently endangered tb life of tb pa
tieot. thousands or lemalea bave been cured
of cancer in the breast by the medicating ac
tion ol tbe Ointment, and tbelr lives spared to
thir families. ' The ealve follow the oanoer in
It tortuous winding, and Imperceptibly, but
thoroughly and painlessly, eradicate it from
tb system. Tbe Pills cleanse snd purify the
blood. Sold by all Druggists at 25a., C3c, and
$) per box or pot. ... ; i
'
SPECIAL NOTICES.
TIIE aCOTUII THISTLE.
When tb stealthily 'approaching Dan stepped upon
the thistle, he cried ont with ptln, and the Scottish
camp was saved. let all who hava bees lojured by
poisonous compoaads of talssatae live tb alarm, and
SV Its aMoamnity. PTlt's DlTTlTIO BAtUtATUS to
pun and safe. Bepol,f3tf WMhlnjtpn street, New
Tork. . j i j .. i ' '. .'.
TO KJTOBE ini BICKttO
HEALTH, Tbe blood Dost he purified, and all med
icines ar bm1 which do not poetess th quality ot
silaulatui the blood to discharge Its lmporltlti Into tb
bowels. BaiHHiTi's Pius possess this euallty la a
hl(b deirs,ae4 sboald bs In every family.' They art
equally uMfol (or chlldrra sod adult adapUd to both
suss, a4 aat a ianoesnt as brtad, yst or itrmmrt
as a assieun.' ' - .''
Tb Hon. Jseob Bsytrs, of flpringrllle, Isd.', wrlUi
to9r.Braadrsdi,anerdaUof Ms 11, 1861.
;I have wd year limluahle VefSUfcle Unlveml
Pills la mj faally sine 136; tbey nv alwtys Nnd,
w vhaa older medloifiM ware of avail. I fern
beta the auaus of ny noichbois uslof hnadftds of dol
lar worth, u4 I am MiJiflcd the "bar raoaivad a
tbaMd per teat, io tlene health, (hrra(h itwlr om
Tber are aw Io tbiarexlva far Billows and Lifer Die
rT" sa Asm, eud all rheaueile Caws with the
I "wt, taey are tbe treat nil
,adl tvaatvoar venerable nrma bt
I rpay sa eietlea a aeoita (tr tb
. . .-...- ...,. :
rkut and t4 UaM irtat by ta tnm,"
by k. Coot. rn1fl Colombo,, sod bv
ailre.iMi.eaiieiHita BMiteUet. x-
U t mm ef eetOreaaai, tjtspepsla, blllloos and ivl
aette, aftta, ttiiaisil . fevan aa atnea, earn
ate bat eefass, aa all enwial aeranretnetitrof health
mis ban mvarlsbly proved certain sad rce
a(l trial WIU plae tb Ittt rtUa bane
U ra ef (Maxell lloa la Oieeetfrnatloa of evsryti.
ssa. ti ' ft . !t " l . .t -. ' 1 1.
Vs. tMUtt ftetatt Bitters Will bs foand equally ef
tnMm le ailewM ef aerroos OeltUty, ijrtpeptla, bead
, 0 aVkaeai tottdeat to tuaalea ladttlcate health,
vry tal of weeks tea ef th dlrssUv errsas.
atlas, ,,W.. MOV MI, 33Ji Breadway,. T.
( by all tni&M. j g y siaye-naiwlf :
'
;
.
Th tbllowlojS U aa extract frpm a
lettrvrittay UMttrv.' J. 0. ilolmsJ 'paster' ot ths
nerreaofnt Sueet Baptlet Chan,' Broolfljo,
lb 'Jonrnsl aad KaaMngsr," Cluclnaail, , and ipmkt
roltoaet ia (avoi of tbat vorM-reaowned Bedlolae, Mm,
If nwioWi Soemwa BraiTT roa CHaram Tmnmei 1
"Wssessa advertlmneot In your, eoloauii of If as
trmtow's Sootbim Braor. ' Noirws nevtr Mid a word
Io favor of aeataat aiedlolne before la osr ur. tmt we
(eel eonpellee ia ear to yoorieedets that this Itne hum
Due wt Ti Tie rr, j biow r to m ata ri
oluks. . It if probably eoeef the mott mreeMfal aiedl
doeeef thtdty. beoaaas U i aa ef Uia bstU And thos
oryasrrtederswbehav bsbtofOM'tde better than
tsy taa Supply." ao7.-lydet
ia
,
Justice of the Peace.
HbJ? T0:-Plsas snnounc tht atm at Jaoos
saOHuqirrrim u a esnaioaw ior sivi .
ttliseenlnt election In MontaMMrr tpHIii Aa(
S, 1861, autyeet to tb dteiilon o( th Dmoun nornln-
stioiandAuch Mfh.'mMvr'nMr,'ranZr:
- J. HOST OF BKMO0BA1B.
Ma. snsoano , W. v7asson as
oandldattforJuitto -Wine rsae. at tbt sleetlon In
Uontgomery towtuhlhuitut , 1801, said sot tP-tt
fionoerajilo nomination,, and oblige
ikUOT
AT8.
IT0 BtATVWAil! ( (II "HA jO i t 'C 'i'
Tlsas annoaaou me as a candidate for r election
th offle ot J attics of tbs 7teo.fif Montgomery town
ship at an eitetloa to bs kU Aafatte, 1861. . 1 '
Justice of the Peace. WM. L. HEYL.
NEW ADVERTISEMENTS
lfWilUAM:;K-,RESTJEAUXj
Xltil vt wt-al.' i-M ' ,,v ' . ' ,.
UEaLEK IN
Groceries.
Produce,:.:;. .,., .......
. -Provisions,
' " Foreign and Domestic! Liquors,
y: Fruits,-eto. etcpwA. i
; ' ,, ii (kb1rg!jriii fMfijt laoii :"
NO. Si, N08.TH HIGH STREET,
No." 106, :South ' High Street, '
The old stand rcon(iy occupUd hy,WM. JKoCONiC
He It In dally receipt of . .
-v.: . ' .... .- ;.. '
NEW, AND FRESH COODS,
t , ,. Which bt will sell
Cheap lor Casli or Conntry Produce.
JU' floods delivered to OUt trad freelof charge.cQI
;J"18,. .:- .,.. . ,;
EAGLE-BRASS WORKS
, 1 corner Spring water St., ,
W?SB. vPOTTS -r & CO.,
.ad Manafaotortrs of Brass aad Oompotlttoa Osstlni
i . , ainlsiwa niaas won i au Kttonpuooe. .
Electro Plating. and ! Gilding!!
I """ STENCIL CUTTING, &C.
7M. H. RESTIEAUX,
! (BCOCSSSOBTO UoESS i ASBTIIAUZ) -
No. 106, South ' High " Street
i OoXjXJIXZSTJS;' ;. :
i , .. ....MAUI V
groceries; produce,
provisions;
: Toreign and Domestio IVuits,
FLOUR, SALT, LIQUORS, ETC
STORAGE fit COMMISSION.
.BAIN & SON.
Ho. 29 South High Street, Columbus,
A It NOW OFFERING
XV 2000 e.rds Traveler Brets Goods at 8X, value
SJO0 yards Travtllor Drsn Goods at JStf, va'ns SOcts,
xuuu jams tof inn Derate at ih, vau etsu.
1000 yards treaoh Oraadlos at UK, value SO etnta.
SOOo rards fast Oolored Lawn at 10, raise IS oenta. -1000
tarda fonlard DrM Billet tt 37. value 0 oentt.
1500 yards Super Plain Black 811k at 1 0O, valoe 1 25.
Robes of Orgendio Bang, and Boliah Bsrage, at one-
nan vutir vaiue. , ,, , , r
- i ' BAIN k BON, . .
Jt22 . . .i . SO Booth Ulh Street.
Elegant Lace Mantillas.
JBjSLXN eto SON,
N"o. 29 South High St.,
Hava just opsned an Invoice of very larg an
bandtome
Rusher; French;' and. chantill a
i ! lace mantillas and pointes.
TVide French Laces fob . Shawls.
Vry Deep French Flouncing Laos. 'i
Real Thread, French, Chantllla Gtnaveae
VETXS. v.;
Valenciennei, Point do Gaze, Brusgals
: and zmeaa Laoei and Collars,
VALENCIENNES TRIMMED H'DKFS,
MALTESE LACE COLLARS & SETS,
- 1 LINEN, COLLARS CUFFS, , : f
o , J Iq ne Shapes,
V PAPER .'COLLARS & CUFFS,, !
' ' - ' For traveling,
PRICES TJNTJSTTAIY LOW.
i ii
r i
Traveling Dress Goods.
MOZAMBIQITIs', POPLINS, BBSPHZBD'g OHICKS,
BILKS, POIL SB OHIVRBS. ,
LATELtAS, SftOOHl VAUMOIAfl, aie. 'o.
Th best and most (athlonablt styles In th stty, .,
AT VERY IXTW. PRICKS. '
B4IN St SON, "
1 SO South Blfh Street.
jeSl
I
raicn xiotxoid
" ' '" fi -it
rifom the Ntw V ors Obeervar.l '-"'t'-
As all liartlftt atniifuhirlM Inrin V.aVlh. . .L
- - --n - n wivtuun mvuv
lite NBil Mr. Hnmauoaiita on auh nuhiuuM
and an a so eompelled to make returns to him, nnder
oath, aa to thtaumbsr sold, his books lire soonest atata-
-r."". " ., "';'"." tounw wt nav ootaiDoa m
fcHowlni statutlos. Of tht macblstt mad la tb year
IBM, there were sold, .
7 Whler Wilson......... .81, a ,
I. at. Slnier Oo 10,M
" flrevar fc BUer...,. ...JOJWtt.t i, :
Showing th ttieeaf Wheeler fc WUkd to k donNe
laoaa at any ether Conpny,M i vi. - m. .: .
Awarded tht highest eretame- at ths'
' f i United States fairs at JMSjlotf and lfl0 , .? . -
. l ' alsertto - .v.-'-'k ;-
ObtoBtalt tAjs of 1M9 and 18M. - -v
asdatseartyall t. County funis Uientaei.
Ourprieea,at the laet radtetM, are aa is as any
oe tUcA machine now told- aod aat a titat bigber tban
ths Interior two (Areud aioea f4 wMsMn, now
foretdnooa themarkaer ' ' " 1 -
Tba WUBSLKM i WILSON MAOBIII wakes th
Leo Stiob theoalranewhtohamnot eeiwveltd. It
Auca oa Botb BiDtaof to (oeaa, loevuc no rVat er
iitaiUt andtr.e4de -. . ' ' 'i '
M wMcAtoe tcarraatd-l tm, md inttrucHon,
ttvea ia tbelr ase, free or enana. i -r
. ,H. CJtr,al High .. -Colombo!, 0.
i'i-..-wi 1 WM. BUMMaHm CO.,
eeeS-Swd3m4w6sai Pike's Opera Hoaee. OlneinnaeV
la
U
: at' . Gfintoa Matiingn, v a,
Of
14? .4';g-i; tirWa .ai4 Hl in
I ,' . .. jiiiii..,.jn SAIN i SON.
faMJ'' ' ' .Na-WaoathHlilllt)'
Summer Arrangement.
Little Miami Columbus & Xenia
Hons
TP
Little Miami Columbus & Xenia RAILROADS.
f or Clnoinnati, Dayton ft IndianapolUl
Through to lndlanaooli witaoa Change of Cars
and but One Change of Cars between t
Mj i I t;ColuiabuB and St. LouU. J lV
Four Trains Daily from Columbus.
jj, j FIRST TRAIN
ACCOMMODATION at S a. m.. stopping at allat-
ilons between Oblumbus and Olnolnnati aod Viylaa, ar
riving at Cincinnati at 1005 a. m.,and at Dayton at
8 10 a.m., oonaeoUni at Dayton, for Indianapolis aid
tht Weil.
8ECOND TRAIN. . "
1 No. V1XPRE3S at 11.40 a.m. .stopping st JtfTenon ,
London, Okarteeton, Oedarvllle, Xenia, Spring Valley,
Oorwia, I reeport, fort Ancient. Morrow St., Lebanon,
f otter's, Loreland and Mllford, arriving at Olnolnnati
at 4.30 p. m., Dayton at 9.45 p. m.,oooneotln( with the
Ohio and Mlnlttlppl Ballroadfor Louisville, Ky., Vin
otouea. Oalro, St. Lome, Mew Orleans, eto.t at Dayton
Ipr Iodltntpolle, Laryette, Terra Haute, Cbiesgo and
all Westtra polntt. .. i .
' ! ; " THIRD, TRAIN.
MAIL at 810 p. m.,itobplDgat all stttions betusen
Oolumbos and Xenia, and at Spring V alley, Oorwia,
Morrow and Lovelaad, arriving at Cincinnati at 8 a. a
. ,.. FOURTH TRAIN. - .
NIQDT EXPRESS, vis Dtyton, at IS W midnight,
stopping at London, Xenia, Dtyton, Mludletowa and
Hamilton, arriving at Olnolnnati at i.U a. m.; at Day
ton at 8. Me. m. oonneotlng at Cincinnati with tit
Ohto and Mlnlttlppl Railroad lor Lonlivllle, Brantvllle,
Vlnoennes, Cairo, Bt. Louli. Memphli, Ntw Orltaaa,
and all polntt South and South-weat; alio, at Dayton
for ladltnapolls, Lafayette, Terre Haute, Chicago, etc.
JCy for further Infortiition and Through Tlckttt,
iptily to M. L. DOHEltir, l'loltet Agent, Union Depot,
Culumkut.
, : ... ; ...'. ' P. W. 8TBADER,
Oentral llcktt Agtnt, Olnolnnati. "
'-' ' " - JN0. W.DOHKBTT,
rpT-rj 'm -f Agant, Oolumbna, '
" H.W'.WOODWABD,
-T,
" . - ' Suptrlnttndent, Olnolnnati.
Columbui, Jaly 14, 1801.
IRISH STEAMSHIP LINE,
-- ' 1 I... .. ,t.-
Steam Between Ireland aod America.
NEW YORK, BQ3TON AND QALWAY '.
The following new and magnificent flnt-clait paddlt
wbeel Steamthlpt oompves tbt above lion . , . .
ADBIAUO, 8,888 torn borthtn, Otpt, J. AUuar
' (Torawrly of tht Oolllns LIos.)
HIBERNIA, 4,400 tons burthen. Capt. r7. Paowsx.
COLUMBIA, t 4CO . " . h. L x; Tea.
ANOLIA. 4,400 - hratnifOM.
PAOIH0, 8,00 ... i gBIlB,
P1UN0K ALBERT. (Screw.) '
: ., . f ... .3,300." !... J.WAtia.i
6nt of tht above ships will leave Ntw Tork or Boston
alternately every Tueadty fortnight, for Oalway, car
nine the government malls, touching at St. Johns,
N. f.
The Steamers of this lint have been conitrnoted with
iht greatest care, nnder tht luptrvialon of tht govern
ment, hare water-tight eompirtmtnti, end are unexcel
led toroemfort, atfety and speed by aoy steatosis afloat.
Tbty art oommandtd by able and experienced omoeri,
and every exertion will be mad to promote tht oomfort
of pasaengera.
t An;experltnoed Surgeon attached to each ship."
- KATES OF PASSAGE. - -Flrst-cltis
N. Y. oi Boston to Oalway or Liverpool I loo
Second-clan, ' " 7j
Jlrst-olassr t ' " " I to 8 1 John's 3i
Xaird-olatt, " ' " to Oalway or Liverpool.
or any town In Ireland, on a Railway, - - - SU
Thlrd-olatt pasaengers are liberal ly aupplled with pro
visions of the best quality, ouoked and served by tbt ser
vants of tbt Company.
-RETURN TICKET!. r
' Parties wtihing to tend for intlr friends from ths old
Country can obtain tickets from any town on a railway, in
Ireland, or from the principal cities of England snd Scot
land, at very low rates. .
Fatttngen for Mew Tork, arriving by tht Boaton
Steamers, will bt forwarded to Mow York fret of chargt.
' for paatage-er furthtr information, apnly to
j . Wat. H. WI0EHAH,
At tbt office of tht Company, on tht wharf, feet of
Canal street. New York.
, HOWL AND fc ASPINWALL, Agents.
aprlllfcdOm. ,.
: PROF. U. MILLER'S
HAIR MVIGORATOR
9
An Effective, Safe, and Zoo'nomleal
Compound,
rOft RESTORING GRAY HAIR
To its original color without dytlng, and pravtntisg
uair irom turning gray.
FOR PREVENTING BALDNESS,
And oaring It, when there Is tht least partiolt of vltall -
or Ronperauvt energy remaining.
FOR REMOVING SCURF AND DANDRUV
I And alleutaneoaaaffecuont cr th Scalp.' ,
FOR BEAUTIFYING THE HAIR.
Imparting to It an nneqaled stoat and brilliancy, maklnt
It soft and silky In Its texture, and causing It to cur
rtadlly. -
Th great celebrity and increaelni demand for this na-
qualed preparation, oonvtneet the proprietor that ont
trial tt only necessary to aatbfy a diacernlng public of Its
toptriorqualltlea over any other preparation in tat.. It
Cleanses the head and scalp from dandruff and other
entaneous diseases, canting ths hair to grow luxuriantly
giving it a rich, soft, glotay and flexible appearanoe, and
also, where the hair U loottning and thinning, It will grra
ttrength and vigor to the roots and restore iht growth to i
note paru wmcn nave Become nam, canting it to yield a
reeh covering of bair.
Then art hnndredi of ladlet and eentleman In Haw
York wbo have bad ihelr hair restored by the nte of thlt
Invigorator, when all other preparation! have failed. L. '
M. hat in bis potteetlon letlera innamtrablt tetttfylng
to tht above facts, from peraoni of the hltbaat ndtMti. -
bility. It will ollectually prevent tbe hair from turning -
until tht latest period o( ii(t and inoatet where'the hair -hah
already changed ltsoolor, the est of tht Invigorator 1
will with certainty restore lt to It to its original hat, gl v -
At a periumt ior in -It
ptrticultrlr reoosa- :
mended, having an agreeable fragrance; and the great fa-
tiiltlet it affords in d retting tht hair, which, when moiat
with tht Invlirorator.-can bt d retted In tnv required
form to as to pretarvt Its place, whether plalnor In curia;
henot the great demand for It by the ladlet at a ttandard
toilet artlole which none ought to be without,! tht price
placet lt within tb reach of all, being - - '
Only Twenty-Rve Cents
per bottle, to be bad at all respeotablt Druggisbi and
rerramtrs.
L. MILLIB wonld call ths attention of Parenta anil
Ouardians to the oat ot hit Invigorator, In xaitt when 'j
tht ehlldrea't htlrlnclfnet to bt weak. Tht net of it
laya tht foundation for a aqodhtad of hair, aa It re
moves any impurities tbat may have become oonneoted
with tbe scalp, tht removal of wkloh la neooteary both
for the health of the child, and tht future ppaaranot of
its Hair. . v. ........
Oitmo. None ten aint without tht fao-slmlle LOOT 8
MILLKK being on tbe outer wrapper:, alto, L. MIL
LEU'S UAItt INVIQOBATOU, M. Y., blown In tbt
glaes. ' ".'' ' - '
Wboletelt Depot, M Dey strtat, and sold by all tht J
prlteipal Merchants and Druggists throughout tb world , A
Liberal dlKount to purchaser! by tbt quantity. , x 1
I alto dttire to preeeut to the American PubUt my "i' '
ITKW ADD m?0VZD t LTTSTADTAHEOUa
LIQUID HAIR DYE,
which, after years of setentifle experimenting, I have
brought to perfection, lt dyts Black or Brown Instantly
wtthoutlnjury to tht Hair or Skin; warranted tbt btit
articlt of Iht kind In tiltunc.
PRICE, ONLY 0 CENTS.
Depot,' 66. Dey Sti;' New. York; -yj
otm-dltwly.' j., - '.-.r.M.-.i -:' t -l -?,
ExmAonomAny bargains j
waBaa f f ;tJ -1 I ' t'
BAnSTs&SON;
i
.1 t .1,"
a ! 10. S9 SOUTH B20B BIBKI, .. o..;
.... i 1
A.BJB3 . ITO'W: 'OrFHBlWP.t,,
1,000 yards Saotr Plain Black Silks al tt OOTSto
1 BS per yard. , J J , T; . M
StSOOvard Ttettltig Dree and Mantle ; at 3:
H If cents Value 20 cents per yard. . ,
8,000 yard Whit irllllantes at it ttiA &
value to teats par yard. :::'t .7I "T.'.'C
StOCO yards Fin asdDomtttto Olngbams greatly aa-
der value. ...1 j . :.! If I ,.
I
iAroe and desirable lots op 'n
K02A113IQ.TE!, BAUOMJTKS,!
CHAUM, F0C1ABD IILW,
I E50LIBS 8ASSaB,tAmiAS,
1 LAWKf, OAU00I3, F0PHH8, '.'
I AND ALLTOTHERrirT".
New saxd mehionabla Urmmm. Good
th moatuetlrable styles and at very lotert prlcer
I ,T3sa;.a.t ii i J s .til
J XJ 1 1 Xa X iaOL O I r i .
all materials mad la tht mott sl'yibh aunntV afuir "
the latest Parts fashlonsjths most lfaat ff if fjd'
BAUIsflOirf ntfai
PT ataHlrttrett j
.v.
xml | txt | http://chroniclingamerica.loc.gov/lccn/sn84028645/1861-07-20/ed-1/seq-2/ocr/ | CC-MAIN-2014-35 | refinedweb | 9,005 | 72.76 |
Please help me define a class level "standID" type of variable to hold the stand's ID. Also please help me correct my typo in my constructor. Test class needed to test the JustSold() method as well.
Thank you
import java.util.Scanner;
public class BudgetPlan {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the current price: ");
double cost = in.nextDouble();
System.out.print("Enter the inflation rate in percentage: ");
double rate = in.nextDouble();
// convert the percentage rate into units
rate = rate / 100;
System.out.print("Enter the number of years the item will be purchased: ");
int years = in.nextInt();
// for each year, increment the price after calculating it
for(int i=0; i<years; i++) {
cost += cost * rate;
}
System.out.printf("nThe cost of the item after %d years will be %.2fn", years, cost);
in.close();
}
} | https://www.coursehero.com/tutors-problems/Java-Programming/11521650-Please-help-me-define-a-class-level-standID-type-of-variable-to/ | CC-MAIN-2018-17 | refinedweb | 145 | 61.33 |
send you reminder for all your meetings, calls, meets, attending the seminars, and many more. We have discussed and implemented this step in our previous blog.
Suppose, now you have and update in your call or meeting. For example your meeting is postponed or cancelled. In that case, you have to tell your assistant about the update so that it will not remind you as per the previous time. But how do we do it, that’s all you will learn in this blog.
Now, lets discuss and implement it.
Implementation
For the implementation, it’s important for us to understand that what conversation flow we want to follow in this blog. So, here is the conversation that we will follow to make you understand abot this concept.
User: Hey buddy! Bot: Hey, How can I assist you? User: Actually my meeting has been postponed so don’t remind me for the meeting now Bot: Sure, No problem.
So, this is our conversation as per which we will make the changes and we will understand the how to cancel the scheduling.
As you have already seen in the previous blog, that how to schedule the reminder so here are the changes that you have to make in to the rasa files,
actions.py
class ForgetReminders(Action): """Cancels all reminders.""" def name(self) -> Text: return "action_forget_reminders" async def run( self, dispatcher, tracker: Tracker, domain: Dict[Text, Any] ) -> List[Dict[Text, Any]]: dispatcher.utter_message(f"Okay, I'll cancel all your reminders.") # Cancel all reminders return [ReminderCancelled()]
In the actions script, you can see I have created a class with the name “action_forget_reminders” in which we are just calling an utter message saying “Okay, I’ll cancel all your reminders.” which is actually not cancelling any reminders. Reminders are cancelled from the return statement where I have called “ReminderCancelled()”, which will cancel all the existing reminders.
It’s because by default if you will not pass any reminder name so it includes all the reminders that will be canceled. But if you will return “ReminderCancelled(“my_reminder”)” like this then it will only cancel the reminder with the name “my_reminder”. So in this way, we can cancel any reminder whether all or any specific.
nlu.md
## intent: ask_forget_reminders
- forget about it
- don't remind me!
- Forget about the reminder
- do not remind me
- Actually my meeting has been postponed so don’t remind me for the meeting now
- do not remind me!
- Forget reminding me
- Forget reminding me!
This is the intent that we created as the user input based on which our chatbot will cancel the scheduling.
domain.yml
intents:
- ask_forget_reminders:
triggers: action_forget_reminders
actions:
- action_forget_reminders
In the domain file, i have added the intent with name ask_forget_reminders which will trigger the action that we created for cancelling the schedule reminders.
You can also check this video for more clarification,
Before training the model and checking it’s working. Make sure you already have the data added for scheduling a reminder as we have discussed in the previous blog. Check the full code here:
Download Full Code for Reminder Schedule/Cancel bot
Now, train the model and test it with the given commands,
rasa train
rasa x
here is the output for the above code,
Time to wrap up now. Hope you liked our content on How does your personal assistant can help you cancel the reminder. | https://innovationyourself.com/cancel-the-scheduled-reminder-to-call/ | CC-MAIN-2022-21 | refinedweb | 564 | 62.78 |
Dirty Coding Tricks To Make a Deadline 683
Gamasutra is running an article with a collection of anecdotes from game developers who had to employ some quick and dirty fixes to get their products to ship on time. Here's a brief excerpt: ?" Have you ever needed to insert terrible code to make something work at the last minute?
Here's one... (Score:5, Funny)
Re:Here's one... (Score:5, Funny)
Re: (Score:3, Funny)
Don't be absurd. Even the lowliest coder would know enough to write #DEFINE PSEUDO_RND_BSOD = 1
Re:Here's another one... (Score:5, Interesting)
This is the code for the Apollo 11 lunar lander flight computer. [google.com]
and yes some of my code is in there along with the equivalent of a few "goto's
Lots of bright people worked on this and in some circumstances a "goto" is required.
Re:Here's another one... (Score:4, Funny)
I'm trying to get this code to work. I'm at an altitude of 6,000 ft, hovering over the Sea of Tranquility, and the darn thing keeps crashing! (The code, not the lunar module.)
PLEASE don't connect me to that Bangalor helpdesk again! I am in serious trouble here!
Has this been tested for Y2K compliance?
Did we not pay our last support bill?
- Major Tom [wikipedia.org]
One word.. (Score:5, Funny)
Re:One word.. (Score:5, Informative)
The goto statement is very useful. Your dislike of it is irrational. Do you even know why you do not like it? Often, goto is the best solution to given problem.
Re: (Score:3, Informative)
I have not used a 'goto' statement in about 15 years now. But it's not some irrational fear. It was all due to someone saying 'there's no situation that requires a goto' and 'goto statements make code hard to read'.
And after I used goto a little more, I realized they were correct. In any good, modern language, 'goto' is completely unnecessary and makes your code harder to read.
If you're breaking out of a loop, you should use 'break'. If you're continuing a loop, 'continue'. If you're handling an error,
Re: (Score:3, Informative)
So, where's your example?
Finite State Machines. They really are quite difficult to implement without goto logic and is exactly what you do when discussing theory.
Re: (Score:3, Insightful)
as well as some oddly structured loops for which try/catch logic doesn't get you all the way
Such loops are almost certainly buggy, almost certainly maintenance nightmares and I'll stick my neck out and say certainly unnecessary. The logic needs redesigning. So they are examples of dirty tricks to get code out of the door, as the GOTO poster suggested.
Re:One word.. (Score:5, Interesting)
But as below says, they make error handling an easier task as well as some oddly structured loops for which try/catch logic doesn't get you all the way
Ugh. Magic invisible gotos FTW! [joelonsoftware.com]
Re: (Score:3, Informative)
Re: (Score:3, Informative)
From the linked article: [joelonsoftware.com]
I have done code that way, before exceptions came into vogue. To do it right, you've got to have many many many error-checking if() statements after every call to any function that could fail. That could mayb
Re:One word.. (Score:5, Interesting)
I like the way my former VB teacher put it (and yes I use the occasional GOTO, but then again I learned in the real BASIC-Commodore BASIC) he said "The GOTO is like a chainsaw. yes, some folks can actually make good things, and even make really nice carvings with a chainsaw. most just make a big fucking mess."
Of course me and him both laughed our asses off when some 19 year old tried to rip off my code and pass it off as his own. After laughing and giving the kid a big F the kid said "How do you know that he didn't steal it from me?". So he asked the kid where he learned VB and which OS and the kid said "Windows 98 and the VB I got from this class!" and the teacher projected the code onto the board and said "Now class, does anybody notice something a little...weird about this code?" and a girl popped up and said "Why are their numbers before the lines, and what is a GOTO?".
The teach just laughed and said "once upon a time their weren't any GUIs on personal computers. All you got when you turned it on was a blinking CLI and you had to write your own programs, using VERY old syntax. The person who wrote this is used to working in teeny tiny amounts of memory and using the old style, which works just fine if you know what you are doing, but if not it'll blow in your face like Mr. Greene found out when he tried to snatch this code and incorporate it into his own without knowing how it works" he then turned to me after staring at the code for a minute and said "Atari or Commodore?" and I looked shocked and said "Commodore VIC20, but how did you know that?" and he said "because I have been around long enough to have coded on just about everything, and that looked liked Atari or Commodore code. Very efficient, but about as subtle as a chainsaw." which is when he gave me the chainsaw quote.
So I have never forgotten the chainsaw quote, and while I can wield the chainsaw without making a mess, I saw first hand when others in the class tried to use GOTO what a mess you can make if you don't know EXACTLY what your code is doing. He caught me outside a month later and said "thanks a lot, I hadn't seen a GOTO in ages and then you come along and it spreads like the damned clap. Giving these youngsters GOTO is like handing a monkey a sledgehammer and letting them loose in a bomb factory. There is no doubt they are going to go boom, the only question is when." but what can I say, I'm just an old greybeard that was used to numbered lines and GOTO.
Re: (Score:3, Insightful)
You were very, very lucky, in an awesome way. None of my programming teachers were EVER that savvy.
Re: (Score:3, Insightful)
Re:One word.. (Score:5, Insightful)
I’m a goto-user, but this is a bad reason to use them: If you regard language features as ‘just’ syntactic sugar, why aren’t you programming in raw machine code? That is what everything eventually gets turned into anyway.
You use gotos when the normal control structures are inadequate somehow. It doesn’t matter what the compiler does; source code is for humans.
Re:One word.. (Score:4, Insightful)
You use gotos when the normal control structures are inadequate somehow.
This is the heart of the issue: control structures are a well defined, easy to follow, hard to fuck-up subset of the things you can do with goto. If you can do it reasonably with a control structure, you shouldn't use goto, because it makes your code more readable. If you can't, then you should consider if your program should be restructured (which is why goto is dangerous to novice programmers). If not, then you can use a goto.
Of course, all bets are off when you're scraping for clock cycles with machine code, but that's not necessary most of the time.
Re: (Score:3, Insightful)
So formatting is worthless, then? And why do we have so many languages, many of them domain-specific? Compilers don’t care about how understandable the metaphors are or how many lines are needed to do a specific thing.
Re:One word.. (Score:5, Funny)
So formatting is worthless, then?
No, formatting is for successors and maintainers. As fellow coders, they're not human, strictly speaking.
Re: (Score:3, Insightful)
Every [gnu.org] of C) is compiled as an indirect jump.
A more interesting concept is continuation [wikipedia.org] Regards
Example (Score:5, Interesting)
#include <stdio.h>
void *f(void)
{
a:
printf("Here!\n");
return &&a;
}
int main(int ac, char **av)
{
goto *f();
printf("There\n");
return 0;
}
Re:Example (Score:5, Informative)
OMG. I didn't even knew you could write that in C (and I have my name in the comp.lang.c FAQ...)
Of course, I checked C99, and, no, you can't write that:
3.6.6 Jump statements
Syntax
jump-statement:
;
goto identifier ;
continue ;
break ;
return expression<opt>
identifier being defined as:
identifier:
nondigit
identifier nondigit
identifier digit
So, goto *f() is a no-no (as is probably &&a)
But, anyway, wow. Gcc actually compiles that to something that somewhat runs...
Re: (Score:3, Informative)
Yes, it is non-standard. But quite useful for some things (although not in the way written above). Consider a function that needs to return and then resume where it left off the next time it is called. Could be done by wrapping it in a large switch, but this is more direct and efficient.
#include
void *f(void *p)
{
if(p != 0)
goto *p;
return &
a: printf("A\n");
retur
Re: (Score:3, Interesting)
I don't think the efficiency is worth having a non-standard construct, considering a simple switch would do the trick.
You could also split the function in multiple function (because having all the code in the same function is not very useful as local variables are trashed between executions), and directly returning pointer to the next function to call (hence you could spare of the cost of actually calling f() before jumping).
Anyway, a nice trick. Didn't thought I would learn another one in C. The worst I ev
Re: (Score:3, Insightful)
I pity the developer who has to maintain your code after you've moved on.
Re:One word.. (Score:5, Insightful)
Breaking out of a deeply-nested loop, as can happen when you’re looking for a specific element in a multidimensional array. The alternative involves adding state variables and complicating the logic terribly.
Re:One word.. (Score:4, Insightful)
Ewww.
1) decent languages support labeled for/while cycles and apropriate "break label" constructs. It is not so different from using goto but has much better semantic meaning and thus allows neat optimalizations (with, say, paralelization in mind)
2) if you do this kind of thing, you are MUCH better off separating lookup code to method or function and simply using return statement once you find it without having to break from cycles per se. Cleaner, more structured.
Re:One word.. (Score:5, Interesting)
You often cannot develop software with the language you want, but must develop it with the language you have. C has no such features and, therefore, goto is used more often than in languages that have them. Fit the strategy to the tool.
This is reasonable, but it assumes some other function can do the needed cleanup code or other data massaging just as cleanly. If the goto is being used because finding the value is an error condition, you often have to do certain things as soon as possible in the code so you do not lose important debugging information.
And, no, exceptions are not part of C, and setjmp/longjmp is, if anything, even less likely to pass code review. An advantage of goto is that you can keep the cleanup code in the same function, visually close to the rest of the logic and sharing the same locals.
Re: (Score:3, Informative)
Yes it is, goto requires a label, and thus requires someone reading your code to go hunting for it. Return is known to push control flow to the exit of the function. One obfuscates code, the other doesn't.
Re: (Score:3, Funny)
I agree, if you need cleanup code... But I don't write code with side effects, so there's no problem whatsoever. No side effects means no clean up.
Re: (Score:3, Informative)
Error handling in C code is my typical example of that. It mostly avoids the need for lots of if statements to make sure that you clean up all that you need to and nothing more.
There are other ways to go about it, but in general I'm not convinced they are better.
The most common use of "goto" in that circumstance is to enforce "only one return".
Which is every bit the pedantic lunacy that goto-hate is.
Re:One word.. (Score:5, Insightful)
Hardly pedantic or lunacy. For example, pick one of the drivers from the Linux kernel, e.g. this one [sourceforge.jp]. Look in particular at the "geode_aes_probe" function.
The structure looks like a pyramid. On one side is the setup phase, on the other side is the cleardown phase. If one of the setup operations fails, then the "goto" jumps to the appropriate cleardown operation and continues from there. If the top of the pyramid is reached, then return #1 (success) is used. Otherwise, return #2 (failure) is used.
This function could be written in C without using goto. But would it be as easy to read and as easy to maintain? Doubt it. As it is, it's perfectly obvious what you would need to do in order to add a new capability to the driver. Tricks to work around "goto" would only obfuscate the functionality.
Re: (Score:3, Insightful)
Whether that is better or not is subjective. "Goto considered harmful" has become dogma, but while your example is a very good example of goto used well, most programmers would use it to write spaghetti code. Barring the use of the keyword means that it does only get used by people who know exactly what they're doing.
Re:One word.. (Score:5, Insightful)
I'd agree with all of that. Like C itself, goto is a powerful tool that is easily misused by beginners, but is still very useful in the right circumstances.
Re:One word.. (Score:5, Insightful)
I can't figure out if I'm the only sane one or the only crazy one. Especially given the 'pyramid' referred to - I don't see a pyramid unless it's rewritten to use nested ifs.
To me, nested ifs are much easier to read - they convey the meaning/intent of the code a lot better. As in 'if this function call works, then do this. Otherwise, just clean up and exit'
How is this so hard to understand?
geode_aes_probe(struct pci_dev *dev, const struct pci_device_id *id) {
int ret;
if ((ret = pci_enable_device(dev)))
return ret;
if (!(ret = pci_request_regions(dev, "geode-aes"))) {
/* Clear any pending activity */
_iobase = pci_iomap(dev, 0, 0);
if (_iobase == NULL) {
ret = -ENOMEM;
}
else {
spin_lock_init(&lock);
iowrite32(AES_INTR_PENDING | AES_INTR_MASK, _iobase + AES_INTR_REG);
if (!(ret = crypto_register_alg(&geode_alg))) {
if (!(ret = crypto_register_alg(&geode_ecb_alg))) {
if (!(ret = crypto_register_alg(&geode_cbc_alg))) {
printk(KERN_NOTICE "geode-aes: GEODE AES engine enabled.\n");
return 0;
}
crypto_unregister_alg(&geode_ecb_alg);
}
crypto_unregister_alg(&geode_alg);
}
pci_iounmap(dev, _iobase);
}
pci_release_regions(dev);
}
pci_disable_device(dev);
printk(KERN_ERR "geode-aes: GEODE AES initialization failed.\n");
return ret;
}
Re:One word.. (Score:5, Funny)
Pyramid? It looks more like the players' ship sprite from Galaga, rotated 90 degrees...
Damn, now I want to play Galaga...
I see two unconditional jumps here (Score:3, Insightful)
But I might have missed some. There is not much difference between "return 0;" and "ret=0; goto exit_function;". Both are unconditional jumps there is no rational reason why one should be "considered harmful" and the other not.
Re:One word.. (Score:4, Informative)
How is this so hard to understand?
It's not. But nor is code that uses goto in the idiom that FourthAge posted above.
My objection to that code is that if you do even just three or four allocations, you start getting very large indentations pretty fast, especially if you like 8-character indentations [sourceforge.jp]. (They get pretty long even with 4, which is what I like!) This causes a problem if you restrict yourself to 80-columns [sourceforge.jp].
Arguably this is a problem with restricting yourself to 80 columns, but that's not entirely unreasonable even if I'd rather the limit be ~100. But guess how many your code uses? Your longest line is 109, longer even than my longer preference. Even if you use 4-character indentations, your longest line is still 80 characters.
If you reformat your code to use 8-character indentations and 80-character column limits, your code would become a bit uglier as you'd have to wrap four lines (a couple of which don't really have a good breaking point), and hence a little harder to understand on its face.
By contrast, the original code fits entirely within 80 characters (admittedly only just) without anything remotely like an awkward line break.
Further, in some sense it doesn't entirely follow the flow of the code. Perhaps this is a vice and not a virtue, but I tend to think of places where there's an unusual condition (like a failed allocation) as not on the same "level" as normal control flow. In this sense, I would think of that procedure as basically linear "with some provisions for exceptional conditions". In that sense, your proposal of the cascaded ifs doesn't really match my mental model of how the code behaves -- the indentation of the normal code changes depending on how many exceptional conditions might arise, and there's not really any reason why it should by that model. By contrast, the original code matches it.
(Incidentally, "linear with some provisions for exceptional conditions" is basically how I'd write it either in a language that supports exceptions or a language that has RAII. In the former case, there's a decent chance do just one try block for the body of the function, and in the associated catch test to see if each item is allocated in turn. (This doesn't match the structure of the real code exactly, but it's closer to it than it is to your nested-if code.) In the latter case, you'd have basically the real kernel code except that the deallocation would be in the RAII objects' destructors. Again, no nested ifs.)
Re:One word.. (Score:4, Funny)
If you were going to do that without goto, use a while with a break instead of ugly nested ifs.
while(1)
{
if (!start_condition) break;
action1();
cleanup1();
if (!test_condition1) break;
action2();
cleanup2();
if (!test_condition2) break;
}
And so on
... it basically gets you exception handling formatted code. Of course, goto is probably still cleaner :)
Re:One word.. (Score:4, Informative)
"How is this so hard to understand?"
For me, it's hard to understand because your most highly indented lines wrap off the edge of the window, back to the left margin, wrecking the indentation cues. In an IDE, it sets a limit on how many conbditions you can check before having to scroll around to see the whole function.
I used to work at a company where this was the standard and I was never fond of it.
Re: (Score:3, Insightful)
But why use a loop + break, when your loop isn't really a loop (i.e. it only executes once)? Every time I see this trick, it makes me cringe: it is just a goto in disguise, and its sole reason for existence is that disguise! If the given situation is best handled by goto (and there are many such cases), then don't be shy and just use it.
Re: (Score:3, Insightful)
Re:One word.. (Score:4, Insightful)
Actually most exception handling constructs are even worse than goto, because they can unwind the stack an arbitrary amount. This is because they are taken from languages like Lisp and Smalltalk, which had accurate garbage collection and stack introspection and so could be used safely, and plonked into languages which have neither. In Java they're not too bad because you have to explicitly declare every exception that you can throw and so they become part of the interface, but they are horrendous in something in the C family. There's a nice Raymond Chen article where he writes the same bit of code with and without exceptions, and it's clear where the bug is in the exception-free implementation (error value ignored) but with exceptions it's very difficult to spot and the number of possible code paths grows alarmingly.
Goto in C is not like goto in BASIC or many languages from the '70s and earlier, which was basically a higher-level wrapper around a jump instruction. In C, a goto statement is only allowed to jump within the current function, so it doesn't break structured programming too badly. Exceptions and longjmp(), do. Longjmp(), as it's traditionally implemented, is the worst because there is no way for any code in intervening stack frames to handle cleanup and so it's almost impossible to use without causing resource leaks of some kind. Non-local exceptions are almost as bad, because they hide multiple return paths. Sometimes it's cleaner to have two or three different return statements in a function, but with exceptions every single function call is a potential return path unless you wrap every single call in a try / catch block.
return, break, continue? (Score:4, Informative)
Have you ever wrote a function / procedure with more then one return statement? Or used break or continue in a loop? Then you can use goto as well. From a structure point of view goto, break, continue and return are all unconditional jumps. They are one of a kind. And looking back in retrospect: Since goto need to be paired with a label it's the least evil of the group.
Note that Pascal the archetype of structured programming had goto but it did not have break, continue or return.
pretty much everytime I write in (Score:3, Insightful)
Balancing act (Score:4, Interesting)
University Assignments. (Score:5, Funny)
Once I had an assignment due and at the last minute before being evaluated, realized I had made a huge mistake, even though the code looked OK...
Too much time playing games in class and I was about to fail the course unit if I didn't pass that one test (right at the end of a semester)
So I ran the program, adjusted the output in a word processor, saved it as a file and threw some code hidden in the comments that read the file, outputted it and exited.
Three minutes later my code was evaluated... I was the only one who passed.
Fortunately, no one investigated too carefully at the time why I was the only one who passed, because after trying to fix the code later in my own time, I realized the source data we were all supplied was corrupted.
Inevitably, Later the same lecturer came to the same conclusion when his program didn't work either and cornered me to ask why mine worked (of course he was suspicious). Thinking quickly, I told him my source data was corrupted and that I fixed that first so my program would work. I don't know if he believed me, but he accepted the story.
Fortunately, I got away with it and I got to keep the pass.
Re:University Assignments. (Score:4, Funny)
Similar story.
In one of my "Intro to C" mid-term exam, one of the (sit down in the 'puter lab and spew code type) assignments was a simple string manipulation exercise. After I was done with the program, while sitting around waiting for the output-verifying lab drone to come over to my place, I noticed all she was doing for the other folks with the same assignment question was key in the same series of words as test inputs. I saw this, and quickly whipped up another little program that basically displayed a prompt, and did a printf("{hard-coded desired output for same set of words}"); and ran this piddly little pile of 'code' when she stopped by my machine.
Sadly, I passed..
Re:University Assignments. (Score:4, Interesting)
You laugh, but that's the basis of 'Test Driven Design'.
:D You were only supplied with 1 test, and you passed it. Had their been more tests, your code would have had to be what was really wanted.
I've started to think about how a class could be run like that... Create a series of unit test sets that progressively test more of the program. For each assignment, give the students the next set of tests and have them code to make the tests pass. In the next class session, work to show everyone how to make it happen, then give the next set.
Re: (Score:3, Interesting)
DOS to the rescue... (Score:3, Interesting)
> Once I had an assignment due and at the last minute before being evaluated, realized I had made a huge mistake, even though the code looked OK...
I once did almost the same thing, except that I wrote the entire assignment the first day we got it, during class. But I couldn't turn it in yet. And nearly forgot about it. So I turned it in at the last minute...
Except that I had misread the specification! Oh, the program worked just fine, but it printed everything to the screen. It was *supposed* to go
Re:University Assignments. (Score:5, Interesting)
Not the only lesson (Score:5, Insightful)
Well, in part, but another important lesson in science labs is learning to report the truth, even if is disappointing and not what you want. This is an important lesson and unfortunately even some well known scientists [wikipedia.org] don't learn it,
Re:University Assignments. (Score:5, Funny)
To this day I continue to find typos in my code but less and less bugs-in-libraries.
That's because the ratio of code-bugs to library-bugs increases with the programmer's age, even if both the code and the library remain unchanged. </zen>
Wolf 360 hack (Score:4, Interesting)
The deadline is looming, I can't spend much more time on this. So, I did the unthinkable -- I packed the controller id into the pointer parameter. I marked it as a horrible hack in a 4-line all-caps comment, and checked it in.
Does not sound so horrible, just make sure the 1,2,3,4 pointers never point at anything "free()"able and it'll work fine.
BTW, is that Wolf 360 game out?
Re: (Score:3, Funny)
(oh, and solaris lies about giving you rgba -- it only gives you rgb -- my code would work on one of the uni servers, but not on another)
Wrong question (Score:5, Insightful)
Have you ever needed to insert terrible code to make something work at the last minute?
Wouldn't "have you ever shipped a product without needing to insert terrible code to make something work at the last minute?" be a more sensible question?
Re:Wrong question (Score:5, Funny)
Probably. But reading a stream of "nope", "sorry", "you're kidding", "good one"
... answers leads to a lot of redundant mods but no good entertainment.
Never (Score:4, Funny)
My boss however *only* does coding tricks. And he puts them in one big 1k line function.
And is proud of it.
Sucker punch (Score:4, Funny)
When my deadline comes up and I haven't produced I wait for my boss to ask me for the code then I sucker punch him and run away. The trick is to hold down short term contracts and give false references and hire someone to back them up (another dirty trick). That also makes it easier to dodge the cops when your boss presses charges. It's getting harder though with all this talk of test driven development and short incremental releases. Then the trick becomes to write the most meaningless trivial unimportant tests first - but crucially tests that you can make pass quickly so you don't have to do any real work.
(For anyone insane enough not to realise it, this is a joke. Don't try this at home...or at work).
Game Art (Score:5, Interesting)
Technically not a code fix, but still a valid solution.
seen some bad shit. (Score:5, Interesting)
I once worked at a Fortune 25 company in Chicago. They had this ENORMOUS mainframe program written in COBOL that ran their order inventory system which accounted for 20% of the companies revenue. All the guys who wrote this grunting pig of a system had either retired or had passed away. In the middle of the code was the following;
*
* We don't know what this does.
* Please leave it alone !
*
SET INSIDE-INDEX TO 1.
*
* We don't know what this does.
* Please leave it alone !
*
If this statement was commented out or removed the system stopped working. No one could find the problem. People had spent years looking for it but the code was such a mess and the documentation was so useless that they just left it alone and made a note that when the order inventory was re-done to make sure they left this "feature" out. I have been told that many old system have similar problems.
Even worse stuff! (Score:5, Interesting)
Some of the worst I have seen:
In critical C code:
if (some condition)
i *= 0;
else
i *= 1;
And I was the actual variable name.
Even worse, on a different project, an Easter egg that told the user their hard drive was about to be erased, and another that popped up about 30 dialog boxes full of banter between Spock and Kirk. Worst of all this code written in VB and was licensed for megabux then we got hold of it for orders of magnitude more megabux (Most of the original coders were hired fresh out of highschool). It ended up being rewritten (thankfully NOT by me) but we had to get the source to work out how it worked in the first place.
I wish I was making this up.
Easter egg dependency (Score:5, Interesting)
We had an easter egg in our code that was in a routine scheduled to be executed only at 0-dark-30 when our users were long gone. But someone later called the routine as part of the loading process, and the users ended up seeing it anyway as they signed on at start of day. It made people smile, so we left it in.
A few years later, we were telling a client that we couldn't add their new feature X because we don't have the memory. At that point the director said to get rid of the easter egg and then it'd fit. (A few hundred bytes was not going to make a difference, but our director didn't care, it was a perception thing.) What we got instead was a hundred bug reports that the easter egg wasn't displaying, and that they "needed" to see it so they'd know when start of day was complete.
Train simulation (Score:5, Interesting)
Study Assignment (Score:5, Funny)
This was a pretty important assignment back when I was studying computer science. It added to the final mark mark for that particular class. The task was to write a reasonably complex application in Prolog or some functional programming language, I can't remember which it was. I think the goal was to pair males and females based on their preferences, and find the optimal solution. Of course, I screwed up royally, and nothing worked five minutes before I had to demonstrate my solution.
So in the final five minutes, I changed my code so it would avoid the parts which put it into an infinite loop, and instead simply output a random result. My goal was to tell the prof that it had worked a few minutes earlier, and that I didn't know what had gone wrong, and could I please have another week?
So I demonstrated my app, it gave its random output, and I was about to start with my "damn, it used to work properly" spiel when he said (and this is actually true, even though it sounds unbelievable):
."
And so I did.
Re:Study Assignment (Score:4, Insightful)
...
:-(
Prolog Assignment (Score:5, Interesting)
That's completely understandable in this case of programming in Prolog.
Prolog is a declarative language.
You declare the rules, and the system figures out a result that matches those rules.
The problem is that this basically doesn't work. So a Prolog programmer has to write the "declarative" rules in a procedural order so that the run-time system doesn't have to try every possible combination to find (or fail to find) a matching result.
The proper ordering of declarations can be quite subtle. With a modestly complex program you can make a seemingly unimportant change in the order of the declarations and have the runtime go from a second to a week.
In this case the professor didn't (couldn't) know how long a Prolog program to solve this problem should take. He just assumed that you had found a more efficient ordering for the declarations. He might even have thought it was luck rather than deep insight that your program was faster than his. But you have to a decent understanding of the limits of Prolog to get a complex program to complete in a reasonable time, so you had to be good before you could get that lucky.
If you couldn't already tell, I have a low opinion of Prolog and declarative languages. They are "parlor tricks". Much like computer 'Life' and neural networks, simple programs can produce unexpected seemingly-sophisticated results. But they don't get better from those initial results. To compute the answers or results you want in a reasonable time, you end up with at least the complexity of writing things in the traditional explicitly procedural method.
The promoters of declarative language typically don't mention that you end up writing rules in an explicitly procedural order if you want the program to work. If you press them on the issue, they then say "well, OK, it's not actually any easier to write, but it's easier to verify that you've correctly specified the desired result." But if you have to carefully shuffle declarations around, and even then some results unpredictably take centuries to compute, pretty much no one cares.
Re:Prolog Assignment (Score:4, Informative)
General-purpose declarative languages are bunk, I agree.
However, domain-specific declarative languages often work pretty well. Consider build systems (Make, ant, etc.), or SQL, both of which are declarative.
Re:Study Assignment (Score:4, Interesting)
In Real Life dating agencies, there are often a lack of males. So one person who owned it often dated the women, just to keep them on longer and to get more money from them. They were not in the dating game, they were in the 'get money from desperate souls' game.
The reason (his words) was that women were less afraid to admitting to each other that they were unable to find a partner, where male ego's would never admit such a thing.
Obviously with the anonymity that is The Internet, this difference is gone and any man now gets ripped of as well.
complex finance math (Score:3, Funny)
I worked with some finance guy who was convinced that the square root of a negative number -x was -sqrt(x), and wouldn't hear otherwise. I hacked sqrt(x) to return sgn(x)*sqrt(fabs(x)), but he complained that when he squared the answer, he didn't get back a negative number. Luckily our code was C99 so I changed his dollar type to be "double complex", made him use the complex sqrt, and changed his print function to display creal(x) - cimag(x). The guy said things worked great. I was glad to hear that, but it still feels wrong that part of our finance system is handling complex number of dollars, whatever that means.
Re: (Score:3, Funny)
> I was glad to hear that, but it still feels wrong that part of our finance system is handling complex number of dollars, whatever that means.
What? I'm sure most finance guys are adept enough at counting both real and imaginary dollars, so having complex dollars isn't really that complex...
Re: (Score:3, Insightful)
I learned long ago that regular math and financial math follow very different rules.
Who hasn't? (Score:5, Funny)
After years of programming, I guess everyone had to cut some corners sometimes. It's also not (always) a problem of goofing off, a module you depend on not shipping in time but you being required to keep your deadline can already force you into doing just that: Delivering a hack that 'kinda-sorta' works, or at least the customer won't notice 'til we can ship the patch.
Yes, that happens often. It's dubbed "Bananaware". Delivered green and ripens with the customer.
I knew a guy who pulled a hack like this (Score:3)
it made a total hash out of what I was trying to do. But he lost the source code, so I couldn't prove that he did it. Of course we couldn't fix it either. It was in code that calculated people's paychecks. He got fired. I quit.
Wow am I the only one in here (Score:3, Insightful)
I haven't implemented a fully finished system by the deadline in years simply because I can't squeeze 3 months work into 1 month.
Re: (Score:3, Interesting)
Here is my strategy for dealing with this situation:
1) Tell the salesmen that you have absolutely no problem with them telling the customer whatever they want. Their function is to make sales to customers. Your function is to write software. You won't try to tell them how to do their job, because quite frankly you aren't qualified to know what's best for sales. Of course the implication is that they shouldn't tell you how to write software, but you probably don't have to tell them this explicitly (well,
Customers (Score:3, Insightful)
Yes. But mostly it's not to "make it work"; it's because the customer wants something that is entirely against the original design they asked for.
char Str[255] (Score:3, Informative)
char Str[255];
sprintf(Str, "%s, %s", Lastname, FirstName);
I really wish snprintf was available on my C implementation.
Re:char Str[255] (Score:5, Insightful)
I believe another name for that little snippet is "buffer overflow vulnerability".
Configurable sleep() (Score:3, Interesting)
So we had a race condition on database transactions using two-phase commit, your usual mind-fucking WTF situation, drove us up the walls for days, you all know what I mean. We knew it was a race condition because if we put a sleep() statement at the end of one of the transactions, everything ran fine. sleep(10) was always long enough, and since all of this ran asynchronously in the back end, an end user would never notice the difference.
So we went to the customer. We told them that we could continue to bust our brains trying to find a "real" fix, and didn't know how long that would take, or we could just leave the sleep() in. And we could even make the length of the sleep interval configurable, so they could try to make it shorter than 10 seconds, if they really felt like fiddling around with it.
The customer went for the configurable sleep().
VB6: Lost source code - Ultimate repack (Score:5, Interesting)
. We finished converting a few rogue scripting modules and things like that, which creep in over time. But we COULD NOT find the source code to one of our VB6 DLLs (an old one that had not been changed since it was first compiled in VB6). We searched and searched and eventually the fastest coder(not me) started rewriting it. We were 1 day from delivery date and there was no way he could finish it, so I ran it through a disassembler.
the C++ code we delivered looked like this:
int functionName(int parm) {
_asm {
push esi
mov esi, dword ptr ds:[esp+8]
mov dword ptr ds:[edi], esi
retn
}
It was unreadable, but it compiled and worked and we got our money. I still wonder what they ever did with that... since the software is still in use...
Re:VB6: Lost source code - Ultimate repack (Score:5, Funny)
"Wow, assembler code."
"It must be highly optimized."
"Told you it was a good idea to buy it."
I program small games (Score:4, Funny)
And, I never split my code into multiple files - scroll and Ctrl+F were good enough for my grandfather, and they're good enough for me!
The Fucksort Incident (Score:5, Funny)
Apparently, however, Visual C++ includes a mysort in its standard library. So, with the clock ticking down and the solution's only impediment to our victory being an identifier conflict, I renamed the routine the way that any one of us would have: myfuckingsort. We won the competition.
In this particular competition, the judges were not supposed to read our code - they just run the output of your code on the input and check for correct output - so I felt safe when I typed what I did. However, one of them came up to us afterwards and told us that they do in fact usually read the code of the winning team to see if we did anything unique in our solution. Yep. Sure did. And my classmates and professors never did let me live down what was affectionately nicknamed the fucksort algorithm.
Re:Wow. Talk about old news. (Score:5, Funny)
The editor might have approved this submission just to meet some kind of deadline or a minimum requirement.
Re:Wow. Talk about old news. (Score:5, Insightful)
Re: (Score:3, Interesting)
Quick, find the dupe and copy-paste all the +5 Insightfuls!
Re:Wow. Talk about old news. (Score:5, Funny)
> it's the comments that are worth reading
More specifically the comments in the article. I loved this one:
.""
That's awesome.
Re:Really? Not Slashdot's fault, if so... (Score:5, Funny)
Where'd he get to anyway?
Re:Really? Not Slashdot's fault, if so... (Score:5, Informative)
Re: (Score:3, Funny)
Re: (Score:3, Interesting)
Re:Deadline is not the problem (Score:5, Insightful)
In the real world there are deadlines, and it's entirely the developer's responsibility to be able to meet those deadlines without using such "dirty coding tricks". Good developers should have tested their code so as to not have serious problems to fix at the last minute, and designed it so as to be able to extend it easily.
Yes, because deadlines are always reasonable and never pushed up. And change orders are a myth.
Re:Deadline is not the problem (Score:5, Insightful)
Wait, you were serious? Does your hair come to points on the side of your head, by any chance?
If I could cope with unreasonable deadlines without some sort of nasty compromise, I wouldn't be developing software. I'd be turning water into wine, holding back the tide, etc. "Good software developer" doesn't mean "miracle worker". If the time isn't there before the deadline to solve the problem correctly, either the deadline will be missed or the problem will be unsolved or poorly solved. That's close to a tautology; it's implicit in the term "unreasonable".
Re:Deadline is not the problem (Score:5, Funny)
Re:yuck (Score:5, Insightful)
Basically ALL the software you use works like this.
Welcome to the real world, no need to feel bad.
Re: (Score:3, Insightful)
Re: (Score:3, Interesting)
We do this at my job. We have a decent production database system, but we develop against a K6-2/400 with 256MB of RAM and a couple flaky SCSI disks. If it performs adequately there, it'll perform adequately anywhere. | http://games.slashdot.org/story/09/08/26/021253/Dirty-Coding-Tricks-To-Make-a-Deadline | CC-MAIN-2015-06 | refinedweb | 7,442 | 71.34 |
Writing a Recipe for ASP.NET MVC 4 Developer Preview the process to create mobile versions of desktop views.
Recipes are a great way to show off your lack of UI design skills like me!
In this blog post, I’ll walk through the basic steps to write a recipe. But first, what exactly is a recipe?
Obviously I’m not talking about the steps it takes to make a meatloaf surprise. In the roadmap, I described a recipe as:
An ASP.NET MVC 4 recipe is a dialog box delivered via NuGet with associated user interface (UI) and code used to automate a specific task.
If you’re familiar with NuGet, you know that a NuGet package can add new Powershell commands to the Package Manager Console. You can think of a recipe as a GUI equivalent to the commands that a package can add.
It fits so well with NuGet that we plan to add recipes as a feature of NuGet (probably with a different name if we can think of a better one) so that it’s not limited to ASP.NET MVC. We did the same thing with pre-installed NuGet packages for project templates which started off as a feature of ASP.NET MVC too. This will allow developers to write recipes for other project types such as Web Forms, Windows Phone, and later on, Windows 8 applications.
Getting Started
Recipes are assemblies that are dynamically loaded into Visual Studio by the Managed Extensibility Framework, otherwise known as MEF. MEF provides a plugin model for applications and is one of the primary ways to extend Visual Studio.
The first step is to create a class library project which compiles our recipe assembly. The set of steps we’ll follow to write a recipe are:
- Create a class library
- Reference the assembly that contains the recipe framework types. At this time, the assembly is Microsoft.VisualStudio.Web.Mvc.Extensibility.1.0.dllbut this may change in the future.
- Write a class that implements the
IRecipeinterface or one of the interfaces that derive from
IRecipesuch as
IFolderRecipeor
IFileRecipe. These interfaces are in the
Microsoft.VisualStudio.Web.Mvc.Extensibility.Recipesnamespace. The Developer Preview only supports the
IFolderRecipeinterface today. These are recipes that are launched from the context of a folder. In a later preview, we’ll implement
IFileRecipewhich can be launched in the context of a file.
- Implement the logic to show your recipe’s dialog. This could be a Windows Forms dialog or a Windows Presentation Foundation (WPF) dialog.
- Add the MEF
ExportAttributeto the class to export the
IRecipeinterface.
- Package up the whole thing in a NuGet package and make sure the assembly ends up in the recipes folder of the package, rather than the usual lib folder.
The preceding list of steps itself looks a lot like a recipe, doesn’t it? It might be natural to expect that I wrote a recipe to automate those steps. Sorry, no. But what I did do to make it easier to build a recipe was write a NuGet package.
Why didn’t I write a recipe to write a recipe (inception!)? Recipes add a command intended to be run more than once during the life of a project. But that’s not the case here as setting up the project as a recipe is a one-time operation. In this particular case, a NuGet package is sufficient because it doesn’t make sense to convert a class library project into a recipe over and over gain.
That’s the logic I use to determine whether I should write a recipe as opposed to a regular NuGet package. If it’s something you’ll do multiple times in a project, it may be a candidate for a recipe.
A package to create a recipe
To help folks get started building recipes, I wrote a NuGet package, AspNetMvc4.RecipeSdk. And as I did in my //BUILD session, I’m publishing this live right now! Install this into an empty Class Library project to set up everything you need to write your first recipe.
The following screenshot shows an example of a class library project after installing the recipe SDK package.
Notice that it adds a reference to the Microsoft.VisualStudio.Web.Mvc.Extensibility.1.0.dll assembly and adds a MyRecipe.cs file and a MyRecipe.nuspec file. It also added a reference to System.Windows.Forms.
Feel free to rename the files it added appropriately. Be sure to edit the MyRecipe.nuspec file with metadata appropriate to your project.
The interesting stuff happens within MyRecipe.cs. The following shows the default implementation added by the package.
using System; using System.ComponentModel.Composition; using System.Drawing; using Microsoft.VisualStudio.Web.Mvc.Extensibility; using Microsoft.VisualStudio.Web.Mvc.Extensibility.Recipes; namespace CoolRecipe { [Export(typeof(IRecipe))] public class MyRecipe : IFolderRecipe { public bool Execute(ProjectFolder folder) { throw new System.NotImplementedException(); } public bool IsValidTarget(ProjectFolder folder) { throw new System.NotImplementedException(); } public string Description { get { throw new NotImplementedException(); } } public Icon Icon { get { throw new NotImplementedException(); } } public string Name { get { throw new NotImplementedException(); } } } }
Most of these properties are self explanatory. They provide metadata for a recipe that shows up when a user launches the Add recipe dialog.
The two most interesting methods are
IsValidTarget and
Execute. The
first method determines whether the folder that the recipe is launched
from is valid for that recipe. This allows you to filter recipes. For
example, suppose your recipe only makes sense when launched from a view
folder. You can implement that method like so:
public bool IsValidTarget(ProjectFolder folder) { return folder.IsMvcViewsFolderOrDescendent(); }
The
IsMvcViewsFolderOrDescendant is an extension method on the
ProjectFolder type in the
Microsoft.VisualStudio.Web.Mvc.Extensibility namespace.
The general approach we took was to keep the
ProjectFolder interface
generic and then add extension methods to layer on behavior specific to
ASP.NET MVC. This provides a nice simple façade to the Visual Studio
Design Time Environment (or DTE). If you’ve ever tried to write code
against the DTE, you’ll appreciate this.
In this particular case, I recommend that you make the method always
return
true for now so your recipe shows up for any folder.
The other important method to implement is
Execute. This is where the
meat of your recipe lives. The basic pattern here is to create a Windows
Form (or WPF Form) to display to the user. That form might contain all
the interactions that a user needs, or it might gather data from the
user and then perform an action. Here’s the code I used in my MVC 4
Mobilizer recipe.
public bool Execute(ProjectFolder folder) { var model = new ViewMobilizerModel(folder); var form = new ViewMobilizerForm(model); var result = form.ShowDialog(); if (result == DialogResult.OK) { // DO STUFF with info gathered from the form } return true; }
I create a form, show it as a dialog, and when it returns, I do stuff with the information gathered from the form. It’s a pretty simple pattern.
Packaging it up
Packaging this up as a NuGet package is very simple. I used NuGet.exe to run the following command:
nuget pack MyRecipe.nuspec
If it were any easier, it’d be illegal! I can now run the
nuget push
command to upload the recipe package to
NuGet.org and make it
available to the world. In fact, I did just that live during my
presentation at BUILD.
Using a recipe
To install the recipe, right click on the solution node in Solution Explorer and select Manage NuGet Packages.
Find the package and click the Install button. This installs the NuGet package with the recipe into the solution.
To run the recipe, right click on a folder and select Add > Run
Recipe.
Right now you’re probably thinking that’s an odd menu option to launch a recipe. And now you’re thinking, wow, did I just read your mind? Yes, we agree that this is an odd menu option. Did I mention this was a Developer Preview? We plan to change how recipes are launched. In fact, we plan to change a lot between now and the next preview. At the moment, we think moving recipes to a top level menu makes more sense.
The Run Recipe menu option displays the recipe dialog with a list of installed recipes that are applicable in the current context.
As you can see, I only have one recipe in my solution. Note that a recipe can control its own icon.
Select the recipe and click the OK button to launch it. This then calls
the recipe’s
Execute method which displays the UI you implemented.
Get the source!
Oh, and before I forget, the source code for the Mobilizer recipe is available on Github as part of my Code Haacks project!
18 responses | https://haacked.com/archive/2011/09/22/writing-a-recipe-for-asp-net-mvc-4-developer-preview.aspx/ | CC-MAIN-2020-29 | refinedweb | 1,467 | 66.33 |
Feature flags in Swift
When developing new features for an app, it can be really useful to have some form of mechanism to gradually roll out new implementations & functionality, instead of having to launch to every single user at once. Not only can this help "de-risk" the launch of a big change (if something breaks, we can always roll back), it can also help us gather feedback on a partially finished feature, or perform experiments using techniques like A/B testing.
Feature flags can act as such a mechanism. They essentially allow us to gate certain parts of our code base off under certain conditions, either at compile time or at runtime. This week, let's take a look at a few different ways that feature flags can be used.
Conditional compilation
When working on a code base there are multiple strategies we can use when it comes to dealing with features that are a work in progress. We can - for example - use something like feature branches, and use version control to keep a feature that's under development completely separated from our main
master branch. Once the feature is ready to be released, we simply merge it in and ship it.
However, there are some big advantages to instead continuously integrate new implementations and features into our main branch. It lets us detect bugs and problems earlier, it saves us the pain of having to solve a massive number of merge conflicts if the two branches have diverged a lot, and it can let us ship a pre-release version of a new feature internally or to beta testers.
But we still need some way to remove code that shouldn't be shipped live to the App Store. One way of doing so is to use compiler flags, which lets us mark a code block so that it only gets compiled in if the flag has been set. Let's say our app is currently using Core Data, and we want to keep it that way in production (for now), while still being able to try out a new solution - like Realm. To do that, we can use a
DATABASE_REALM compiler flag, that we only add for builds that we want to use Realm in (for example for beta builds). We can then tell the compiler to check for that flag when building our app, like this:
class DataBaseFactory { func makeDatabase() -> Database { #if DATABASE_REALM return RealmDatabase() #else return CoreDataDatabase() #endif } }
To toggle the above flag on or off, we can simply open up our target's build settings in Xcode and add or remove
DATABASE_REALM under Swift Compiler - Custom Flags > Active Compilation Conditions. This is especially useful for features that are still under active development, which lets the developers working on such a feature easily turn it on locally without affecting production builds.
Static flags
Conditional compilation is super useful when you want to completely remove the code for a new implementation from an app. But sometimes that's either not needed or not practical, and in those cases defining feature flags in code instead can be a much better option.
One really simple way to do so is to use static properties. We could, for example, create a
FeatureFlags struct that contains all of our flags, like this:
struct FeatureFlags { static let searchEnabled = false static let maximumNumberOfFavorites = 10 static let allowLandscapeMode = true }
As you can see above, flags can also be super useful in order to tweak an existing feature, not only to roll out brand new ones. Using the above
maximumNumberOfFavorites property we can easily experiment with how many favorites a user can have, to find a value that we think will strike the right balance.
With the above
FeatureFlags type in place, we can now place checks in code paths where we'd activate a given feature. Here's an example method that conditionally activates the search feature, which gets called from the
viewDidLoad() method of a
ListViewController:
extension ListViewController { func addSearchIfNeeded() { // If the search feature shouldn't be enabled, we simply return guard FeatureFlags.searchEnabled else { return } let resultsVC = SearchResultsViewController() let searchVC = UISearchController( searchResultsController: resultsVC ) searchVC.searchResultsUpdater = resultsVC navigationItem.searchController = searchVC } }
The benefit of static flags is that they, just like compiler flags, are quite easy to setup and integrate. However, they don't let us modify the value of our flag after our app has been compiled. To be able to do that, we need to start using runtime flags.
Runtime flags
Adding the option to configure our app's feature flags at runtime can be a bit of a "double edged sword". On one hand, it can enable us to perform A/B testing by changing the value of a given flag for a certain percentage of our user base, and on the other hand it can make our app more difficult to maintain & debug - since the code paths it'll end up using are not fully determined at compile time.
Runtime flags are often loaded from some form of backend system, and could potentially (depending on the app's architecture) even be included in the response the app receives as part of logging a user in (otherwise it's common to have a
/feature_flags endpoint or similar that the app queries at launch). Optionally, we could also enable flags to be tweaked in the app itself using some form of debug UI.
Regardless of how we load the values for our feature flags, we'll want to update our
FeatureFlags type to use instance properties instead of static ones. That way we can load the values for our flags and then transform them into a
FeatureFlags instance, which we'll then inject whenever needed. Our flags type now looks like this:
struct FeatureFlags { let searchEnabled: Bool let maximumNumberOfFavorites: Int let allowLandscapeMode: Bool }
To be able to transform an instance from a serialized format, we'll also add an initializer that takes a dictionary. That way we can either create our feature flags from a JSON backend response, or from values stored locally in the app (for example from a cache):
extension FeatureFlags { init(dictionary: [String : Any]) { searchEnabled = dictionary.value(for: "search", default: false) maximumNumberOfFavorites = dictionary.value(for: "favorites", default: 10) allowLandscapeMode = dictionary.value(for: "landscape", default: true) } } private extension Dictionary where Key == String { func value<V>(for key: Key, default defaultExpression: @autoclosure () -> V) -> V { return (self[key] as? V) ?? defaultExpression() } }
The reason we're not using
Codable above is that we want to use default values (in case our backend hasn't been updated with a given flag), which is much easier done with a simple
Dictionary extension. For more information about
@autoclosure, which is used above, check out "Using @autoclosure when designing Swift APIs".
We can now load our feature flags whenever our app launches or a user logs in (depending on if we want our flags to be user-specific), and inject them whenever needed, like this:
class FavoritesManager { private let featureFlags: FeatureFlags init(featureFlags: FeatureFlags) { self.featureFlags = featureFlags } func canUserAddMoreFavorites(_ user: User) -> Bool { let maxCount = featureFlags.maximumNumberOfFavorites return user.favorites.count < maxCount } }
We now have a lot more freedom when it comes to toggling certain features on and off, or tweaking values that determine part of our app's logic. We could also enable our flags to be mutated while our app is running (and add some form of observation API to react to changes), but personally I rarely think adding that much complexity is worth it. Just loading the values once and setting up the app after that helps keep things simple and avoids introducing tricky corner feature flags can be key when it comes to being able to quickly iterate on an app, especially as its team grows and the code base changes with a much higher velocity. By being able to conditionally enable certain features or tweak their behavior, we can usually integrate our code quicker into our main branch and still keep shipping our app.
Feature flags can also add a bit of complication to our setup, especially when runtime flags are used. It can become harder to reproduce bugs that only occur when a certain combination of flags are on, and testing all of our app's potential code paths can quickly become much more complicated and time consuming.
If you haven't used feature flags before, I suggest to start simple (perhaps with compiler flags or static ones), and work your way from there. Like with most tools, they might require you to adopt your workflow a bit, especially if the project doesn't currently use much automated testing (which makes using feature flags much less risky).
What do you think? Have you used feature flags before, or is it something you'll try out? Let me know, along with any questions, comments or feedback that you might have - on Twitter @johnsundell.
Thanks for reading! 🚀 | https://swiftbysundell.com/articles/feature-flags-in-swift/ | CC-MAIN-2021-43 | refinedweb | 1,484 | 53.95 |
Which
i am Getting Some errors in Struts - Struts
i am Getting Some errors in Struts I am Learning Struts Basics,I am Trying examples do in this Site Examples.i am getting lot of errors.Please Help me
Hibernate Getting Started
with the fast track Hibernate Getting Started tutorial.
What is required?
I am... is ready.
Create database
I am assuming that MySQL is installed on the local...
Hibernate Getting Started
What you Really Need to know about Fashion
talk about fashion.
In recent years fashion, in general, has really started...What you Really Need to know about Fashion
You might think... know about fashion, even if you are not really
interested in following
VoIP Getting Started
VoIP Getting Started
VoIP
Getting started with SIP
Voice-over-IP (VoIP....
VoIP-
Getting Started
To get started you need VoIP output displays 4 rows and 2 columns. How can I calculate the total
Good tutorials for beginners in Java
Good tutorials for beginners in Java Hi, I am beginners in Java, can someone help me in knowing if there any tutorials which can provide me in details about good tutorials for beginners in Java with example?
Thanks.
JSP Getting Started, Getting Started With JSP
every thing is ready to get started with JSP programming. Now you can
write...Getting Started with JSP
This page is all about getting started with JSP... CGI and Perl
All the advance frameworks such as Struts, JSF, Spring MVC
Not sure what I am missing ? Any ideas?
Not sure what I am missing ? Any ideas? import java.util.*;
public...)
{
if(str.length()==0)
return false;
for(int i=0;i<str.length();i++)
if (c==str.charAt(i));
return true
struts
struts Hi,
i am writing a struts application
first of all i am takeing one registration form enter the data into fileld that
will be saved perfectly.
but now i can apply some validations to that entry details
but with
Hi ..I am Sakthi.. - Java Beginners
Hi ..I am Sakthi.. can u tell me Some of the packages n Sub Directories starts with...
import javax.swing.*;
import javax._________;
... JSP Struts2.0 HTML ");
tabbedPane.addTab("Four", icon, panel4, "Now Articles
the lines of comparing Struts to JSF. I thought it would be a good idea to compare... previous Struts experience. I notice in many cases that some sort of ?paradigm mismatch? exists between Struts and JSF. I call this the ?problem of the locomotive Books
started really quickly? Get Jakarta Struts Live for free, written by Rick Hightower... components
How to get started with Struts and build your own...
Request Dispatcher. In fact, some Struts aficionados feel that - Jboss - I-Report - Struts
Struts - Jboss - I-Report Hi i am a beginner in Java programming and in my application i wanted to generate a report (based on database) using Struts, Jboss , I Report
struts <html:select> - Struts
struts i am new to struts.when i execute the following code i am... DealerForm[30];
int i=0;
while(rs.next())
{
DealerForm dform=new... :
1. Remove name attribute altogether and specify only an action attribute
Print Only Forms Contents - Java Beginners
Print Only Forms Contents Hello Sir I Have Created Simple Registration Form with Database Connectivity,
Now I Want To Print Registration form Contents ,How I can Do that,
plz Help Me Hi Friend,
Please go through
servlet not working properly ...pls help me out....its really urgent
servlet not working properly ...pls help me out....its really urgent ...;/body> </html>
</form> </body> </html>
Now... (Exception e)
{
}
} }
Now
Struts Tutorials
and on top of Struts, is now an integral component of any professional Struts... v5.0.2.2.
Adding Spice to Struts - Part 2
This time, we started looking at how... application development using Struts. I will address issues with designing Action
Just Got The New iPad? Getting Started?
Just Got The New iPad? – Getting Started
Since its release in early... should know to help get you started.
The basics
As with any device you... inches
Weight (Wi-Fi only): 1.5 pound
Weight (Wi-Fi
PHP Getting Started With PHP Tutorial
starts with <?php and ends with ?>
If you want to print "I am...; print("I
am learning PHP");
?>
Example 2:
<?php
echo("I
am learning PHP");
?>
Output:
Above written codes will display
:( I am not getting Problem (RMI)
I am not getting Problem (RMI) When i am excuting RMI EXAMPLE 3,2
I am getting error daying nested exception and Connect Exception
struts- login problem - Struts
struts- login problem Hi all, I am a java developer, I am facing problems with the login application. The application's login page contains fields like username, password and a login button. With this functionality Application dispatch action - Struts
Struts dispatch action i am using dispatch action. i send....
but now my problem is i want to send another value as querystring for example
now it showing error
javax.servlet.ServletException: Request[/View/user] does
technologies like servlets, jsp,and struts.
i am doing one struts application where i...struts hi
Before asking question, i would like to thank you... into the database could you please give me one example on this where i i have
Struts Book - Popular Struts Books
books out there where they give top-soil kind of overviews of the technology. I am... very well. This is the first Struts book ever published and the one I bought when I first learned Struts. For exmaple, the MVC design pattern was explained well
Struts - Struts
Struts for dummies pdf download I am looking for a PDF for struts beginners.Thanks
Struts small complite project - Struts
Struts small complite project I am a beginner in struts I want to do... that I can by taking the reference of that I can write good and effective...,
i am sending link,
Perl Programming Books
This book is a work in progress. I have some ideas about what will go into the next few chapters, but I am open to suggestions. I am looking for interesting... efficiently.
Like any good marriage, the partners of Extreme Perl support each
Struts file uploading - Struts
Struts file uploading Hi all,
My application I am uploading... = newDocumentForm.getMyDocument();
byte[] fileData = file.getFileData();
I am... I upload the large size file like 10 mb.
Now my requirement is below
Struts 2 issue
Struts 2 issue hi,
I have one jsp page and having one hidden field methodName and when we submit request we get value in action class and again i... in hidden field is show and in action we get show and on 2nd submit in action i am
display:table export only data
display:table export only data I am using display:table tag with attribute export="true". Using that I can export table data in excel. Here one of the column is in hyper link. But i need to export only data not html tag . Can
HOW TO BECOME A GOOD PROGRAMMER
HOW TO BECOME A GOOD PROGRAMMER I want to know how to become good programmer
Hi Friend,
Please go through the following link:
CoreJava Tutorials
Here you will get lot of examples with illustration where you can
Struts first example - Struts
!
I am using struts 2 for work.
Thanks. Hi friend,
Please visit...Struts first example Hi!
I have field price.
I want to check... friend!
thanks you so much for your supports,
I want to check not only type
struts - Struts
Struts ui tags example What is UI Tags in Strus? I am looking for a struts ui tags example. Thanks
help i want it now the answer pleas...
help i want it now the answer pleas... write a program that will display the exactly output as below:
Hints: declare and initialize value of array in double type.Read and write all elements of array.perform the multiply
Java - Struts
Java hello friends,
i am using struts, in that i am using tiles framework. here i wrote the following code in tiles-def.xml
in struts-config file i wrote the following action tag Validator Framework - lab oriented lesson
' JSF
last year (2004), Struts is still holding its ground and only recently...
already been built using Struts, it may be that only a combination of Struts...
of the preceding technologies, a good knowledge of Struts is equivalent to
competence
i am unable to identify the error in my code
i am unable to identify the error in my code class Program
{
public static void main(String[] args)
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter
Deploying Struts and testing struts 2 hello world application
Deploying Struts and testing struts 2 hello world application
I am assuming that you have already installed ant...\struts2\struts2helloworld\WEB-INF\src>
Testing Struts 2 Hello..please provide me a good Hibernate in Spring example
as I am new to Hibernate.
Thanks in advance..
Dear Friend,
If you are new to Hibernate and are also looking for Hibernate in Spring examples, I...Please..please provide me a good Hibernate in Spring example Hi - Struts
Struts Is Action class is thread safe in struts? if yes, how it is thread safe? if no, how to make it thread safe? Please give me with good... safe. You can make it thread safe by using only local variables, not instance
HTTP Status 404 - /web/login/showLogin.action Error in Struts 2 - Struts
Everyone
I am using the following version for my project:
Tomcat 6.0.16
Eclipse 3.4
Struts 2
Now my question is I am trying to implement the login... and Now when I am trying to right click on the index.jsp and give it the command run
Struts - Struts
Struts
You have been working with this current firm for a long time. Don?t you think it would be difficult now to switch over t
quality.
E.g. “Well I can’t really call it worry, but I am very... an impressive record with this company and I am sure you will find the information... you think it would be difficult now to switch over to a new company
java - Struts
java I have changed the things still now i am getting same problem friend.
what can i do.
In Action Mapping
In login jsp
... :
In Action Mapping
In login jsp
For read more information on struts
struts
struts <p>hi here is my code can you please help me to solve...
{
public ActionForward execute(ActionMapping am,ActionForm af...(ActionMapping am,HttpServletRequest req)
{
ActionErrors ae=new ActionErrors
Hi - Struts
Hi Hi friends,
must for struts in mysql or not necessary please tell me its very urgent....I have a only oracle10g database please let me... very urgent....
Hi friend,
I am sending you a link
struts
struts <p>hi here is my code in struts i want to validate my form fields but it couldn't work can you fix what mistakes i have done</p>... ActionForward execute(ActionMapping am,ActionForm af,HttpServletRequest req
Struts - Struts
Struts How to display single validation error message, in stude of ? Hi friend,
I am sending you a link. This link will help you. Please visit for more information.
struts am retrieving data from the mysql database so the form bean will be null for that action.... if i give it in struts config it is asking me to have a form bean.... how to solve this problem
regarding connectivity program only - JDBC
,
i am sending simple code of connectivity
import java.sql.*;
public... .. that i had created student data base with his name and subject marks resp ... i...---- sub2--------- sub3--------
3.total ........i want to calculate
in the back
struts - Struts
struts Hi,
I am new to struts.Please send the sample code for login....shtml
Hope that the above links... handset[]=new int [handset1.length];
for(int i=0;i<handset1.length;i++)
{
handset[i]=Integer.parseInt(handset1
Aggregating Actions In Struts Revisited
Aggregating Actions in Struts , I have given a brief idea of how to create action...;
System.out.println("I am in CRUDDispatchAction - create"); ... Employee follows
System.out.println("I am
Why the Google Penguin update is good for SEO
update is good for SEO, well specially for white-hat SEO and not black-hat... for it, now have to stop it with immediate affect as it looks that the new update....
The recent update is a good sign for White Hat SEO who has been working
Struts - Struts
Struts Hello
I have 2 java pages and 2 jsp pages in struts... for getting registration successfully
Now I want that Success.jsp should display... with source code to solve the problem.
For read more information on Struts visit
i have split a string by space ,done some operation and now how to properly order them for sending a mail in java or jsp - JSP-Servlet
i have split a string by space ,done some operation and now how to properly order them for sending a mail in java or jsp Dear sir,
I have... the matter while sending it and also i am getting a small font size ,i want medium | http://www.roseindia.net/tutorialhelp/comment/3928 | CC-MAIN-2014-49 | refinedweb | 2,191 | 66.03 |
Cleanup unmanaged objects
In This article i will give you a short idea to handle unmanaged objects and free them from memory after work has done. However memory is a large task to do but here we cover a basic of it using Dispose and Destructor.
Cleanup unmanaged objects
Introduction
Object is backbone of object oriented languages. All codes and programs under this structure will follow object lifecycle. Object creation and destruction is very basic idea behind this concept.
MSDN defines object in a simple way "object is an entity, any live or non living thing is object"
but in our practically it's a instance of class.
basically a thing which represent a class, called object.
.Net framework and Object creation
The .NET Framework provides garbage collector which takes care of memory managment tasks like memory allocation and deallocation. When we create NEWobject,
the CLR will search space in managed heap to allocate memory for newly created, The memory allocation continue till space is available in the managed heap,
when memory get's full, garbage collector perform a collection operation to free some memory. it checks for those objects who are no longer used by application, GC will collect those object and
freed up memory for upcoming objects.
Managed and Unmanaged objects
Roughly we can divide objects in to two parts a managed and unmanaged objects
Managed objects
Managed objects are those for which GC having all knowledge. mainly all system defined and inbuilt classes, structures, namespaces are under managed objects
UnManaged objects
GC completely unaware about these objects and unable to freed up memory allocated by these objects
such as Memory stream, COM Objects, automation objects like word, excel
The GC does not know about unmanaged resources, if you do not clean them up explicitly in your code then you will end up with memory leaks and locked resources.
Disposing unmanaged objects
Let's overcome this issue.
We can use Idisposable interface to dispose all managed and unmanaged resources to freed up memory for other resources
The idea behind the IDisposable interface is to clean up resources in a Highly skilled fashion and clean up unmanaged resources. Even if you do not have unmanaged resources in your code,
but you used heavy managed objects which consumes large memory like images, network connections, fleshy loops etc. if you no longer need these objects then flush them from memory
This code is placed inside the Dispose functions. we can also use IDisposable interface. you should call the Dispose() method when you are finished with the object.
Once you called Dispose() you can stop the GC from calling the dispose function in the finalizer because this is unnecessary overhead on system. we can tell GC not call dispose method
by calling GC.SupressFinalize(this) method.Which make sure that the object will not put in GC's dispose Queue.
If you use unmanaged objects like Image or IOStreams then it has already Dispose function and a Finalizer methods implemented inside, just do not forget to call them
Implementing a way to Dispose Objects
When you create any class, you can use two methods to dispose objects means to freeing memory used by unmanaged resources.
The way are:
1. Use of finalizer (also called Destructor) as a member of your class
2. Implementing the System.IDisposable interface
Let's discuss them in Detail
Implementing Finalizer
Constructors usually in action when an instance of a class is created. Conversely, finalizer is called before an object is destroyed by the garbage collector.
However a Finalizer seem to be a great place to free unmanaged resources and perform a general cleanup.
Here is example to implement Finalize
But there is problem with C# finalizer, finalizer may delays the final removal of an object from memory. Objects that do not under finalizer are removed from memory in single GC Cycle,
but objects that are under finalizer need to call two GC cycle, The first pass calls the finalizer without removing the object, and the second cycle actually deletes the object.
that may be impact on performance.
Implementing IDisposable
The recommended alternative to finalizer is using System.IDisposable interface.
The IDisposable is basically a interface that ensures a deterministic level for freeing memory from unmanaged resources and avoids the garbage collector–related problems occurs in
case of finalizer.
The IDisposable interface declares a single method named Dispose(), which is without parameters and returns void.
Consider following example in which IDisposable is implemented
Here object directly call Dispose() method and should explicitly free all unmanaged resources. In this way, the Dispose() method provides precise control over when unmanaged resources are
freed.
Suppose that you have call Dispose method using class instance like following
Unfortunately, above code fails to free the resources if an exception occurs during processing. so you should write the code as follows using a try...catch...finally block
see the following code
in above code ,
The finally get's executed always regardless of exception occured or not. So here Dispose will call and any resources consumed by Unmanaged class are always freed,
mamory management is big ocean
so this is about short article on Cleanup unmanaged objects, How ever mamory management is big ocean, we can not cover it in single article,This article gives you short idea of it.
we will go in depth step by step in upcoming articles.
Suggestion and Queries always welcome
Thanks
Koolprasad2003
Hi Koolprasad2003,
Thanks to giving valuable information for disposing unmanaged code in c#.
i have created my application in wpf here am found Ram memory increasing problem is load xaml file because using few staticresource and load some style in xaml file.
i want make sure how xaml staticresource and style resource dispose.
Thanks and regards,
Selva | https://www.dotnetspider.com/resources/43616-Cleanup-unmanaged-objects.aspx | CC-MAIN-2021-43 | refinedweb | 960 | 50.67 |
Please please help]
Below is a link to the instructable with the code I used to make a playback device (uses GPIO pins) ... pberry-Pi/
Code: Select all
import RPi.GPIO as GPIO import time import os #variables: butPressed = [True, True, True, True, True, True, True]#if button i is pressed, then butPressed[i] is False pin = [26, 19, 13, 6, 5, 21, 20]#GPIO pins of each button recordBool = False#True if a record is in progress GPIO.setmode(GPIO.BCM) for i in range(0, 7): GPIO.setup(pin[i], GPIO.IN, pull_up_down=GPIO.PUD_UP)#sets Pi's internal resistors to pull-up while True: for i in range(0, 7): butPressed[i] = GPIO.input(pin[i])#checks if a button is pressed if butPressed[i] == False:#if a button is pressed previousTime = time.time() while butPressed[i] == False and recordBool == False: butPressed[i] = GPIO.input(pin[i]) if time.time() - previousTime > 1.0:#if the button is pressed for more than a second, then recordBool is True recordBool = True if recordBool == True:#if recordBool is True, it plays a beep sound and then records os.system("aplay -D plughw:CARD=Device_1,DEV=0 beep.wav") os.system("arecord %d.wav -D sysdefault:CARD=1 -f cd -d 20 &" %i)#records for maximum 20 seconds in file i.wav, with cd quality while butPressed[i] == False: butPressed[i] = GPIO.input(pin[i]) os.system("pkill -9 arecord")#the record is stopped when the button is let go, or after 20 seconds recordBool = False else:#if recordBool is False, it plays sound i.wav os.system("aplay -D plughw:CARD=Device_1,DEV=0 %d.wav" %i) time.sleep(0.1) | https://lb.raspberrypi.org/forums/viewtopic.php?f=102&t=225035 | CC-MAIN-2019-04 | refinedweb | 281 | 66.64 |
Details
- Type:
Bug
- Status: Closed
- Priority:
Major
- Resolution: Won't Fix
- Affects Version/s: 1.6.4
- Fix Version/s: None
- Component/s: None
- Labels:None
Description
The following:
foo = 5 foo()
results in:
Caught: groovy.lang.MissingMethodException: No signature of method: java.lang.Integer.call() is applicable for argument types: () values: [] at MyScript.run(MyScript.groovy:2)
This is bad for at least two reasons:
- The error message is hard to understand (should be: No signature of method: MyScript.foo() is applicable for argument types: () values: [])
- invokeMethod and methodMissing don't get a chance to intercept the method call
Likely solution: Change line 1093 of MetaClassImpl.java to: if(bindingVar instanceof Closure) {
Issue Links
- relates to
GROOVY-2503 MOP 2.0 design inflluencing issues
- Open
Activity
I am not sure about the binding variable logic in Script.invokeMethod but the change to MetaClassImpl was done by me as part of
GROOVY-3284, where it was mentioned that "for sure I can say, that call() is to be made even if x is no Closure".
Reproduce here some portion of the comments from
GROOVY-3284
- A call like Foo.A() is not supposed to work because Foo.A is of type Foo and not Closure.
- you can't say it like that.... x() is supposed to resolve to x.call(), but this is a undocumented feature as we are not entirely sure if we really want to support this.
- x() is supposed to resolve to x.call() even if x is not of type Closure? Irrespective of type of x?
- kind of... as I said, it is not really specified. for sure I can say, that call() is to be made even if x is no Closure. I suspect in the MetaClass code where we test the field we test only for closures. A change here needs some experiments, because it may influence other parts.
let us change the example....
def foo = 5 foo()
do you still expect the methodmissingexception here? What if foo is a field? What if foo has no int, but a closure? What if a call() method has been added to int?
What I expect above all is consistent behavior. Therefore the duplication in MetaClassImpl and Script is dubious. When a call goes through MetaClassImpl, you get one behavior, and when it doesn't (e.g. because it goes through ClosureMetaClass), then you get another one. IMHO this needs to be fixed.
That sounds reasonable but the first thing is to decide which of the two behaviors is correct.
Unless the undocumented "resolve to x.call()" feature is made official, it seems logical to only invoke call() for closures. But I think we need Jochen's input here.
the logic for f() is:
(1) if there is a local varibale f, do f.call().
(2) if there is a method f(), invoke it
(3) if there is a property f, invoke f.call()
is this not consistent or is that problematic?
The inconsistency is the following: If the call goes through MetaClassImpl, the binding variable wins over Script.invokeMethod(). If it doesn't (e.g. because it goes through ClosureMetaClass), then it's the other way around.
so it is not about an existing method or variable, but for the case it does not exist... ok...
(1) if there is a local varibale f, do f.call().
(2) if there is a method f(), invoke it
(3) if there is a property f, invoke f.call()
(4) call invokeMethod()/methodMissing
Accroding to this scheme it is ok for the script variable to win over invokeMethod.
>so it is not about an existing method or variable, but for the case it does not exist... ok...
It's about the race between an existing script variable and Script.invokeMethod().
>Accroding to this scheme it is ok for the script variable to win over invokeMethod.
I don't see script variables mentioned in your logic, and intuitively I'd put them after invokeMethod(), just like the author of Script.invokeMethod(). Anyway, if a script variable should win over invokeMethod(), then the implementation of Script.invokeMethod() must change. Because right now, Script.invokeMethod() wins over a script variable as soon as the call occurs from within a closure (and for all other calls that don't go through MetaClassImpl).
Script variables are properties, so this goes in (3).
OK, then let's change Script.invokeMethod().
After rereading the issue I think we are in the state that we can close the issue already. If
(1) if there is a local varibale f, do f.call().
(2) if there is a method f(), invoke it
(3) if there is a property f, invoke f.call()
(4) call invokeMethod()/methodMissing
is acceptable, then the important point here is that f is found in step (3) in the binding. Script's invokeMethod is not asked, because that would have happened in (4), but because a property was found we do the call for it which fails, because Integer does not provide a call() method in this example. What if it would provide one? Wouldn't it be expected to be called? The only way to fix it in the way that you may think is right is to react to the missing method there.
If the method call is in a Closure, then yes, it behaves different. And that is the reason I don't close this issue. But this is because of the way the MOP is designed. So this will become a target for 2.0 instead
I just noticed that the logic to call a closure in the binding is duplicated (MetaClassImpl and Script.invokeMethod). Can one of the two occurrences be removed? | https://issues.apache.org/jira/browse/GROOVY-3675?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel | CC-MAIN-2015-40 | refinedweb | 953 | 75.5 |
Magics classes
So far in this series, we have covered three different decorators:
@register_line_magic (in part1),
@register_cell_magic and
@register_line_cell_magic (in part2). Which is enough to create any type of magic function in IPython. But, IPython offers another way of creating them - by making a Magics class and defining magic functions within it.
Magics classes are more powerful than functions, in the same way that a class is more powerful than a function. They can hold state between function calls, encapsulate functions, or offer you inheritance. To create a Magics class, you need three things:
- Your class needs to inherit from
Magics
- Your class needs to be decorated with
@magics_class
- You need to register your magic class using the
ipython.register_magics(MyMagicClass)function
In your magic class, you can decorate functions that you want to convert to magic functions with
@line_magic,
@cell_magic and
@line_cell_magic,
Writing a magics class
To show how the magics class works, we will create another version of
mypy helper. This time, it will allow us to run type checks on the previous cells. This is how we expect it to work:
In [1]: def greet(name: str) -> str: ...: return f"hello {name}" In [2]: greet('tom') Out[2]: 'hello tom' In [3]: greet(1) Out[3]: 'hello 1' In [4]: %mypy 1-2 Out[4]: # Everything should be fine In [4]: %mypy 1-3 Out[4]: # It should report a problem on cell 3
Here are a few assumptions about the
%mypy function:
- It should accept all the parameters that the
mypycommand accepts
- It should accept the same range parameters that
%historycommand accepts, but only from the current session. I usually don’t reference history from the previous sessions anyway and it will make parsing arguments slightly easier. So
1,
1-5, and
1 2 4-5are all valid arguments, while
243/1-5or
~8/1-~6/5are not.
- The order of arguments doesn’t matter (and you can even mix ranges with
mypyarguments), so we can call our function in the following ways:
%mypy --ignore-imports 1 2 5-7
%mypy 1-3
%mypy 2 4 5-9 --ignore-imports
%mypy 2 4 --ignore-imports 5-9
With that in mind, let’s write the code. The main class looks like this:
from IPython.core.magic import Magics, magics_class, line_magic import re # The class MUST call this class decorator at creation time @magics_class class MypyMagics(Magics): @line_magic def mypy(self, line): try: from mypy.api import run except ImportError: return "'mypy' not installed. Did you run 'pip install mypy'?" if not line: return "You need to specify cell range, e.g. '1', '1 2' or '1-5'." args = line.split() # Parse parameters and separate mypy arguments from cell numbers/ranges mypy_arguments = [] cell_numbers = [] for arg in args: if re.fullmatch(r"\d+(-\d*)?", arg): # We matched either "1" or "1-2", so it's a cell number cell_numbers.append(arg) else: mypy_arguments.append(arg) # Get commands from a given range of history range_string = " ".join(cell_numbers) commands = _get_history(range_string) # Run mypy on that commands print("Running type checks on:") print(commands) result = run(["-c", commands, *mypy_arguments]) if result[0]: print("\nType checking report:\n") print(result[0]) # stdout if result[1]: print("\nError report:\n") print(result[1]) # stderr # Return the mypy exit status return result[2] ip = get_ipython() ip.register_magics(MypyMagics)
We have the
MypyMagics class (that inherits from
Magics) and in it, we have the
mypy line magic that does the following:
- checks if
mypyis installed
- if there were no arguments passed - it returns a short information on how to use it correctly.
- parses the arguments and splits those intended for
mypyfrom the cell numbers/ranges. Since
mypydoesn’t accept arguments that look like a number (
1) or range of numbers (
1-2), we can safely assume that all arguments that match one of those 2 patterns, are cells.
- retrieves the input values from the cells using the
_get_historyhelper (explained below) as a string, and prints that string to the screen, so you can see what code will be checked.
- runs the
mypycommand, prints the report and returns the exit code.
At the end, we need to remember to register the
MypyMagics class in IPython.
We are using one helper function on the way:
def _get_history(range_string): ip = get_ipython() history = ip.history_manager.get_range_by_str(range_string) # history contains tuples with the following values: # (session_number, line_number, input value of that line) # We only need the input values concatenated into one string, # with trailing whitespaces removed from each line return "\n".join([value.rstrip() for _, _, value in history])
I told you before, that when writing a class, we can put our helper function inside, but I’m purposefully keeping this one outside of the
MypyMagics. It’s a simple helper that can be used without any knowledge about our class, so it doesn’t really belong in it. So, I’m keeping it outside and using the naming convention to suggest that it’s a private function.
Coming up with the
_get_history helper was quite a pickle, so let’s talk a bit more about it.
Approach 1:
_ih
I needed to retrieve the previous commands from IPython, and I knew that IPython stores them in
_ih list (so, if you want to retrieve, let’s say, the first command from the current session, you can just run
_ih[1]). It sounded easy, but it required some preprocessing. I would first have to translate
1-2 type of ranges into list slices. Then I would have to retrieve all parts of the history, one by one, so for
1 2-3 5, I would need to call
_ih[1],
_ih[2:4],
_ih[5]. It was doable, but I wanted an easier way.
Approach 2:
%history
My next idea was to reuse the
%history magic function. While you can’t just write
%history in Python code and expect it to work, there is a different way to call magics as standard functions - I had to use the
get_ipython().magic(<magic_function_name>) function.
Problem solved! Except that
%history magic can either print the output to the terminal or save it in a file. There is no way to convince it to return us a string. Bummer! I could overcome this problem in one of the following 2 ways:
- Since by default
%historywrites to
sys.stdout, I could monkey-patch (change the behavior at runtime) the
sys.stdoutand make it save the content of
historyoutput in a variable. Monkey patching is usually not the best idea and I didn’t want to introduce bad practices in my code, so I didn’t like this solution.
- Otherwise, I could save the output of
%historyto a file and then read it from that file. But creating files on a filesystem just to write something inside and immediately read it back, sounds terrible. I would need to worry about where to create the file, whether or not the file already exists, then remember to delete it. Even with tempfile module that can handle the creation and deletion of temporary file for me, that felt like too much for a simple example.
So the
%history function was a no-go.
Approach 3:
HistoryManager
Finally, I decided to peak inside the
%history and use whatever that function was using under the hood - the HistoryManager from
IPython.core.history module.
HistoryManager.get_range_by_str() accepts the same string formats that
%history function does, so no preprocessing was required. That was exactly what I needed! I only had to clean the output a bit (retrieve the correct information from the tuples) and I was done.
Testing time!
Now, that our
%mypy helper is done (the whole file is available on GitHub) and saved in the IPython startup directory, let’s test it:
In [1]: def greet(name: str) -> str: ...: return f"hello {name}" ...: In [2]: greet('Bob') Out[2]: 'hello Bob' In [3]: greet(1) Out[3]: 'hello 1' In [4]: %mypy 1-3 # this is equivalent to `%mypy 1 2 3` Running type checks on: def greet(name: str) -> str: return f"hello {name}" greet('Bob') greet(1) Type checking report: <string>:4: error: Argument 1 to "greet" has incompatible type "int"; expected "str" Out[4]: 1 # What about passing parameters to mypy? In [5]: import Flask In [6]: %mypy 5 Running type checks on: import flask Type checking report: <string>:1: error: No library stub file for module 'flask' <string>:1: note: (Stub files are from) Out[6]: 1 In [7]: %mypy 5 --ignore-missing-imports Running type checks on: import flask Out[7]: 0
Perfect, it’s working exactly as expected! You now have a helper that will check types of your code, directly in IPython.
There is only one thing that could make this even better - an automatic type checker that, once activated in IPython, will automatically type check your code as you execute it. But that’s a story for another article.
Conclusions
This the end of our short journey with IPython magic functions. As you can see, there is nothing magical about them, all it takes is to add a decorator or inherit from a specific class. Magic functions can further extend the already amazing capabilities of IPython. So, don’t hesitate to create your own, if you find yourself doing something over and over again. For example, when I was working a lot with SQLAlchemy, I made a magic function that converts an sqlalchemy row object to Python dictionary. It didn’t do much, except for presenting the results in a nice way, but boy, what a convenience that was, when playing with data!
Do you know any cool magic functions that you love and would like to share with others? If so, you can always send me an email or find me on Twitter! | https://switowski.com/blog/creating-magic-functions-part3 | CC-MAIN-2019-47 | refinedweb | 1,632 | 59.03 |
All you ever wanted to know about Windows Forms and Windows Presentation Foundation Interoperability (plus some other stuff).
(Blogging Tunes: Screaming Headless Torsos - "1995")
We've talked about hosting Windows Forms controls in WPF applications, but what about the other way? You may very well want to just keep your existing Windows Forms application and "sprinkle" in some WPF sweetness in strategic places. That means you will need some means to be able to place WPF controls side-by-side with Windows Forms controls. Is it do-able? Well, if it weren't, I probably wouldn't have a blog entry on the subject now would I?
So what we'll do is create the converse of our other application that demonstrated hosting a Windows Forms ListBox in a WPF application. That means that we will create a Windows Forms application and have it host a WPF ListBox. Pretty exciting huh? Try to contain yourself...
First step is to create a Windows Forms application using Visual Studio (VS):
Next we'll need to add reference to the WPF namespaces and the System.Windows.Forms.Integration namespace:
Note that you will need the following references: PresentationCore, PresentationFramework, UIAutomationProvider, UIAutomationTypes, WindowsBase
Remember, this DLL can be found in the "\Program Files\Reference Assemblies\Microsoft\Avalon\v2.0.50215" directory. Now let's just go to the Load event for our Form and add the code to populate the Form with the WPF ListBox control.
private void Form1_Load(object sender, EventArgs e)
{
ElementHost host = new ElementHost();
System.Windows.Controls.ListBox wpfListBox = new System.Windows.Controls.ListBox();
for (int i = 0; i < 10; i++)
{
wpfListBox.Items.Add("Item " + i.ToString());
}
host.Controls.Add(wpfListBox);
host.Dock = DockStyle.Fill;
this.Controls.Add(host);
}
All we have to do here is create an instance of the ElementHost control, create an instance of the WPF ListBox, populate the ListBox with some items and add it to the ElementHost control. Then we just have to add the ElementHost control to the Form itself. Note that if we don't dock fill the host control, we won't see the ListBox at all. Now let's run the application:
Cool. But what if you don't want to just use a single, standard WPF control? What if you want to instead use a composite WPF control that is defined in some XAML file somewhere. How can you make that happen, Houdini? Well, it's easier than you might think, oh inquisitive one. Let's use the same project, but let's rip out the list box and replace it with a WPF composite control.
Blow away the following lines of code:
System.Windows.Controls.ListBox wpfListBox = new System.Windows.Controls.ListBox();
for (int i = 0; i < 10; i++)
{
wpfListBox.Items.Add("Item " + i.ToString());
}
host.Controls.Add(wpfListBox);
Next let's add a new item to our project, specifically an Avalon UserControl:
This will create a UserControl1.xaml and a UserControl1.xaml.cs file and put them in our project. As you may guess, this just provides you with a XAML file that will describe the WPF composite control and the code behind file to go with it. So let's modify the UserControl1.xaml file to represent the composite control:
<UserControl x:Class="WindowsApplication89.UserControl1"
xmlns=""
xmlns:
<UserControl.FixedTemplate>
<Grid Background="VerticalGraident LemonChiffon Red">
<StackPanel>
<Button>Hello</Button>
<Button>From</Button>
<Button>WFP</Button>
</StackPanel>
</Grid>
</UserControl.FixedTemplate>
</UserControl>
You can see that all we are really doing here is creating a composite of three WPF buttons. Obviously, you would want to do something much more useful, but I'm too lazy to think of anything really clever here. Let's build the app and see what happens!
DOH! Whaddya mean an ERROR? Yep, you should have the following error:
What happened? Well, let's think about the error for just a minute... If you double-click the error message to take you to the line of code that it is complaining about, you will see that it takes you to the code behind file for your WPF UserControl and it is complaining about the InitializeComponent method call in that class. Huh? What's going on here? I have no idea where the implementation of this method is supposed to be! To understand what's happening here, you have to have some insight into how WPF works. When you create a WPF application, the project template is smart enough to know how to deal with XAML objects. Specifically, when you build a WPF project, the compiler knows how to parse the XAML, create a binary representation of the XAML (known as BAML) and generate code for the XAML. The problem is that we have a Windows Forms application and not a WPF application and the template we used to create this application does not know anything about XAML.
Whatchoo talkin' 'bout Willis?
Well Gary, we have to teach the Windows Forms application how to understand the XAML files and to know what to do with them so the right thing happens. We do this by hand modifiying the project file (.csproj, .vbproj, etc.). YIKES! Okay, don't panic. It's not that big of a deal. Just go find the project file and open it up in your favorite text editor (which is of course Notepad, isn't it?). Make sure you don't just double-click on the project file or VS will just open the project. Okay, now that we have the project file open in the editor, scroll down to the bottom of the file. You will see the following line:
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
This line instructs the build system how to build general CSharp applications. We have to add a similar line to tell the build system how to deal with WPF things as well. So what we'll do is copy that line, paste it below the other one and make a small change.
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Import Project="$(MSBuildBinPath)\Microsoft.WinFX.targets" />
Notice that all we changed after we pasted the line was that we changed CSharp to WinFX. Now the build system will know how to foshizzle the XAML! Okay, let's save the project file, then reopen the project using VS and rebuild the solution.
Ah, success at last! If you're really nosy, you can cruise over to the bin directory below your project and see all of the files that get created for you as a result of adding this line. This is where the implementation of the InitializeComponent method lives (among other stuff).
This little hiccup is just a temporary situation, by the time we ship the integration layer, we should have these kinds of details ironed out so you won't have to do such a goofy hack. Okay, let's run the beast:
There you have it! Okay, I'm gettin' kinda' hungry so I'm gonna go get some grub. Happy interop everybody! | http://blogs.msdn.com/mhendersblog/archive/2005/10/03/476536.aspx | crawl-002 | refinedweb | 1,165 | 65.01 |
[Date Index]
[Thread Index]
[Author Index]
Re: Help Providing a Module
In a message dated 3/1/03 11:41:08 PM, flip_alpha at safebunch.com writes:
> I have
>
> a = {-1, 2, 3, 61};
> q = {{{-1, 1}, {3, 2}}, {{-1, 1}, {2, 3}, {3, 6}, {61, 1}}, {{2, 2}, {61 ,
> 1}}}
>
> I want a module vects[a_, q_ ] that will produce (notice, the number of
> vectors is the length of q and the number of values within each vector is
> the length of "a":
>
> evects = {{1 , 0, 0, 0} , {1, 0, 0, 1}, {0, 1, 0, 0}}
>
> We see that the first values of the submatrices in q have -1 and 3, and
> those exist in "a", so in each position where the values in a exists, we
> take the mod base 2 of the second value of that value.
>
> So for example, we have {-1, 1} and {-1} exists in a, thus we take Mod[1,
> 2]
> = 1 as the first evect. Then we see that there is no 2 in q, so we have a
> zero, Then we have 3 in q and that does exist, so we take Mod[2, 2] = 0 as
> the value in the evect. Then, there is no 61, so we have a zero.
>
> Thus, the first vector is {1, 0, 0, 0}. (The values in this vector are
> either zero if the value in the first position of the submatrix doesn't
> exist, otherwise we take the Mod[*, 2] of the second value for the value in
> the vector). I hope that makes sense.
>
> We then look at he second submatrix in q and it contains as the first value
> of each submatrix, so we can take Mod[*, 2] of each second value and get
> {1,
> 1, 0, 1}.
>
> The tird would be {0, 0, 0, 1}. And so on (as q could be larger).
>
> Thus, the vect[a, q] will return (in this example): {{1, 0, 0, 0}, {1, 1,
> 0,
> 1}, {0, 0, 0, 1}}
>
> The length of a varies and the length of q varies.
>
> We could have a = {-1, 2} and q = {{{-1, 1},{2, 3}, {5, 6}, {7, 8}}, {{-1,
> 1}, {3, 2}}}, for example.
>
> I tried doing this, but made a mess of things. Can someone provide such a
> module?
>
I'm not sure what you want since your example and explanation appears to be
inconsistent. However, this should give you an idea of how to approach it:
vects[a_?VectorQ, q_List] :=
PadRight[#, Max[Length /@ q]]& /@
Map[If[MemberQ[a, First[#]], Mod[Last[#], 2], 0]&, q, {2}];
a = {-1, 2, 3, 61};
q = {{{-1, 1}, {3, 2}}, {{-1, 1}, {2, 3}, {3, 6}, {61, 1}}, {{2, 2}, {61,
1}}};
vects[a,q]
{{1, 0, 0, 0}, {1, 1, 0, 1}, {0, 1, 0, 0}}
Bob Hanlon | http://forums.wolfram.com/mathgroup/archive/2003/Mar/msg00044.html | CC-MAIN-2014-10 | refinedweb | 470 | 80.04 |
Docker Interview Questions: If you’re looking for questions to help you prepare for a job interview in Docker, you’re in the right place. There are many opportunities from reputable companies all over the world. This means there’s still room for advancement in your career as a Docker engineer. We’ve gathered some advanced Docker Interview Questions that will help you during your interview and land your dream job as a Docker engineer!
We’ve put together a collection of Docker interview questions and answers, so you can be prepared for your next job interview. These questions are suitable for experienced, intermediate, and primary levels.
If you’re interviewing for a job that uses Docker, you’ll want to be prepared for some challenging questions. This article will give you a good overview of the kinds of questions you might be asked. With a little practice, you’ll feel more confident when sitting down for your?
Docker Interview Questions For Devops Engineer
- Can you tell me something about the docker container?
- What are docker images?
- What is a DockerFile?
- Can you tell what is the functionality of a hypervisor?
- What can you tell about Docker Compose?
- Can you tell me something about the docker namespace?
- What is the docker command that lists the status of all docker containers?
- In what circumstances will you lose data stored in a container?
- What is the docker image registry?
- How many Docker components are there?
- What is a Docker Hub?
- What command can you run to export a docker image as an archive?
- What command can be run to import a pre-exported Docker image into another Docker host?
- Can a paused container be removed from Docker?
- What command is used to check for the version of the docker client and server?
Docker Intermediate Interview Questions For Java Developers
- Differentiate between virtualization and containerization.
- Differentiate between COPY and ADD commands that are used in a Dockerfile?
- Can a container restart by itself?
- Can you tell the differences between a Docker Image and a Layer?
- What is the purpose of the volume parameter in a docker run command?
- Where are docker volumes stored in docker?
- What does the docker info command do?
- Can you tell the what are the purposes of up, run, and start commands of docker-compose?
- What are the basic requirements for the docker to run on any system?
- Can you tell me the approach to login into the Docker registry?
- List the most commonly used instructions in Dockerfile?
- Can you differentiate between Daemon Logging and Container Logging?
- What is the way to establish communication between the Docker host and the Linux host?
- What is the best way of deleting a container?
- Can you tell the difference between CMD and ENTRYPOINT?
Docker Advanced Interview Questions
- Can we use JSON instead of YAML while developing the docker-compose file in Docker?
- How many containers you can run in Docker and what are the factors influencing this limit?
- Describe the lifecycle of the Docker Container?
- How to use docker for multiple application environments?
- How will you ensure that container 1 runs before container 2 while using docker-compose?
Conclusion
Here are some questions you might be asked in a Docker interview. How many of them do you know the answer to? Let us know in the comment window below. | https://www.softwaretestingo.com/docker-interview-questions/ | CC-MAIN-2022-40 | refinedweb | 557 | 59.7 |
Board index » python
All times are UTC
import os import sys
def Parser(filename): lines = None try: fsock = file("forparser.py","r",0) try: lines = fsock.readlines() finally: fsock.close() except IOError: print IOError.__str__ return
for line in lines: print line
if __name__ == "__main__": Parser("c:\forparser.py")
In addition you could import traceback and print the stack. This may give you more interesting information. It would look something like this: import traceback ... try: ... except IOError, e: print str(e) traceback.print_exc() return
Yours, Noah
Sent: Sunday, May 19, 2002 7:50 PM
Subject: why the code error?
i'm a newbie of python. i encounter a problem in my programming. here is my program. when it's running, a IOError always raised. why? and how can i get more detail error message of the exception?
if __name__ == "__main__": Parser("c:\forparser.py")
>def Parser(filename): > lines = None > try: > fsock = file("forparser.py","r",0)
> for line in lines: > print line
for line in open('filename').readlines(): print line
but that's just personal preference.
Otherwise, the \f will be changed to a formfeed -- 0x0C. --
Providenza & Boekelheide, Inc.
> import os > import sys
> def Parser(filename): > lines = None > try: > fsock = file("forparser.py","r",0)
(and "r" is the default, if you want to save typing)
> for line in lines: > print line
> if __name__ == "__main__": > Parser("c:\forparser.py")
1. Why do I get Load Error code 8 from Labview
2. why do i get error code -2147024891?
3. why error message on this form code below
4. why why why oh why why baby
5. Why this MAKE Error ->Make error: No source for objet .obj
6. what is a DOS error code 170 DBFNTX/1001 open error =
7. Error code DBFCMD 2001 : ORDLISTCLEAR() error
8. Thorw an error or return an error code
9. Why, Why Why????
10. why why why (mouse related question)
11. MVCL (was Re: why code in 370 Assembler)
12. why code in c or assembler? | http://computer-programming-forum.com/56-python/1431de9b3c65a867.htm | CC-MAIN-2019-35 | refinedweb | 332 | 79.77 |
XvPutVideo(3X) UNIX Programmer's Manual XvPutVideo(3X)
XvPutVideo - write video into a drawable
#include <X11/extensions/Xvlib.h> XvPutVideo from which to get video. d Defines the drawable (window) into which video is to be written. gc Defines the graphical context. GC components are: subwindow-mode, clip-x-origin, clip-y- origin, and clip-mask. vx,vy,vw,vh Define the size and location of the source (video) region to be written. vx and vy define the upper-left pixel of the region. vw and vh define the width and height, in pix- els, of the region. dx,dy,dw,dh Define the location and size of the destina- tion (drawable) region into which the video image is written. dx and dy define the upper-left pixel of the region. dw and dh define the width and height, in pixels, of the region.
XvPutVideo writes video into a drawable. The position and size of the source (video) rectangle is specified by vx, vy, XFree86 Version 4.5.0 1 XvPutVideo(3X) UNIX Programmer's Manual XvPutVideo(3X) vw, and vh. The position and size of the destination (draw- able)- able.X)GC] Generated if the requested graphics context does not exist. [BadAlloc] Generated if there were insufficient resources to process the request.
XvPutStill(3X), XvGetVideo. | http://mirbsd.mirsolutions.de/htman/sparc/man3/XvPutVideo.htm | crawl-003 | refinedweb | 216 | 68.67 |
25 March 2010 14:41 [Source: ICIS news]
SINGAPORE (ICIS news)--Japanese refiner Idemitsu Kosan plans to shut down three of its refineries during the second half of 2010 in response to weak market conditions, a source close to the company said on Thursday.
The source said the company planned to shut down its 140,000 bbl/day ?xml:namespace>
Indemitsu’s 120,000 bbl/day Tokuyama refinery would shut down between November and December also for around 30 days, the source said.
Earlier in March, Indemitsu announced plans to lower operating rates at its refineries to around 448,000 bbl/day or around 70% of capacity from 1 April. Earlier in 2010 operating rates were around 79% of capacity.
The move by Indemitsu has come amid an ongoing decline in Japanese oil demand over recent years, which has been exacerbated by the recent global recession.
The decline in
Idemitsu operates four refineries | http://www.icis.com/Articles/2010/03/25/9345911/Idemitsu-Kosan-to-shut-down-three-refineries-in-2010.html | CC-MAIN-2014-15 | refinedweb | 153 | 50.77 |
Microsoft Shareholders Unhappy After Annual Meeting
Unknown Lamer posted more than 2 years ago | from the 15-minutes-should-be-enough-for-anyone dept.
.... (5, Insightful)
ThisIsNotMyHandel (1013943) | more than 2 years ago | (#38068562)
Re:Simple solution.... (5, Insightful)
fsckmnky (2505008) | more than 2 years ago | (#38068746)
Re:Simple solution.... (1, Troll)
Runaway1956 (1322357) | more than 2 years ago | (#38069102)
Anything that makes Microsoft or Microsoft shareholders unhappy is a good thing, IMHO.
Re:Simple solution.... (5, Informative)
Ihmhi (1206036) | more than 2 years ago | (#38069134)
Would the term you're thinking of happen to be the sunk cost fallacy [wikipedia.org] ?
Re:Simple solution.... (0)
Anonymous Coward | more than 2 years ago | (#38069218)
Judging by MS' flat share price for the past decade, I'd say many people have sold the stock. My guess is that what you saw in this meeting is the people who were either too dumb to sell it, or are people who are just sitting on it and collecting dividend checks. The latter of course don't really care too much about things like stock holders meetings, just so long as the dividends keep rolling in.
Re:Simple solution.... (1)
Billly Gates (198444) | more than 2 years ago | (#38069250)
That would devalue the stock more.
If MS bought some of its own shares that would limit supply and increase its price.
Just now they're "disgruntled"? (5, Interesting)
bmo (77928) | more than 2 years ago | (#38068570)"? (4, Interesting)
JoeMerchant (803320) | more than 2 years ago | (#38068614)
Haven't there been some pretty fat dividends on occasion? I really wish the Y! charts would include an option to represent present value of a DRIP [fool.com] investment at the beginning of the period.
Re:Just now they're "disgruntled"? (-1, Flamebait)
bmo (77928) | more than 2 years ago | (#38068626)
Dividends are not growth.
Learn stock basics.
--
BMO
Re:Just now they're "disgruntled"? (1)
Anonymous Coward | more than 2 years ago | (#38068686)
Dividends are still profit, which is what all shareholders are after whatever form it comes in.
Learn economics basics.
Re:Just now they're "disgruntled"? (-1, Flamebait)
bmo (77928) | more than 2 years ago | (#38068738)
Oh, look, a softie redefining words at whim.
You're an idiot.
Here, have another chart. This is growth.
You should have bought AAPL, ya dummy. [yahoo.com]
--
BMO
Re:Just now they're "disgruntled"? (4, Interesting)
JoeMerchant (803320) | more than 2 years ago | (#38068854)"? (-1, Flamebait)
bmo (77928) | more than 2 years ago | (#38069112)
>1988 to 1998.
--
BMO
Re:Just now they're "disgruntled"? (0)
Anonymous Coward | more than 2 years ago | (#38068892)
And you're an asshole. You should have learned how to be a decent human, ya fucknut.
Re:Just now they're "disgruntled"? (3, Informative)
similar_name (1164087) | more than 2 years ago | (#38068996)
Re:Just now they're "disgruntled"? (3, Interesting)
icebike (68054) | more than 2 years ago | (#38069068)"? (5, Insightful)
JoeMerchant (803320) | more than 2 years ago | (#38068718)
Dividends are not growth.
Learn stock basics.
I'm an investor, I care about DI/DO - dollars in / dollars out. Dividends matter. Give me a flat stock price and reliable 20% dividends and I don't care at all about growth.
Re:Just now they're "disgruntled"? (-1, Flamebait)
bmo (77928) | more than 2 years ago | (#38068762)
Then go own stock in your local gas company.
It's not growing either.
--
BMO
Re:Just now they're "disgruntled"? (-1)
Anonymous Coward | more than 2 years ago | (#38068988)
You've got too much stock in your own gas... and that's an industry that's growing faster than most. At least in this thread. Be entitled to your opinion, fine, but grow the fuck up and learn how to be polite. Fucking 5-year old.
Re:Just now they're "disgruntled"? (2)
elbonia (2452474) | more than 2 years ago | (#38068914)
Re:Just now they're "disgruntled"? (2, Informative)
bmo (77928) | more than 2 years ago | (#38069006)"? (0)
Anonymous Coward | more than 2 years ago | (#38069076)
Gold is up on average 17% annually for the past ten years. No dividend though (and a 28% 'collectibles' tax on gains).
Re:Just now they're "disgruntled"? (1)
trout007 (975317) | more than 2 years ago | (#38069278)
The Canadian oil trusts were 10% for years before the Canadian government started taxing them at the corporate level. PWE and PGH come to mind. There are others.
Re:Just now they're "disgruntled"? (2)
oakgrove (845019) | more than 2 years ago | (#38068948)
Re:Just now they're "disgruntled"? (2)
JoeMerchant (803320) | more than 2 years ago | (#38069258) chunk of their stock. I have held a chunk of O [yahoo.com] for about 10 years now... it has been good to me, better than a lot of the "growth" stocks.
Re:Just now they're "disgruntled"? (0)
Anonymous Coward | more than 2 years ago | (#38068724)
Dividend not important? Dividend is an integral part of a stock ROI, learn your basic. At 0.80 per year or 3%, over ten years, it would be equivalent to a 30% increase in the stock price.
Of course tax treatment is different though, but cash is cash.
Re:Just now they're "disgruntled"? (4, Interesting)
bmo (77928) | more than 2 years ago | (#38068898)
:Just now they're "disgruntled"? (-1)
Anonymous Coward | more than 2 years ago | (#38069310)
You appear to be a moron.
Re:Just now they're "disgruntled"? (2)
ckaminski (82854) | more than 2 years ago | (#38068882)
Profits (and dividends) matter if you really want to make reliable money.
Re:Just now they're "disgruntled"? (1, Interesting)
theshowmecanuck (703852) | more than 2 years ago | (#38068918)
Re:Just now they're "disgruntled"? (0)
Anonymous Coward | more than 2 years ago | (#38069300)
In what way does one benefit from owning a stock if that stock doesn't increase in value? It is not rational to sink a bunch of money into something just so it can stay flat or trickle away. Given a choice between letting money sit and lose value to inflation, or investing it in something that will make one richer, it is perfectly rational to pick the profitable option.
This is how humans work. Rational humans, anyway.
Re:Just now they're "disgruntled"? (0)
Anonymous Coward | more than 2 years ago | (#38069292)
Dividends are not growth.
Learn stock basics.
--
BMO
And this f*** attitude is exactly why the economy is screwed. Give me a long term dividend producing stock over so-called "growth" any day.
Re:Just now they're "disgruntled"? (2)
NFN_NLN (633283) | more than 2 years ago | (#38069298)
Dividends are not growth.
Learn stock basics.
--
BMO
Where I live (and report income), dividends are taxed at a lower rate than capital gains.
So, comparing apples to apples, you are better off getting the same return in the form of dividends.
Re:Just now they're "disgruntled"? (1)
larry bagina (561269) | more than 2 years ago | (#38068832)
Re:Just now they're "disgruntled"? (4, Informative)
Citizen of Earth (569446) | more than 2 years ago | (#38068894)
Re:Just now they're "disgruntled"? (1)
JoeMerchant (803320) | more than 2 years ago | (#38068928)
I was thinking of the $3 payout in 2004, yeah, MS is not a growth company, unless you believe they're going to set the world on fire with Nokia, or Kinect, or something else they haven't advertised yet... I don't (believe), and that's why I'm not invested in MS.
Re:Just now they're "disgruntled"? (1)
tsalmark (1265778) | more than 2 years ago | (#38068646)
Re:Just now they're "disgruntled"? (1)
rolfwind (528248) | more than 2 years ago | (#38068650) [dividend.com]
It's about $.80 per share per year now. Idk where to look for past dividend payouts, but figuring this is steady, the past decade it comes to $8 a share, about 1/3 of it's price.
Now, I don't fee like calculating what if the early shares were reinvested, someone else can do that, so I'll stop the calculation theres, but at the surface, 33% growth over a decade isn't exactly encouraging.
Re:Just now they're "disgruntled"? (1)
larry bagina (561269) | more than 2 years ago | (#38068970)
Re:Just now they're "disgruntled"? (5, Informative)
Antony T Curtis (89990) | more than 2 years ago | (#38068668)"? (4, Informative)
russotto (537200) | more than 2 years ago | (#38068768)
Except that, as the disclaimer says, past performance is no guarantee of future results. Not that I'm buying any MSFT.
An oldie but goodie: The Ballmer Stagnation [zdnet.com]
Re:Just now they're "disgruntled"? (1)
Threni (635302) | more than 2 years ago | (#38068932)
> An oldie but goodie: The Ballmer Stagnation
LOL! I like the y axis.
"This gives a little bit of an exaggerated sense of how much Microsoft grew under Gates."
Uh..yeah, it does.
Re:Just now they're "disgruntled"? (3, Informative)
inviolet (797804) | more than 2 years ago | (#38069270)'t also need to fabricate indictments of Ballmer.
Re:Just now they're "disgruntled"? (2, Insightful)
PCM2 (4486) | more than 2 years ago | (#38068810) -- so you better hope those growth rates hold.
Re:Just now they're "disgruntled"? (2)
oakgrove (845019) | more than 2 years ago | (#38068900)
Re:Just now they're "disgruntled"? (1)
Billly Gates (198444) | more than 2 years ago | (#38069308)
It doesn't matter how much a company makes.
Here is what I learned in Finance 101. The goal of any company is to raise the share price and not make money. Investors look for things like insane liquidity ratios. This means assets that you can sell quickly to make money. Having more cash, very sellable assets, and other things to raise cash just in case they do not perform well in the next quarter.
Sure your company is making money now but can you make even more money next quarter? That is the question and selling stuff very quickly reassures the investors the stock price will continue to go up. MS pretty much had so much liquid a decade ago that they bought stocks of other companies. The problem is when the great recession hit they tanked and they were no longer liquid at the price MS paid for them. Even with sales increases it is hard.
Re:Just now they're "disgruntled"? (0)
Anonymous Coward | more than 2 years ago | (#38068824)
Don't compare MS the 2 most successful tech company of the last decade. The whole industry looks pale compare to GOOG and AAPL. Although I agree that MS performance was certainly lackluster of the last decade and they are going nowhere fast.
If all companies that didn't do 4000% growth sucks, well 99.9% of companies sucks.
Re:Just now they're "disgruntled"? (1)
FrankSchwab (675585) | more than 2 years ago | (#38068950)
And if I had a time machine, I'd go back to Google's IPO, when I convinced our investment club that it was a fad stock with no business model that was soon to be the next pets.com.
Sigh. I guess I'm not a good long-term investment choice either.
The thing is, with hindsight you can always find "great long-term investment choices". The trick, of course, is doing it in the present and not in the past.
/frank
Re:Just now they're "disgruntled"? (3, Informative)
tgd (2822) | more than 2 years ago | (#38069002)"? (2)
c0lo (1497653) | more than 2 years ago | (#38068672)
Just now they're "disgruntled"?
I mean... what did they think?
/. posters are disgruntled for ages already.
Re:Just now they're "disgruntled"? (1)
Albanach (527650) | more than 2 years ago | (#38068902)
This graph is probably more useful for the average investor. [goo.gl]
Over the past five years MS have outperformed the NASDAQ and the S&P500 by 20%
Re:Just now they're "disgruntled"? (5, Insightful)
amiga3D (567632) | more than 2 years ago | (#38068944).
Re:Just now they're "disgruntled"? (1)
Nerdfest (867930) | more than 2 years ago | (#38069124)
Re:Just now they're "disgruntled"? (0)
Anonymous Coward | more than 2 years ago | (#38068974)
Low UID to troll.
What would you trust more to hold your money? 67% tied to fickle consumer products. The market is run by computers, not common sense.
Re:Just now they're "disgruntled"? (1)
LordThyGod (1465887) | more than 2 years ago | (#38069050)
Re:Just now they're "disgruntled"? (0)
Anonymous Coward | more than 2 years ago | (#38069234)
May not look encouraging to you, but MOST buzz I've been hearing suggests that most people are excited about the look and potential of Windows 8, me included.
Re:Just now they're "disgruntled"? (4, Insightful)
jbolden (176878) | more than 2 years ago | (#38069340).
Dividends? (3, Insightful)
XanC (644172) | more than 2 years ago | (#38068584)
Doesn't MSFT pay dividends? You can't just look at the chart of the stock price. The fair way to construct such a chart would be a graph of an investor's money assuming he reinvested the dividends.
Re:Dividends? (4, Informative)
c0lo (1497653) | more than 2 years ago | (#38068634)
Doesn't MSFT pay dividends?
quarterly [dividend.com] .
There's no excuse for a 15 min Q&A (5, Insightful)
elbonia (2452474) | more than 2 years ago | (#38068598) [geekwire.com]
I would have left too if those were the best answers I could come up with for those questions.
Re:There's no excuse for a 15 min Q&A (0)
Anonymous Coward | more than 2 years ago | (#38068754)
Warren Buffet also has no problem admitting he's fucking the American people. Good role model you fucking bitch.
Re:There's no excuse for a 15 min Q&A (1)
Grishnakh (216268) | more than 2 years ago | (#38068952)
The OP never said Buffet was a saint, just that, compared to Ballmer, he has a lot more consideration for his shareholders. If Buffet is an asshole for fucking the American people as you say, then what does that mean for Ballmer, who can't even be bothered to spend a half hour answering questions?
Re:There's no excuse for a 15 min Q&A (1, Flamebait)
elbonia (2452474) | more than 2 years ago | (#38069054)
Exactly how did he do that moron? By warning people how financial derivates would crash the market? By demaning stock grants be factored into quarter earnings at the time they are granted? Fucking read a book, maybe then you wont have an IQ of a fruit fly.
Re:There's no excuse for a 15 min Q&A (1)
TurtleBay (1942166) | more than 2 years ago | (#38068870)
Unhappy about static share price? (5, Insightful)
qubezz (520511) | more than 2 years ago | (#38068602)
Re:Unhappy about static share price? (4, Insightful)
NonSequor (230139) | more than 2 years ago | (#38068816):Unhappy about static share price? (3, Insightful)
Anonymous Coward | more than 2 years ago | (#38068886):Unhappy about static share price? (2)
PCM2 (4486) | more than 2 years ago | (#38068922)
As many other people have mentioned, Microsoft does pay a quarterly dividend, currently annualized at about 3 percent.
Re:Unhappy about static share price? (2)
Dhalka226 (559740) | more than 2 years ago | (#38068934):Unhappy about static share price? (0)
Anonymous Coward | more than 2 years ago | (#38069020)
Re:Unhappy about static share price? (0)
Anonymous Coward | more than 2 years ago | (#38069024)
Those companies pay large dividends. You trade a static stock price for guaranteed returns. MSFT pays a very small dividend.
Re:Unhappy about static share price? (0)
Anonymous Coward | more than 2 years ago | (#38069154)
Please overlay GM and IBM with MSFT and recall in horror at your own ignorance.
Shareholders are stupid (5, Insightful)
Anonymous Coward | more than 2 years ago | (#38068628)]
You've never invested in anything, have you? (-1, Troll)
jmcbain (1233044) | more than 2 years ago | (#38068888)
Re:You've never invested in anything, have you? (2)
Anonymous Coward | more than 2 years ago | (#38069200)
No, you're the idiot. You obviously don't understand the point I was making.
Microsoft doesn't control the price their stock trades for in the market. They have been doing their part -- increasing profits -- but the shareholders have decided the stock is worth exactly the same amount. THEREFORE shareholders are stupid.
What do you expect Microsoft to do? Have Ballmer go down to Wall Street and scream Developers! Developers! Developers! ?
MS makes 3x the amount Google does in profits. For 2010, MS made 50% more than Apple. Only this past year has Apple matched Microsofts profits. Yet, Apple and Google get bid up to insane levels based almost solely on emotions.
So if shareholders want to base Microsoft's share price on their emotions, instead of Microsoft's financials, then that's their problem, not Microsoft's.
Re:You've never invested in anything, have you? (1)
whoever57 (658626) | more than 2 years ago | (#38069240)
Do what other comapies do when they think that their stock is undervalued. Buy up their own stock in the market.
Re:You've never invested in anything, have you? (1, Informative)
jmottram08 (1886654) | more than 2 years ago | (#38069264)
Re:Shareholders are stupid (1)
oakgrove (845019) | more than 2 years ago | (#38069120)
In a related thread... (1)
bmo (77928) | more than 2 years ago | (#38068648) [fark.com]
Substitute Microsoft for Fark.
--
BMO
Pretty crappy return (1)
stox (131684) | more than 2 years ago | (#38068662)
3% yield on dividend is relatively poor. But there are worse places to put one's money.
Re:Pretty crappy return (2)
JoeMerchant (803320) | more than 2 years ago | (#38068890)
3% is 2x what my credit union pays in an IRA, which is itself 3x what most banks pay. Poor, but there's a risk/reward thing to consider.
Dividends (0)
Anonymous Coward | more than 2 years ago | (#38068684)
Microsoft should pay out much larger dividends. It's clear that the R&D isn't turning out good results. Their last good new product was the XBox. If they paid shareholders instead of spending money on silly things like buying Yahoo, then those shareholders wouldn't complain.
Re:Dividends (1)
Grishnakh (216268) | more than 2 years ago | (#38068990)
Their last good new product was the XBox.
That Courier tablet seemed like a very interesting idea, but Bill and Steve shot it down shortly before the iPad came out and became the standard for tablets.
Anyone care to repeat a meme? (1)
erroneus (253617) | more than 2 years ago | (#38068804)
So all this crap about the corporation [required] to serve the interests of the shareholders and all that is simply crap. Shareholders express their dissatisfaction all the time like this only to be ignored by the people who maintain the majority controlling interest... and yet somehow the actions a corporation takes isn't the responsibility of the people who steer the company and often make the very decisions which they are somehow neither responsible nor accountable for.
On the long list of the 99%'s complaints should be a reform of what corporate leaders can be held liable for.
Re:Anyone care to repeat a meme? (1)
Grishnakh (216268) | more than 2 years ago | (#38069008)
I don't think this is quite true: with MS, these dissatisfied shareholders do not (IIRC) maintain a majority controlling interest: Bill and Steve do. That's why they're still in charge after all these years of piss-poor performance and zero vision. In more normal corporations, yes, the shareholders do have a controlling interest, and they can and do oust the executives when they're dissatisfied: just look at HP for example. Of course, these shareholders don't always do the greatest job of selecting executives, again as seen with HP.
Re:Anyone care to repeat a meme? (0)
Anonymous Coward | more than 2 years ago | (#38069148)
I'd love to have my piss poor performance be 23 billion dollars in profit this year. not to mention steady profitability. share price is for the gamblers on wall street.
Re:Anyone care to repeat a meme? (1)
Forbman (794277) | more than 2 years ago | (#38069030)
Well, considering that BillG and Monkeyboy are major shareholders of MSFT stock... if they're happy, their votes count for a bunch at voting time...
Re:Anyone care to repeat a meme? (1)
Anonymous Coward | more than 2 years ago | (#38069086) you can't put a company in jail, and money is not speech..
You'd think... (1)
strangeattraction (1058568) | more than 2 years ago | (#38068808)
Re:You'd think... (3)
PCM2 (4486) | more than 2 years ago | (#38068994).
Innovation lacking, or .... (1)
Anonymous Coward | more than 2 years ago | (#38068852)
So, lets see. A static share price over the past decade...
In that decade they've done the following major things: (IMO)
... and a few minor but interesting things...
- Released Windows XP
- Released XBOX and XBOX Live Network
- Released Window Vista
- Released XBOX 360
- Reached Novell Agreement
- Let Bungie split away
- Showed off Microsoft Surface
- Redefine Microsoft Search with 'bing'
- Released Windows 7
- Released XBOX Kinect
- Released continuously updated versions of Office and Server and misc. software packages, including improving* IE. (Will versions ever end? Bring on rolling release! Or is that what already exists...)
So in point, what has Microsoft done? Kept the industry moving along, business as usual, that's what. Have they come up with game-changing innovation? Obviously not. Have they sunk the ship? No. They're keeping in the game. They're big enough, and have enough clout, that they don't have to redefine themselves every few years.
And, just so you know, I say this as someone who hasn't given MS a dime in over 11 years.
p.s. I'm probably missing some 'biggie events' by some peoples standards. The above are just off the top of my head.
Oh, FFS... (0)
fuzzyfuzzyfungus (1223518) | more than 2 years ago | (#38068924)
C'mon, fucktards, Microsoft has been dead flat(but dividend bearing) for years now. Quit. Fucking. Whining.
If you want to go bubble chasing, sell the boring stuff and invest the proceeds in something wildly volatile. You've got plenty of choices. If you just want your pet stock to go up and up and up, go see if the magic pony you will shortly be receiving for Christmas can take you back a decade or so so you can make smarter buying choices; but, FFS, don't just sit there, holding on to a stock with predictable behavior, and demanding that it make you rich immediately.
If I didn't know otherwise, I'd be inclined to believe that the world's major monotheisms (used to) condemn usury just because people like them were so damn annoying...
Microsoft (5, Insightful)
br00tus (528477) | more than 2 years ago | (#38068976):Microsoft (1)
Anonymous Coward | more than 2 years ago | (#38069268)
What about Xbox? And the Kinect? Not only are they branching out and innovating in the console market, these moves also nicely supplements their leading position regarding PC gaming.
Microsoft is involved in many areas today, and I think you have to look at each area in order to judge them correctly.
Lost decade and a HALF (1)
michaelmalak (91262) | more than 2 years ago | (#38069048)
Putting stock price aside and looking at technology alone, Microsoft has been stagnant for 15 years. NT4 with Office 95 and a quick install of the latest Firefox would give users 90% of the functionality they use today. Fast forward to Office 97 to get 96% functionality (file format compatible with Office 2010). Add a commercial third-party NT4 USB driver and get 99% functionality that is commonly used today.
In 2002, Microsoft came up with a Java/Flash/RIA/HTML5 killer,
.NET, and then decided to not make .NET RIAs mainstream until five years later with Silverlight, when it was too late. This was, in my opinion and guess, a stock market driven decision to avoid killing Windows and Office. Microsoft employed the short-term thinking that results from our stock market system that rewards and demands next quarter's profits and short-term planning.
In the early 1990's, Lotus Notes was taking the world by storm until the web came along. Lotus Notes was a database system that allowed end "power" users to develop GUI database apps that they could immediately share with their coworkers. The web came along and IBM fumbled Notes. Microsoft had a popular web page designer, FrontPage. If they had integrated database capability into it, FrontPage would have ruled the world. Alternatively, Microsoft could have added web capability to Access, or just made it capable of handling more than 1000 records. Access was/is another phenomenal end-user database tool. It's nothing less than an intentional retarding of progress that Microsoft never made it work as an actual database. Undoubtedly, this was again stock-market driven to avoid cannibalizing SQL Server sales. Imagine the productivity the world economy could have experienced over the past decade if SQL Server Lite backend and Access front end were installed on every machine by default (e.g. SQL Server Lite installed with Windows, Access installed with the most basic version of Office). Now further imagine if Microsoft had deeply integrated FrontPage into that bundle!
It's too late now. Drupal et al are, finally after 15 years, the Lotus Notes replacement. Microsoft missed the boat. Goodbye, Microsoft.
Let a ho be a ho (-1)
Anonymous Coward | more than 2 years ago | (#38069096)
Do you know that Muslim faggots eat the shit out of other men's assholes? They eat shit! Muslims are faggots.
Fuck Mohammad! Fuck Allah! Fuck Islam!!!!!
I shit on the unholy faggot Koran.
Dividends... (1)
sdguero (1112795) | more than 2 years ago | (#38069128)
Being the World's Evil Empire has come back. (0)
Anonymous Coward | more than 2 years ago | (#38069192)
Even the small collection of CSci that actually likes Microsoft has huge misgivings about the way the company operates. Compare against the two listed rivals, Apple, who's goal is just to make the best electronics in the world, and Google's is simply to Do No Evil. Maybe making crappy operating systems, and then when no ones buys it, trying to villainishly force their hand wasn't the best choice? Or trying to rip off Apple without adding anything of real value, or being so evil that people don't care if Google collaborates with China, or holding back technical progress in the name of short-term wins, or producing Operating Systerms that give more power to billionaire executives then it does to the people who actually BOUGHT THE PRODUCT, or try to sue rivals out of existence with massively spurious claims,
or, from a privately-owned company perspective, holding back dividends from stock holders, (who collectively OWN THE COMPANY), because you like having a money vault to dive into.
M$ should apologize (2)
Datamonstar (845886) | more than 2 years ago | (#38069210)) (4, Insightful)
bmo (77928) | more than 2 years ago | (#38069290) | http://beta.slashdot.org/story/160622 | CC-MAIN-2014-42 | refinedweb | 4,495 | 74.29 |
Explains how to create queues with the management client, for more posts in this series go to Contents.
Without queues, topics and subscriptions (also called entities) there is not much we can do with an Azure Service Bus namespace. For the start, it is sufficient to create a queue that we will use to send messages to and receive messages from. Creating entities is built into the Azure.Messaging.ServiceBus package and available under the
Azure.Messaging.ServiceBus.Administration namespace.
A management client can be created to interact with the namespace.
var client = new ServiceBusAdministrationClient(connectionString); if (!await client.QueueExistsAsync("queue")) await client.CreateQueueAsync("queue"); await client.CloseAsync();
The above code demonstrates how to query whether an existing queue exists and if it doesn’t create the queue with name “queue” (I know very creative). Deleting a queue is equally simple:
var client = new ServiceBusAdministrationClient(connectionString); if (await client.QueueExistsAsync("queue")) await client.DeleteQueueAsync("queue"); await client.CloseAsync();
For the management operations to work the access policy used to connect to the broker requires the Manage claim.
The really nice thing about those claims is that if you don’t require to create entities during runtime and have a fairly static set of queues, topics and subscriptions (more about those later) you can have two SAS Policies. One SAS policy with manage rights that is only used to create the necessary entities as part of your deployment scripts and one SAS policy without manage rights that is used to actually send and receive messages on the already constructed entities. That gives you an additional layer of certainty that no-code running in production can actually execute destructive operations such as deleting queues. My friend Damien has a great article about restricted access with Azure Service Bus should you wish to dig deeper.
[…] Creating queues […]
[…] the previous post we looked at how queues can be created with the management client. For being able to send messages […] | https://www.planetgeek.ch/2020/03/09/azure-service-bus-net-sdk-deep-dive-creating-queues/ | CC-MAIN-2021-43 | refinedweb | 325 | 55.95 |
Bummer! This is just a preview. You need to be signed in with a Pro account to view the entire video.
Building a WAR for Wildfly13:01 with Chris Ramacciotti
In order to deploy our app to an existing application server, we'll need to build a Web Application ARchive (WAR) that let's the server know about our Spring components.
Structure of a WAR File
If you were to use an archive utility to view the contents of a WAR file, here's what you'd see:
weather-0.0.1-SNAPSHOT.war ├─ META-INF | └─ MANIFEST.MF # empty except for version ├─ WEB-INF | ├─ classes | ├─ api.properties | ├─ application.properties | ├─ com | ├─ teamtreehouse # our root package | ├─ static/ # web app assets | ├─ templates/ # Thymeleaf templates | ├─ jboss-web.xml # context root definition | └─ lib # JARs for dependencies
Java Platform, EE (Enterprise Edition)
Java EE defines a set of standards (APIs) for developing web and other enterprise applications. A Java EE application server is one that provides implementations of the Java EE APIs. For a look at all the packages, annotations, interfaces, enums, abstract classes and classes of Java EE 7, see the documentation here:
Setting the Active Profile(s)
At runtime
You can set the active profile at runtime, for example, when running your app from a JAR. For this option, you'll specify a system property using the
-D option. For example:
java -Dspring.profiles.active=dev -jar build/libs/weather-0.0.1-SNAPSHOT.jar
In Application.java
You can set profiles programmatically using a
SpringApplication object from your apps class that contains the
main method. This class might look as follows:
@EnableAutoConfiguration @ComponentScan public class Application { public static void main(String[] args) { SpringApplication app = new SpringApplication(Application.class); app.setAdditionalProfiles("dev"); app.run(args); } } approach we're going to tackle next,
- 0:01
is one of deploying your build to an existing application server.
- 0:05
In order to deploy your app to an application server,
- 0:07
you'll likely need a WAA file.
- 0:09
WAA stands for Web Application Archive and it's kind of like a jar file, but
- 0:12
its contents have a different structure.
- 0:14
Check the teacher's notes for details on WAA files.
- 0:17
The server all use for demonstrating is WildFly.
- 0:20
Now, this is what used to be known as the JBoss Community Edition.
- 0:24
JBoss is a flagship product as an application server
- 0:26
that's a full implementation of Java Enterprise Edition or Java EE.
- 0:31
This means that the server provides implementations for
- 0:33
all Java EE interfaces.
- 0:35
For example, JBoss implements dependency injection, or
- 0:38
a DI, by leveraging the inject annotation, and
- 0:42
also implements the Java Persistence API, or JPA, with Hibernate.
- 0:47
For more on Java EE, check out the teachers notes as well In any case JBoss
- 0:52
was bought by Red Hat in 2006, but the community edition of JBoss remains
- 0:58
open source and freely available and in 2014 was renamed WildFly.
- 1:04
Before we do anything with WildFly, we'll need to make some code changes to
- 1:07
our application can play nicely with another web server.
- 1:12
Specifically, we need to configure our app for a Servlet 3.0 container.
- 1:16
What is a servlet container you ask?
- 1:19
A servlet container is a component on a web server that is configured to handle
- 1:23
HTTP requests that are process by Java applications.
- 1:26
The container creates and maintains, what are called servlets and these servlets
- 1:30
were the things that interact directly with our application code.
- 1:33
For Spring weather applications typically we'll need to Servlet container to create
- 1:36
Spring's DispatcherServlet which will marshal a quests for
- 1:40
configured controllers.
- 1:42
To configure a Servlet 3.0 container such as that provided by WildFly.
- 1:46
To bootstrap our application and create this DispatcherServlet, we'll need to
- 1:50
implement the web application initializer interface which is an interface
- 1:53
detected by the Servlet container Spring has a handy way of doing this.
- 1:58
So let's go to the application class and do that.
- 2:00
Spring-boot provides an abstract class called
- 2:04
SpringBootServletInitializer that we can extend right here.
- 2:09
So extends SpringbootServletInitializer just like that.
- 2:14
Now this is an abstract class and if you look at the source,
- 2:18
it implements that WebApplicationInitializer interface.
- 2:22
Cool, now in this class we'll then override the configure method right
- 2:28
here which allows us to add the sources of all of our configuration classes.
- 2:33
Now, in this method, we'll just add the application class since it
- 2:36
already includes an annotation to scan for
- 2:39
components in its package and all sub-packages.
- 2:43
So let's do that now, I will use that builder or parameter value there.
- 2:50
I will add the source application that class, cool.
- 2:54
There are other things you could do here in this method.
- 2:57
So check the teacher's notes for an example.
- 3:00
Next, let's move to the data config class In our application deployed
- 3:05
to WildFly we'll configure the data source on the web server itself.
- 3:08
As you'll see on the web server we'll end up giving our database an easy to look up
- 3:12
name using the Java naming and directory interface or JNDI.
- 3:16
This is just a way for Java applications to look up databases or objects by name.
- 3:23
What this means for us in our data config class is that we'll need an alternate
- 3:27
data source bin to be used in our application that's deployed to WildFly.
- 3:32
This one that's configured in the application will no longer suffice
- 3:35
since that configuration will now appear on WildFly itself.
- 3:40
So what we'll wanna do is create another data source bean method.
- 3:44
Just like this.
- 3:46
Bean public datasource and
- 3:51
I'll call this jndiDataSource.
- 3:57
Now, we want this DataSource being to be picked up sing the simple name
- 4:01
DataSource but this method name is not data source in fact in order for
- 4:05
the Java code to compile a cannot be DataSource that's a compiler error.
- 4:09
Two methods with the same signature and same class cannot exist.
- 4:13
So let's specify that the name of this being is DataSource.
- 4:19
Now the name of this bean up here is already by default data source because by
- 4:22
default spring will use the method name to name beans.
- 4:28
Now to be sure that our application only has one unique data source being available
- 4:35
to it at run time, we need to specify what are called profiles in spring.
- 4:40
For example we could use this being here all specify the profile we
- 4:45
could use this bean in production abbreviated prod and
- 4:50
this bean in will say a development environment abbreviated dev.
- 4:57
Now, in any given deployment,
- 4:58
whether it's in a development environment or in a production environment,
- 5:01
I want to make sure that exactly one of these beans is available, this bean for
- 5:07
the production environment and this bean for the development environment.
- 5:11
In order to do that, I need to set the active profile in spring
- 5:17
If we don't set the active profiles, spring will detect two dataSource beans
- 5:22
as injectable and when that happens and
- 5:25
a dataSource bean as needed, we will get a no such bean definition exception.
- 5:29
Since bean definitions need to be unique in any running application.
- 5:35
Now, there are a couple ways to do this, I'll demonstrate one option here and leave
- 5:38
a couple other options in the teacher's notes, so, be sure to check those out.
- 5:41
The optional show here, is setting the active profile and application.properties.
- 5:46
This is a pretty speedy task for us, we'll create a property at the top,
- 5:51
named spring.profiles .active and
- 5:56
set it to prod and that's it.
- 6:00
Now when an application has multiple qualifying beings available as a lot of
- 6:03
wired or otherwise injected dependencies assuming only one of those has been
- 6:07
annotated with the profile prod that one will be chosen and
- 6:12
we can avoid that no such being definition exception
- 6:16
the other thing this allows us to do is pretty handy here.
- 6:19
It allows us to avoid the scenario where we're commenting out one of these or
- 6:23
the other.
- 6:23
When we're switching between the two environments, we can leave both intact and
- 6:27
set a profile for each one of them, individually.
- 6:30
Pretty handy feature in spring.
- 6:32
Okay, let's implement this jndiData Source method right here.
- 6:38
Do here is use Springs
- 6:42
jndidatasource to look up to grab the name of the data source.
- 6:46
So that's new jndidatasourcelookup, and since I don't want to
- 6:52
hard code configuration in my source code I'll grab this from the properties file.
- 6:55
So getdatasource(end).
- 6:58
.get property and
- 7:01
I'll say it's Weather.jndi let me stick my sim icon at the end and
- 7:07
of course we better add that property to our properties file.
- 7:11
So let's go back to application.properties and
- 7:15
I will add that right here whether.jndi and
- 7:20
I will set that equal to java colon slash weather.
- 7:24
Now, by convention, we begin a jndi name with this URL scheme, java colon slash.
- 7:32
Cool, that should do it for the properties put these file here.
- 7:34
But hey speaking of properties we need to be careful with our
- 7:37
property source annotations.
- 7:39
Now, unless otherwise specified in our app that's deployed to wild life
- 7:43
those properties file paths will be considered relative to the root of our app
- 7:47
instead of the class path.
- 7:48
To make sure that our properties are still found we need to indicate
- 7:51
that those are on the class path.
- 7:53
Now I'll use Control + Shift + F to trigger a global search here.
- 7:59
We'll do PropertySource just like that, and I see I have five locations
- 8:07
where I have the PropertySource annotation referencing api.properties.
- 8:12
And you can see in each one of these, that down here I just used api.properties
- 8:16
now to make sure that this is relative to the class path.
- 8:21
I need to prepend this with class path colon just like that and
- 8:26
I can do that in each one of these class hath right from the search window,
- 8:32
course you could also go in to those files directly.
- 8:35
Let me just copy that
- 8:39
there also.
- 8:49
So all of those have been updated to include class path
- 8:53
in the path of the properties file.
- 8:56
So that wild fly doesn't give me an error when I try to deploy the application.
- 9:01
Excellent let me close this window.
- 9:04
Our second and the last task before creating a wire is to configure a great
- 9:07
I'll build file to use the war plot again.
- 9:09
So let me hop over to the build file and under the apply plugin spring boot
- 9:14
I'll say apply plugin war excellent.
- 9:19
Then we should set a couple properties for the grid wire task like this right here.
- 9:25
In fact, I'll just copy that and paste it right here.
- 9:28
Changing this from a jar to war.
- 9:31
Cool.
- 9:33
Okay, before we address the issue of the embedded web server.
- 9:36
I'm gonna to revert my code.
- 9:38
My dependencies here, so that it uses the default.
- 9:41
That is the included Web server in the Spring Boot start thymeleaf,
- 9:45
which is Tomcat.
- 9:46
So, I'm going to remove jetty as a dependency, and
- 9:51
I'm gonna remove that line of code that says exclude the Tomcat module.
- 9:56
So, if I were to run the boot run task we'd have Tomcat up and running again.
- 10:00
Okay. So now that we have Tomcat included by
- 10:03
default again, we want to make sure that Tomcat Servlet container doesn't conflict
- 10:06
with Wildfly's Servlet container because its Wildfly's Servlet container that would
- 10:10
be running our application.
- 10:11
So we'll need to mark Tomcat as a provided dependency at runtime.
- 10:16
In order to do that, I'll just stick that right here.
- 10:19
We use providedRuntime.
- 10:23
And then we just name that dependency ‘org.springframework.boot:spring-boot-
- 10:33
starter-tomcat’.
- 10:36
Excellent. So, this will make sure that when
- 10:39
our war file is built it will not include this imbedded web server here
- 10:43
because we are well we're deploying the war file to an actual web server.
- 10:48
We don't need the embedded one and even further,
- 10:50
it will conflict with wild flies server like container.
- 10:54
Okay, almost there.
- 10:56
One final task before building.
- 10:58
If we want to specify the context root of our application,
- 11:01
to be something other than the name of our archive.
- 11:03
That is, we want a URL that isn't, localhost:8080/whether-0.0.1-snapshot.
- 11:07
Well then we've got to add
- 11:11
a certain file to our application, that WildFly can detect.
- 11:16
And this file has to be named jboss-web.xml and
- 11:20
it's got to be located in a certain directory.
- 11:22
What directory is that?
- 11:24
Well it's under source/main and I'll create the other directories here.
- 11:28
/webapp/web-INF and then the file
- 11:32
there jboss-web.xml And
- 11:38
these directories will be created when I click OK yes I will add that to get and
- 11:43
here is our X.M.L. file so again source main web app web and and there's our file.
- 11:50
Now we' gonna need to create a couple X.M.L.
- 11:52
elements here the first one the top level one is J.
- 11:55
Boss web.
- 11:56
And then in order to specify the context root will use
- 12:00
an XML element named just that.
- 12:02
We want it to be the single slash will it will be the root of the Web Server and
- 12:07
that is all.
- 12:09
With that said let's build this thing.
- 12:11
So I'll open my terminal here.
- 12:13
All this up to give myself a little more space and I will do .slash gradlew or
- 12:19
gradlew.bat and if you wanna build here it'll run the unit tests and
- 12:24
then you'll get the war file as well.
- 12:26
If you want to skip unit tests you could use war.
- 12:29
In the last video you could have used ./gradlew
- 12:32
jar if you wanted to skip the unit tests.
- 12:34
So I'll just run the war here since I know my unit tests are already passing.
- 12:43
You should see the code compiling and
- 12:45
hopefully you'll have a successful build there.
- 12:47
So in the build directory now what you should see yes,
- 12:52
you should see the original jar and then you should see a war there as well.
- 12:57
Cool.
- 12:58
We're ready to deploy this to wild fly in our next video. | https://teamtreehouse.com/library/building-a-war-for-wildfly | CC-MAIN-2017-17 | refinedweb | 2,809 | 70.63 |
Your official information source from the .NET Web Development and Tools group at Microsoft.
We introduced CORS support in ASP.NET Web API a few months ago. Out of the box it supports configuring CORS policy by attributes. It is a very intuitive and powerful way but lacks flexibility at runtime. Imaging your service allows a 3rd party to consume your service. You need the capability of updating the allowing origins list without compiling and deploying your service each time the list changes.
In following this article, I show you two examples of dynamically managing your CORS policy.
Create a WebAPI project. It comes with a default ValuesController. Mark the controller with EnableCors attribute:
1: [EnableCors("*", "*", "*")]
2: public class ValuesController : ApiController
3: {
4: // GET api/values
5: public IEnumerable<string> Get()
6: {
7: return new string[] { "value1", "value2" };
8: }
9:
10: // GET api/values/5
11: public string Get(int id)
12: {
13: return "value";
14: }
15:
16: // POST api/values
17: public void Post([FromBody]string value)
18: {
19: }
20:
21: // PUT api/values/5
22: public void Put(int id, [FromBody]string value)
23: {
24: }
25:
26: [DisableCors]
27: // DELETE api/values/5
28: public void Delete(int id)
29: {
30: }
31: }
Add following line to the App_Start\WebApiConfig.cs file to enable CORS.
1: config.EnableCors();
Now your CORS service is set up.
The client code can’t stay in the same service as CORS service since it requires two services hosted at different origins so the CORS mechanism will kick in.
CORS is also affected by the choice of browsers[i]. So the tests need to be run in browser. Therefore I write the test in QUnit[ii].
Create an empty ASP.NET project. Adding following files:
1: <!DOCTYPE html>
2: <html xmlns="">
3: <head>
4: <title>CORS Test</title>
5: <link href="Content/bootstrap.css" rel="stylesheet" />
6: </head>
7: <body>
8: <div class="container">
9: <h1>CORS Test Client</h1>
10: <p>Input the url to the CORS service in following form.</p>
11: <form action="Test.html" method="get" class="form-inline">
12: <input type="text" name="url" class="input-xxlarge" />
13: <input type="submit" name="submit" class="btn"/>
14: </form>
15: </div>
16: </body>
17: </html>
5: <link href="Content/qunit.css" rel="stylesheet" />
8: <div id="qunit"></div>
9: <div id="qunit-fixture"></div>
10: <script src="Scripts/jquery-2.0.2.js"></script>
11: <script src="Scripts/qunit.js"></script>
12: <script src="Scripts/test.js"></script>
13: </body>
14: </html>
1: function getParameterByName(name) {
2: name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
3: var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
4: results = regex.exec(location.search);
5: return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
6: }
7:
8: test("Cross domain get request", function () {
9: var testUrl = getParameterByName("url");
10:
11: var xhr = new XMLHttpRequest();
12: xhr.open("GET", testUrl + "/api/Values", false);
13: xhr.send();
14:
15: var retval = JSON.parse(xhr.responseText);
16:
17: equal(2, retval.length);
18: equal("value1", retval[0]);
19: equal("value2", retval[1]);
20: });
Notes:
Now you have both CORS service and test client. Host them separately in IIS Express or Azure:
Visit the test client and input the CORS service URL:
The page will navigate to the test page once you submit the URL:
Notice the test passes since the CORS service accepts request from all origins.
The goal is to save the allowed origin list in database and make CORS components to visit the database at runtime. We will introduce a data model, CRUD views to manage the database and a new CORS attribute to mark your endpoints.
The advantage of using database is that it’s powerful. You can change the policy at runtime without restart the service. The downside is that database is sometime overkill especially when your service is too simple to add a database.
I used Entity Framework for the database. First, let’s create the simplest model:
1: public class AllowOrigin
2: {
3: public int Id { get; set; }
4:
5: public string Name { get; set; }
6:
7: public string Origin { get; set; }
8: }
Now, let’s use the powerful ASP.NET scaffolding to create controller and views for managing allowed origin list.
Let’s add a MVC 5 Controller with read/write actions and views, using Entity Framework.
Once views and controller are created let’s update the _Layout.cshtml file by adding a link to the navigation bar:
1: <div class="nav-collapse collapse">
2: <ul class="nav">
3: <li>@Html.ActionLink("Home", "Index", "Home", new { area = "" }, null)</li>
4: <li>@Html.ActionLink("API", "Index", "Help", new { area = "" }, null)</li>
5: <li>@Html.ActionLink("CORS Admin", "Index", "CorsAdminOrigin")</li>
6: </ul>
7: </div>
Now the CORS origin management page is ready to go:
We will take advantage of one CORS extension point to accomplish our goal:
Instances that implement this interface will create a CORS policy based on a given http request. A CORS policy is a rule deciding how the CORS engine will process the CORS request
1: namespace System.Web.Http.Cors
2: {
3: /// <summary>
4: /// Provides an abstraction for getting the <see cref="CorsPolicy"/>.
5: /// </summary>
6: public interface ICorsPolicyProvider
7: {
8: /// <summary>
9: /// Gets the <see cref="CorsPolicy"/>.
10: /// </summary>
11: /// <param name="request">The request.</param>
12: /// <param name="cancellationToken">The cancellation token.</param>
13: /// <returns>The <see cref="CorsPolicy"/>.</returns>
14: Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken);
15: }
16: }
Out of box EnableCorsAttribute implements ICorsPolicyProvider. It turns all of your settings in the CORS attribute to CORS policy.
We won’t use the EnableCors attribute. Instead we create a new attribute:
1: public class AllowCorsAttribute : Attribute, ICorsPolicyProvider
3: private string _configName;
5: public AllowCorsAttribute(string name = null)
6: {
7: _configName = name ?? "Default";
10: public string ConfigName
11: {
12: get { return _configName; }
13: }
15: public Task<CorsPolicy> GetCorsPolicyAsync(
16: HttpRequestMessage request,
17: CancellationToken cancellationToken)
18: {
19: using (var db = new CorsContext())
20: {
21: var origins = db.AllowOrigins.Where(o => o.Name == ConfigName).ToArray();
22:
23: var retval = new CorsPolicy();
24: retval.AllowAnyHeader = true;
25: retval.AllowAnyMethod = true;
26: retval.AllowAnyOrigin = false;
27:
28: foreach (var each in origins)
29: {
30: retval.Origins.Add(each.Origin);
31: }
32:
33: return Task.FromResult(retval);
34: }
35: }
36: }
AllowCors attribute derives from System.Attribute and implement ICorsPolicyProvider, therefore it will be picked up by AttributeBasedPolicyProviderFactory. However it accepts only one parameter for its name. The rest of the settings of the policy are read from the database.
In this sample, it only loads allowed origin from database. It is for the sake of simplicity. In a real scenario all settings can be saved in database.
Replace the EnableCors attribute with AllowCors attribute for ValuesController:
1: [AllowCors("Values")]
2: public class ValuesController : ApiController
3: {
Notice I gave a name “Values” for this scope.
Now open both test client and the CORS service (remember to redeploy your services) Run your test client you will notice that the tests failed:
The error reads:
SEC7120: Origin not found in Access-Control-Allow-Origin header.
Test.html
This is expected since test client is not on the allowed list.
So go to the CORS service and add test client to allowed list. Remember the name of the CORS policy to apply is “Values”.
Rerun your test client. Now it passes!
The goal of this sample is to show you how to manage CORS setting in web.config.
There are multiple benefits to use web.config. First, it doesn’t need recompile and fully redeployed. Second, it’s so simple that you just need a notepad to update the configuration. Last, if you’re using Azure web site, the portal allow you update the settings on the flight.
There a few downside of web.config. It requires service to be started to change the policy. And it doesn’t fit the situation you need configure endpoints differently.
1: <appSettings>
2: <add key="webpages:Version" value="3.0.0.0" />
3: <add key="webpages:Enabled" value="false" />
4: <add key="PreserveLoginUrl" value="true" />
5: <add key="ClientValidationEnabled" value="true" />
6: <add key="UnobtrusiveJavaScriptEnabled" value="true" />
7: <add key="cors:allowOrigins" value=""/>
This is quite straightforward if you have gone through the database sample first:
3: private const string keyCorsAllowOrigin = "cors:allowOrigins";
5: private CorsPolicy _policy;
7: public Task<CorsPolicy> GetCorsPolicyAsync(
8: HttpRequestMessage request,
9: CancellationToken cancellationToken)
10: {
11: if (_policy == null)
13: var retval = new CorsPolicy();
14: retval.AllowAnyHeader = true;
15: retval.AllowAnyMethod = true;
16: retval.AllowAnyOrigin = false;
17:
18: var value = ConfigurationManager.AppSettings[keyCorsAllowOrigin];
19:
20: if (!string.IsNullOrEmpty(value))
21: {
22: foreach (var one in from v in value.Split(';')
23: where !string.IsNullOrEmpty(v)
24: select v)
25: {
26: retval.Origins.Add(one);
27: }
28: }
29:
30: _policy = retval;
31: }
33: return Task.FromResult(_policy);
34: }
35: }
Note: You don’t need to reload policy for every request. Web.config doesn’t change during the life time of a service.
Put your client origin in the web.config and start the service. Run your test client. It just works.
Here’s a powerful integration sample if you’re using Azure Web Sites to host your service. In the Azure Web Site portal you can configure your application settings:
Now you can change the allow list in browser.
[i]
[ii]
Absolutely outstanding. Solves real time problem. Especially this one-"The advantage of using database is that it’s powerful. You can change the policy at runtime without restart the service."
will this new CORS features work in .net 4.0 running in win server 2003? | http://blogs.msdn.com/b/webdev/archive/2013/07/02/manage-cors-policy-dynamically.aspx | CC-MAIN-2014-52 | refinedweb | 1,594 | 50.53 |
# What is Reactive Programming? iOS Edition
There are many articles about Reactive Programming and different implementations on the internet. However, most of them are about practical usage, and only a few concern what Reactive Programming is, and how it actually works. In my opinion, it is more important to understand how frameworks work deep inside — spoiler: nothing actually complicated there — rather than starting to use a number of traits and operators meanwhile shooting yourself in the foot.
So, what is ~~RxSwift~~ ~~Combine~~ Reactive programming?
According to Wikipedia:
```
Reactive programming is a declarative programming paradigm concerned with data streams and the propagation of change. With this paradigm, it is possible to express static (e.g., arrays) or dynamic (e.g., event emitters) data streams with ease, and also communicate that an inferred dependency within the associated execution model exists, which facilitates the automatic propagation of the changed data flow.
```
Excuse me, WHAT?

Let's start from the beginning.
Reactive programming is an idea from the late 90s that inspired Erik Meijer, a computer scientist at Microsoft, to design and develop the Microsoft Rx library, but what is it exactly?
I don't want to provide one definition of what reactive programming is. I would use the same complicated description as Wikipedia. I think it's better to compare imperative and reactive approaches.
With an imperative approach, a developer can expect that the code instructions will be executed incrementally, one by one, one at a time, in order as you have written them.
The reactive approach is not just a way to handle asynchronous code; it's a way to stop thinking about threads, and start to think about sequences. It allows you to treat streams of asynchronous events with the same sort of simple, composable operations that you use for collections of data items like arrays. You think about how your system `reacts` to the new information. In simple words, our system is always ready to handle new information, and technically the order of the calls is not a concern.
I assume that most of the readers of this article came from iOS development. So let me make an analogy. Reactive programming is Notification center on steroids, but don't worry, a counterweight of the reactive frameworks is that they are more sequential and understandable. Moreover in iOS development, it's hard to do things in one way, because Apple gave us several different approaches like delegates, selectors, GCD and etc. The reactive paradigm could help solve these problems in one fashion.
It sounds quite simple. Let's take a look ar a couple of functions in one class implementation of one of the most popular frameworks `RxSwift`:
```
public final class BehaviorSubject {
public func value() throws -> Element {
self.\_lock.lock(); defer { self.\_lock.unlock() }
if self.\_isDisposed {
throw RxError.disposed(object: self)
}
if let error = self.\_stoppedEvent?.error {
throw error
}
else {
return self.\_element
}
}
func \_synchronized\_on(\_ event: Event) -> Observers {
self.\_lock.lock(); defer { self.\_lock.unlock() }
if self.\_stoppedEvent != nil || self.\_isDisposed {
return Observers()
}
switch event {
case .next(let element):
self.\_element = element
case .error, .completed:
self.\_stoppedEvent = event
}
return self.\_observers
}
}
```

This even partial example does not look easy at all… As we can see the implementation of `RxSwift` is not so simple. But let me explain myself. `RxSwift` is an advanced, highly optimized framework with wide functionality. To understand the principles of the reactive world, this framework doesn't fit. So, what are we going to do? We are going to write our own reactive solution from scratch. To do this, firstly we need to understand which parts this library consists of.
The tale of two friends
-----------------------
Let me answer again the question: What is reactive programming? Reactive programming is a friendship of two design patterns: `Iterator` and `Observer`. Let's have a quick reminder of how these patterns work.
`Iterator` is a behavioral design pattern that lets you traverse elements of a collection without exposing its underlying representation (list, stack, tree, etc.). You can read more at this [link](https://refactoring.guru/design-patterns/iterator).
`Observer` is a behavioral design pattern that lets you define a subscription mechanism to notify multiple objects about any events that happen to the object they’re observing. You can read more at this [link](https://refactoring.guru/design-patterns/observer).
How do these two friends work together? In simple terms, you use the `Observer` pattern to be subscribed for new events, and use the `Iterator` pattern to treat streams like sequences.
**Iterator**
Let's start from the beginning. From the `Iterator` pattern.
Here's a simple sequence of integers:
```
let sequence = [1, 2, 3, 4, 5]
```
And I want to iterate through it. Easy enough:
```
var iterator = sequence.makeIterator()
while let item = iterator.next() {
print(item)
}
// 1 2 3 4 5
```
However, I think that everybody would say this way of iteration via sequence is a little bit weird. Let's do this the proper way:
```
sequence.forEach { item in
print(item)
}
// 1 2 3 4 5
```
For now, it looks more natural, or at least I hope so. I used the `forEach` method on purpose. `forEach` has this signature `func forEach(_ body: (Element) -> Void)`. It's a function which takes a function(handler) as an argument and performs this handler over the sequence. Let's try to build `forEach` by ourselves.
```
extension Array {
func forEach(_ body: @escaping (Element) -> Void) {
for element in self {
body(element)
}
}
}
sequence.forEach {
print($0)
}
// 1 2 3 4 5
```
With `forEach` semantics it's possible to write this elegant code.
```
func handle(_ item: Int) {
print(item)
}
sequence.forEach(handle)
// 1 2 3 4 5
```
As I said before, that reactive programming is above all thread problems. Let's add to our custom `forEach` some thread abstraction.
```
extension Array {
func forEach(
on queue: DispatchQueue,
body: @escaping (Element) -> Void) {
for element in self {
queue.async { body(element) }
}
}
}
let queue = DispatchQueue(
label: "com.reactive",
qos: .background,
attributes: .concurrent
)
sequence.forEach(on: queue, body: handle)
// Output is unpredictable, but we'd see all 5 values.
```
**Observer**
I went so far and did some strange custom `forEach` for Array. What is this for? We'll know about this a little bit later, but now let's move to `Observer`.
There are many terms used to describe this model of asynchronous programming and design. This article will use the following terms: an `Observer` and `Observable`. An `Observer` subscribes to an `Observable`, and the `Observable` emits items or sends notifications to its observers by calling the observers’ methods.
In other words: `Observable` is a stream with data itself, and `Observer` is a consumer of this stream.
Let's start with the `Observer`. As I said, it's a consumer of a data stream, which can do something around this data. Let me translate, it's a class with a function inside, which calls when new data arrives. Let’s implement this class.:
```
class Observer {
private let on: (Element) -> Void
init(\_ on: @escaping (Element) -> Void) {
self.on = on
}
func on(\_ event: Element) {
on(event)
}
}
```
And now let’s move to `Observable`. `Observable` it's data itself. Let's make it simple for the first iteration.
```
class Observable {
var value: Element
init(value: Element) {
self.value = value
}
}
```
The most interesting part is that `Observable` should allow to `subscribe` to a consumer of this data. And via changing this data in `Observable`, `Observer` needs to know about these changes.
```
class Observable {
private var observers: [Observer] = []
var value: Element {
didSet {
observers.forEach { $0.on(self.value) }
}
}
init(value: Element) {
self.value = value
}
func subscribe(on observer: Observer) {
observers.append(observer)
}
}
```
Actually we just build our `Observer` pattern. So, let's try this out.
```
let observer = Observer {
print($0)
}
let observable = Observable(value: 0)
observable.subscribe(on: observer)
for i in 1...5 {
observable.value = i
}
// 1, 2, 3, 4, 5
```
And it works! But hold on for a second — let's add some modifications before we go further.
Maybe you've already mentioned that our `Observable` stores all input `Observers` via subscription, which is not so great. Let's make this dependency `weak`. However, Swift doesn't support weak arrays for now and maybe forever, that's why we need to handle this situation otherwise. Let's implement the class wrapper with a weak reference in it.
```
class WeakRef where T: AnyObject {
private(set) weak var value: T?
init(value: T?) {
self.value = value
}
}
```
As a result, you can see a generic object, which could hold other objects weakly. Now let's make some improvements to `Observable`.
```
class Observable {
private typealias WeakObserver = WeakRef>
private var observers: [WeakObserver] = []
var value: Element {
didSet {
observers.forEach { $0.value?.on(self.value) }
}
}
init(value: Element) {
self.value = value
}
func subscribe(on observer: Observer) {
observers.append(.init(value: observer))
}
}
```
For now `Observer`s not held by `Observable`. Let's try this out and create two observers.
```
let observer1 = Observer {
print("first: ", $0)
}
var observer2: Observer! = Observer {
print("second: ", $0)
}
let observable = Observable(value: 0)
observable.subscribe(on: observer1)
observable.subscribe(on: observer2)
for i in 1...5 {
observable.value = i
if i == 2 {
observer2 = nil
}
}
/\*
first: 1
second: 1
first: 2
second: 2
first: 3
first: 4
first: 5
\*/
```
As you can see, the second `Observer` was destroyed after `2`, which proves the workability of the code. However, I think creating an `Observer` object by hand all the time could be annoying, so let's improve `Observable` to consume a closure, not an object.
```
class Observable {
private typealias WeakObserver = WeakRef>
private var observers: [WeakObserver] = []
var value: Element {
didSet {
observers.forEach { $0.value?.on(self.value) }
}
}
init(value: Element) {
self.value = value
}
func subscribe(onNext: @escaping (Element) -> Void) -> Observer {
let observer = Observer(onNext)
observers.append(.init(value: observer))
return observer
}
}
let observable = Observable(value: 0)
let observer = observable.subscribe {
print($0)
}
for i in 1...5 {
observable.value = i
}
// 1, 2, 3, 4, 5
```
For my taste usage is more clear now, however it's possible to use both `subscribe` functions.
For now, our tiny reactive framework looks finished, but not exactly. Let's do some asynchronous stress tests for the `Observable`.
```
let observable = Observable(value: 0)
let observer = observable.subscribe {
print($0)
}
for i in 1...5 {
DispatchQueue(label: "1", qos: .background, attributes: .concurrent).asyncAfter(deadline: .now() + 0.3) {
observable.value = i
}
}
for i in 6...9 {
DispatchQueue(label: "2", qos: .background, attributes: .concurrent).asyncAfter(deadline: .now() + 0.3) {
observable.value = i
}
}
```
In this case, we should receive numbers from 1 to 9 in random order, because changes run in the different asynchronous queues. For my case, it was like this
```
/*
3
4
4
4
5
6
7
8
9
*/
```
As you can see, it's not the expected result. A race condition happened and it should be fixed. The solution is easy — let's add some thread synchronization. There are several ways to achieve this, but I'll use a method with a dispatch barrier. Here's the solution.
```
class Observable {
private typealias WeakObserver = WeakRef>
private var observers: [WeakObserver] = []
private let isolationQueue = DispatchQueue(label: "", attributes: .concurrent)
private var \_value: Element
var value: Element {
get {
isolationQueue.sync { \_value }
}
set {
isolationQueue.async(flags: .barrier) {
self.\_value = newValue
self.observers.forEach { $0.value?.on(newValue) }
}
}
}
init(value: Element) {
self.\_value = value
}
func subscribe(onNext: @escaping (Element) -> Void) -> Observer {
let observer = Observer(onNext)
observers.append(.init(value: observer))
return observer
}
}
```
The same test as before gave me this result:
```
/*
1
2
3
4
5
6
7
8
9
*/
```
This time it's even in the right order, but be aware that it's not guaranteed. Now our reactive framework has thread synchronization.
Let's move further and there's another difference between a vanilla `Observer` pattern and most of the reactive frameworks. Usually, as an `Element` from `Observable`, you manipulate not just an `Element`, but some kind of `Event` enumeration, which looks like this.
```
enum Event {
case next(Element)
case completed
case error(Error)
}
```
It’s a handy solution, because you can handle situations when your sequence completed or received an error. I don't want to spend time adopting this practice right now, I think it doesn't matter for concept understanding.
**Let's compose `Observer` and `Iterator`**
One of the killer features for reactive programming is the possibility to treat your `Observable` `sequence` as a `Sequence` I think everybody knows these handy functions like `map`, `flatMap`, `reduce`, and so on. As an example, let's try to add to our `Observable` the `map` function. But firstly let's remember how it works with a simple array.
```
let sequence = [1, 2, 3, 4, 5]
let newSequence = sequence
.map { element in
return element + 1
}
// newSequence: 2, 3, 4, 5, 6
```
This case is a primitive adding 1 to every element. Can we do the same with an `Observable`? Sure we can. Let's add a `map` function to our `Observable`.
```
class Observable {
typealias WeakObserver = WeakRef>
private var observers: [WeakObserver] = []
private let isolationQueue = DispatchQueue(label: "", attributes: .concurrent)
private var \_value: Element
var value: Element {
get {
isolationQueue.sync { \_value }
}
set {
isolationQueue.async(flags: .barrier) {
self.\_value = newValue
self.observers.forEach { $0.value?.on(newValue) }
}
}
}
private var transform: ((Element) -> Element)?
init(value: Element) {
self.\_value = value
}
func subscribe(onNext: @escaping (Element) -> Void) -> Observer {
let transform = self.transform ?? { $0 }
let observer = Observer { element in
onNext(transform(element))
}
observers.append(.init(value: observer))
return observer
}
func map(\_ transform: @escaping (Element) -> Element) -> Observable {
self.transform = transform
return self
}
}
let observable = Observable(value: 0)
let observer = observable
.map { $0 + 1 }
.subscribe { print($0) }
for i in 1...5 {
observable.value = i
}
// 2, 3, 4, 5, 6
```
Yeah, you can mention that I've cheated a little bit.

True `map` function would have structure with a generic like this:
```
func map(\_ transform: @escaping (Element) -> T) -> Observable
```
However, for the sake of simplicity in this article I just added this:
```
func map(_ transform: @escaping (Element) -> Element) -> Observable
```
I hope you could forgive me and understand the point.
Actually, we're done for now with our own reactive framework, congratulations to everybody who followed until the end. It's super simplified but it works. Gist with the last iteration of this article you can find [here](https://gist.github.com/Atimca/51c83f4c9161fc36bed340b02e605d09).
I hope at least for now, reactive programming doesn’t look scary anymore. However, I hear all the time from people, that reactive way could lead us t an enormous number of sequences flying around the project and it's very easy to shoot yourself in the foot with this approach. I won't fight against this, and you can easily Google a bad style of doing reactive. I don't want to leave you with a cliffhanger, but I hope to show you a way, how to treat a reactive approach in the next chapters.
Where to go after
-----------------
* <http://reactivex.io>
* <https://github.com/ReactiveX/RxSwift>
* <https://refactoring.guru/> | https://habr.com/ru/post/497300/ | null | null | 2,512 | 50.53 |
A plugin for Flutter that supports loading and displaying banner, interstitial (full-screen), and rewarded video ads using the Firebase AdMob API.
Note: This plugin is in beta, and may still have a few issues and missing APIs. Feedback and Pull Requests are welcome..
Admob 7.42.0 requires the App ID to be included in
Info.plist. Failure to do so will result in a crash on launch of your app. The lines should look like:
<key>GADApplicationIdentifier</key> <string>[ADMOB_APP_ID]</string>
where
[ADMOB_APP_ID] is your App ID. You must pass the same value when you initialize the plugin in your Dart code.
See for more information about configuring
Info.plist and setting up your App ID.
The AdMob plugin must be initialized with an AdMob App ID.
FirebaseAdMob.instance.initialize(appId: appId);.
Starting in version 7.42.0, you are required to add your AdMob app ID in your Info.plist file under the Runner directory. You can add it using Xcode or edit the file manually:
<dict> <key>GADApplicationIdentifier</key> <string>ca-app-pub-################~##########</string> </dict>
Failure to add this tag will result in the app crashing at app launch with a message including "GADVerifyApplicationID.".
This is just an initial version of the plugin. There are still some limitations:
For Flutter plugins for other Firebase products, see FlutterFire.md.
firebase_admob v0.9.0
example/README.md
Demonstrates how to use the firebase_admob plugin.
For help getting started with Flutter, view our online documentation.
Add this to your package's pubspec.yaml file:
dependencies: lazy_ads: ^0.0.2
You can install packages from the command line:
with Flutter:
$ flutter pub get
Alternatively, your editor might support
flutter pub get.
Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:lazy_ads/lazy_ads).
Package is pre-v0.1 release. (-10 points)
While nothing is inherently wrong with versions of
0.0.*, it might mean that the author is still experimenting with the general direction of the API.
The package description is too short. (-4 points)
Add more detail to the
description field of
pubspec.yaml. Use 60 to 180 characters to describe the package, what it does, and its target use case. | https://pub.dev/packages/lazy_ads | CC-MAIN-2019-35 | refinedweb | 371 | 59.7 |
I recently joined a Kaggle competition on multilabel text classification and have learned a ton from basic code that one of the competitors shared in the forums.
The code of the genereous competitor does logistic regression classification for multiple classes with stochastic gradient ascent. It is further well-suited for online learning as it uses the hashing trick to one-hot encode boolean, string, and categorial features.
To better understand these methods and tricks I here apply some of them to a multilabel problem I chose mostly for the easy access to a constant stream of training data:
All recent changes on Wikipedia are tracked on this special page where we can see a number of interesting features such as the length of the change, the contributor's username, the title of the changed article, and the contributor's comment for a given change.
Using the Wikipedia API to look at this stream of changes we can also see how contributors classify their changes as bot, minor, and new. Multiple label assignments are possible, so that one contribution may be classified as both bot and new.
Here I will listen to this stream of changes, extract four features (length of change, comment string, username, and article title), and train three logistic regression classifiers (one for each class) to predict the likelihood of a change belonging to each one of them. The training is done with the stochastic gradient ascent method.
One caveat: I am a complete novice when it comes to most of this stuff so please take everything that follows with a grain of salt - on the same note I would be forever grateful for any feedback especially of the critical kind so that I can learn and improve.
%matplotlib inline import matplotlib from matplotlib import pyplot as pt import requests import json from math import log, exp, sqrt from datetime import datetime, timedelta import itertools from collections import defaultdict
URL = ('' '%7Ctimestamp%7Ctitle%7Cflags%7Cids%7Csizes%7Cflags%7Cuser&rclimit=100')
The logistic regression classifier requires us to compute the dot product between a feature vector $\mathbf{x}$ and a weight vector $\mathbf{w}$.
$$\mathbf{w}^\text{T} \mathbf{x} = w_0 x_0 + w_1 x_1 + w_2 x_2 + \ldots + w_N x_N.$$
As by convention, the bias of the model is encoded with feature $x_0 = 1$ for all observations - the only thing that will change about the $w_0 x_0$-term is weight $w_0$ upon training. The length of the article change is tracked with numerical feature $x_1$ which equals the number of character changes (hence $x_1$ is either positive or negative for text addition and removal respectively).
As in the Kaggle code that our code is mostly based upon, string features are one-hot encoded using the hashing trick:
The string features extracted for each observed article change are username, a parse of the comment, and the title of article. Since this is an online learning problem there is no way of knowing how many unique usernames, comment strings, and article titles are going to be observed.
With the hashing trick we decide ab initio that
D_sparse-many unique values across these three features are sufficient to care about:
Our one-hot encoded feature space has dimension
D_sparse and can be represented as a
D_sparse-dimensional vector filled
with
0's and
1's (feature not present / present respectively).
The hash in hashing trick comes from the fact that we use a hash function to convert strings to integers.
Suppose now that we chose
D_sparse = 3 and our hash function produces
hash("georg") = 0,
hash("georgwalther") = 2, and
hash("walther") = 3 for three observed usernames.
For username
georg we get feature vector $[1, 0, 0]$ and for username
georgwalther we get $[0, 0, 1]$.
The hash function maps username
walther outside our 3-dimensional feature space and to close this loop we not only
use the
hash function but also the
modulus (which defines an equivalence relation?):
hash("georg") % D_sparse = 0,
hash("georgwalther") % D_sparse = 2, and
hash("walther") % D_sparse = 0
This illustrates one downside of using the hashing trick since we will now map usernames
georg and
walther to the same feature vector $[1, 0, 0]$.
We are therefore best adviced to choose a big
D_sparse to avoid mapping different feature values to the same one-hot-encoded feature - but probably not too big to preserve memory.
For each article change observation we only map three string features into this
D_sparse-dimensional one-hot-encoded feature space - out of
D_sparse-many vector elements there will only ever be three ones among (
D_sparse-3) zeros (if we do not map to the same vector index multiple times).
We will therefore use sparse encoding for these feature vectors (hence the
sparse in
D_sparse).
We will also normalize the length of change on the fly using an online algorithm for mean and variance estimation.
D = 2 # number of non-sparse features D_sparse = 2**18 # number of sparsely-encoded features
def get_length_statistics(length, n, mean, M2): """ """ n += 1 delta = length-mean mean += float(delta)/n M2 += delta*(length - mean) if n < 2: return mean, 0., M2 variance = float(M2)/(n - 1) std = sqrt(variance) return mean, std, M2 def get_data(): X = [1., 0.] # bias term, length of edit X_sparse = [0, 0, 0] # hash of comment, hash of username, hash of title Y = [0, 0, 0] # bot, minor, new length_n = 0 length_mean = 0. length_M2 = 0. while True: r = requests.get(URL) r_json = json.loads(r.text)['query']['recentchanges'] for el in r_json: length = abs(el['newlen'] - el['oldlen']) length_n += 1 length_mean, length_std, length_M2 = get_length_statistics(length, length_n, length_mean, length_M2) X[1] = (length - length_mean)/length_std if length_std > 0. else length X_sparse[0] = abs(hash('comment_' + el['parsedcomment'])) % D_sparse X_sparse[1] = abs(hash('username_' + el['user'])) % D_sparse X_sparse[2] = abs(hash('title_' + el['title'])) % D_sparse Y[0] = 0 if el.get('bot') is None else 1 Y[1] = 0 if el.get('minor') is None else 1 Y[2] = 0 if el.get('new') is None else 1 yield Y, X, X_sparse
def predict(w, w_sparse, x, x_sparse): """ P(y = 1 | (x, x_sparse), (w, w_sparse)) """ wTx = 0. for i, val in enumerate(x): wTx += w[i] * val for i in x_sparse: wTx += w_sparse[i] # *1 if i in x_sparse try: wTx = min(max(wTx, -100.), 100.) res = 1./(1. + exp(-wTx)) except OverflowError: print wTx raise return res
def update(alpha, w, w_sparse, x, x_sparse, p, y): for i, val in enumerate(x): w[i] += (y - p) * alpha * val for i in x_sparse: w_sparse[i] += (y - p) * alpha # * feature[i] but feature[i] == 1 if i in x
K = 3 w = [[0.] * D for k in range(K)] w_sparse = [[0.] * D_sparse for k in range(K)] predictions = [0.] * K alpha = .1
time0 = datetime.now() training_time = timedelta(minutes=10) ctr = 0 for y, x, x_sparse in get_data(): for k in range(K): p = predict(w[k], w_sparse[k], x, x_sparse) predictions[k] = float(p) update(alpha, w[k], w_sparse[k], x, x_sparse, p, y[k]) ctr += 1 # if ctr % 10000 == 0: # print 'samples seen', ctr # print 'sample', y # print 'predicted', predictions # print '' if (datetime.now() - time0) > training_time: break
ctr
As we can see, we crunched through 106,401 article changes during our ten-minute online training.
It would be fairly hard to understand the link between the
D_sparse-dimensional one-hot-encoded feature space and
the observed / predicted classes.
However we can still look at the influence that the length of the article change has on our classification problem
print w[0] print w[1] print w[2]
Here we can see that the weight of the length of change for class
0 (bot) is
-1.12, for class
1 (minor) is
-0.97, and for class
2 (new) is
2.11.
Intuitively this makes sense since many added characters (big positive change) should make classification as a minor change less likely and classification as a new article more likely: For an observed positive character count change $C$, $2.11 C$ will place us further to the right, and $-0.97 C$ further to the left along the $x$-axis of the sigmoid function:
(from)
Further below we will see that the vast majority of bot changes are classified as minor changes hence we would expect to see correlation between the weights of this feature for these two classes.
To further evaluate our three classifiers, we observe another 10,000 Wikipedia changes and construct a confusion matrix.
no_test = 10000 test_ctr = 0 classes = {c: c_i for c_i, c in enumerate(list(itertools.product([0, 1], repeat=3)))} confusion_matrix = [[0 for j in range(len(classes))] for i in range(len(classes))] predicted = [0, 0, 0] for y, x, x_sparse in get_data(): for k in range(K): p = predict(w[k], w_sparse[k], x, x_sparse) predicted[k] = 1 if p > .5 else 0 i = classes[tuple(y)] j = classes[tuple(predicted)] confusion_matrix[i][j] += 1 test_ctr +=1 if test_ctr >= no_test: break
matplotlib.rcParams['font.size'] = 15 fig = pt.figure(figsize=(11, 11)) pt.clf() ax = fig.add_subplot(111) ax.set_aspect(1) res = ax.imshow(confusion_matrix, cmap=pt.cm.jet, interpolation='nearest') cb = fig.colorbar(res) labels = [{v: k for k, v in classes.iteritems()}[i] for i in range(len(classes))] pt.xticks(range(len(classes)), labels) pt.yticks(range(len(classes)), labels) pt.show()
The confusion matrix shows actual classes along the vertical and predicted classes along the horizontal axis.
The vast majority of observed classes are $(0, 0, 0)$ and our classifiers get most of these right except that some are misclassified as $(0, 0, 1)$ and $(0, 1, 0)$.
All observed bot-related changes (classes starting with a $1$) are $(1, 1, 0)$ (i.e. minor bot-effected changes) and our classifiers get all of those right. | https://nbviewer.jupyter.org/github/waltherg/notebooks/blob/master/2014-10-10-Classifying_Wikipedia_Changes.ipynb | CC-MAIN-2018-13 | refinedweb | 1,626 | 57.81 |
Opened 3 years ago
Closed 2 years ago
#7753 closed bug (fixed)
Profiling report broken with foreign exported functions
Description
Save the following Haskell source as wrapper.hs:
import Foreign.Ptr import Control.Monad main = do fptr <- wrap wrapped replicateM 100 $ (return$!) =<< dyn fptr 4 wrapped :: Double -> IO Double wrapped x = return $ f 10000 x f :: Int -> Double -> Double f 0 u = u f n u = (u / fromIntegral n) * f (n-1) u foreign import ccall "wrapper" wrap :: (Double -> IO Double) -> IO (FunPtr (Double -> IO Double)) foreign import ccall "dynamic" dyn :: FunPtr (Double -> IO Double) -> Double -> IO Double
Then compile and run it with:
$ ghc -O2 wrapper.hs -fprof-auto -prof $ ./wrapper +RTS -p
It generates wrapper.prof (attached). The file contains the following lines:
CAF GHC.IO.Encoding.Iconv 58 0 0.0 0.2 0.0 0.2 wrapped Main 80 100 0.0 1.1 0.0 0.0 f Main 81 1000100 100.0 0.0 0.0 0.0
I see two problems here, (1) the inherited column is 0 for 'wrapped' and 'f' but this is incorrect, and (2) 'wrapped' and 'f' belongs to the wrong cost center, 'GHC.IO.Encoding.Iconv'.
Attachments (2)
Change History (8)
Changed 3 years ago by akio
comment:1 Changed 2 years ago by igloo
- difficulty set to Unknown
- Milestone set to 7.8.1
comment:2 Changed 2 years ago by akio
I think I know what is happening. The wrapper and f cost centres are actually placed under SYSTEM. I can see it by using +RTS -pa instead of +RTS -p. However SYSTEM is a hidden cost centre, so by default it's not included in the report, resulting in a confusing call tree.
Changed 2 years ago by akio
use CCS_MAIN in rts_apply
comment:3 Changed 2 years ago by akio
- Status changed from new to patch
I'm not sure if this is the best way to fix it, but the attached patch improves the output; now wrapper and f are placed directly under MAIN, and they get inherited costs correctly.
comment:4 Changed 2 years ago by Austin Seipp <austin@…>
comment:5 Changed 2 years ago by thoughtpolice
Merged, thank you Takano!
comment:6 Changed 2 years ago by thoughtpolice
- Resolution set to fixed
- Status changed from patch to closed
Merged, thanks!
thanks for the report | https://ghc.haskell.org/trac/ghc/ticket/7753 | CC-MAIN-2015-40 | refinedweb | 393 | 71.14 |
#include <stdio.h> int rename(const char *old, const char *new); int renameat(int oldfd, const char *old, int newfd, const char *new);.
Upon successful completion, the renameat() function shall return 0. Otherwise, it shall return -1 and set errno to indicate the error.
In addition, the renameat() function shall fail if:
The rename() and renameat() functions may fail if:
The following sections are informative.
The following example shows how to rename a file named /home/cnd/mod1 to /home/cnd/mod2.
#include <stdio.h> int status; ... status = rename("/home/cnd/mod1", "/home/cnd/mod2");");.
The Base Definitions volume of POSIX.1-2008, Section 4.2, Directory Protection, <stdio.h>
Any typographical or formatting errors that appear in this page are most likely to have been introduced during the conversion of the source files to man page format. To report such errors, see . | https://man.linuxreviews.org/man3p/rename.3p.html | CC-MAIN-2020-40 | refinedweb | 143 | 52.36 |
Travis CI Tutorial: Getting Started
Automate tests with Travis CI
You’ve got 99 problems, and testing is one of ’em!
Developers know that testing an application thoroughly is necessary to catch problems before they affect users. Forgetting to test can result in complications like annoyed clients, ranting one-star reviews in the App Store, and bruises from smacking yourself in the head for letting simple mistakes slip through the net.
But remembering to run tests before each commit or merge can be tough if you have to do it manually. What’s a time-crunched developer to do?
Continuous Integration
Thankfully, Continuous Integration can save the day. Continuous Integration, often abbreviated to just CI, is the process of automatically building and running tests whenever a change is committed.
Now, Apple has their own solution for this with Xcode Bots, which are designed to run on OS X Server. But the downside of Apple’s solution is that you, yes you have to manage the entire process. You have to set up and maintain OS X Server and Xcode versions on the server, figure out access control for viewing results, and handle provisioning and signing issues. Sounds like a lot of work, right? You don’t have time for this; you have code to write, apps to design, and happy hour to get to – that beer isn’t going to drink itself.
Shout it to the cosmos with me: there must be an easier way!
Travis CI
Luckily, the cosmos heard us, and responded with Travis CI.
What is Travis CI?
Usually simply called Travis, it’s a Continuous Integration service that is free for open-source projects and has a monthly fee for closed-source projects based on how many simultaneous builds you want to run.
What does it do?
Travis sets up “hooks” with GitHub to automatically run tests at specified times. By default, these are set up to run after a pull request is created or when code is pushed up to GitHub.
In this Travis CI tutorial, you’ll use a public GitHub repo and the free version of Travis to set up tests that run every time you try to merge new changes into that repo.
- You already have a GitHub account. If you don’t, sign up for a free one here.
- Git is installed on your system. You can check this by opening up Terminal and typing which git. If there’s a result – typically /usr/bin/git – then you’re good to go. If not, you can download an installer from the Git website here.
Getting Started
Let’s do this! Download the starter project, then open up the zip file and put the resulting MovingHelper folder on your Desktop so you can find it easily. MovingHelper is a to-do list app which, as you might suspect from the name, helps manage tasks related to moving.
Build and run your project in Xcode; you’ll see the following:
Use the picker to choose a date a little less than a month from the current date, then tap the Create Tasks button. You’ll see the following:
The app has created a list of tasks. The red sections are past-due tasks, while the green sections are upcoming tasks.
Looking through the code, you’ll see that a few tests have been set up. Execute the tests by using the Command-U shortcut, and they will quickly run and pass:
So far so good, right? Now that you know the tests are passing, you’re ready to get GitHub and Travis set up to run them automatically.
Setting Up Git and GitHub
First, you’ll create a local Git repo with the files in the starter project. Fire up Terminal, then change the directory to your desktop folder:
cd ~/Desktop/MovingHelper
Next, initialize a local repository on your computer:
git init
Next, add everything in the MovingHelper folder – since you’re already in it, just type:
git add --all
Finally, commit all the code:
git commit -m "Starter project from raywenderlich.com"
Now that everything is committed locally, it’s time to create a public repository on GitHub. This is what Travis will watch for changes.
Head over to github.com and make sure you’re logged in to your account. In the top right corner of the page, there’s a plus sign with a little down arrow next to it – click it and select New repository:
You will see a page to set up the new repository:
The owner will be you. Name the repo MovingHelper, give it a brief description, make sure it’s public, and don’t add a README, license, or .gitignore as these are all included in the sample project. Next, click the big green Create repository button. You’ll see a page explaining how to get your code to GitHub.
Leave this page open in a tab of your browser – you’ll want to come back to it shortly.
Set Up Travis
Open a new tab in your browser and go to travis-ci.org to get started using the free version of Travis. In the upper right corner is a button which allows you to sign in using your GitHub account:
Use this button to sign up for Travis. Since you’re already signed in to GitHub, you should not need to sign in again. If you haven’t already signed up for Travis, you’ll need to agree to the permissions they request:
Travis needs access to read and write webhooks, services, and commit statuses. That way that it can create the automated “hooks” it needs to automatically run when you want it to.
Click the green Authorize Application button. GitHub will ask you to verify your password:
Enter your password and click Confirm password. Now you’re on the Travis “getting-started” page.
Your avatar and GitHub username are in the upper right hand corner:
Click that to be taken to your Travis profile page. You’ll see an alphabetical list of all your public repos. If you haven’t set up Travis previously, they should all be unchecked.
Scroll down to MovingHelper:
Flick the switch to turn it on:
There! Travis is now watching for changes to your MovingHelper repository.
Pushing to GitHub
Go back to the tab with your newly created GitHub repo. Copy the commands from the “…or push an existing repository from the command line” section:
Copy the text from that section either manually or by clicking the clipboard icon on the right, then paste it into Terminal and press enter. This adds your new GitHub repo as a remote and pushes everything up to it.
Since Travis is now watching this repo, it will notice this push and put a build in the line of all the other open source builds waiting to be run.
Whenever your tests run, you’ll get an email that contains something like this:
Ruh roh! What happened? Click on the big Build #1 Failed to be taken to the results of the failed build:
That warning at the bottom contains one specific line that explains why the build failed:
Could not find .travis.yml, using standard configuration.
What does that mean? Well, .travis.yml file uses YAML to tell Travis how to set up a build. Since Travis works with many different languages, it doesn’t know how to build your specific project without some information about what kind of project it is.
To get a quick look at some of Travis’ best features requiring very little configuration, check out a new branch from the command line by typing the following into Terminal:
git checkout -b travis-setup
Terminal will confirm that you created and checked out a new branch:
Switched to a new branch 'travis-setup'
Next, open your plain-text editor of choice. TextWrangler is particularly helpful here because it highlights the syntax of YAML files automatically, but any plain-text editor will work.
Create a new document and save it in the root of your repo as .travis.yml.
Add the following five lines to your new .travis.yml file:
language: objective-c #1 osx_image: xcode6.4 #2 xcode_project: MovingHelper.xcodeproj #3 xcode_scheme: MovingHelper #4 xcode_sdk: iphonesimulator8.4 #5
Note that YAML will disregard anything prefixed with a # as a comment. Here’s what you’re telling Travis to do with each line:
- Build a project using … Objective-C!? Don’t panic! Even though your project is in Swift, Travis only uses the
objective-cvalue to know to build with Xcode command line tools. Since Xcode knows how to tell what’s in Swift and what’s in Objective-C, your Swift project will be just fine. :]
- Use the Xcode 6.4 tools to create the build, since you’re using Swift 1.2. This presently requires specifying which VM image you want to use – in this case
xcode6.4.
- Use the specified Xcode project file. Note that if you have a project you want to build using an .xcworkspace (for example, a project using CocoaPods), you can replace the xcode_project parameter with
xcode_workspaceand use your .xcworkspace file as the value instead of your .xcodeproj.
- Use the specified scheme to decide what tests to run. Since your default scheme is called MovingHelper, Travis should use that scheme.
- Run the tests on an iPhone simulator, because doing so does not require setting up code signing (which is not covered in this tutorial).
Make sure your .travis.yml file is saved, then add and commit it to Git:
git add .travis.yml git commit -m "Added .travis.yml file"
Next, push your branch up to your remote:
git push -u origin travis-setup
Reload the webpage for your MovingHelper GitHub repo. You should see something like this, indicating that the branch has made it up to GitHub:
Click the green Compare & pull request button.
Change the title of the pull request to Travis Setup:
Click the green Create pull request button, and Travis will automatically start working. As soon as your build completes, you’ll see something like this on your GitHub page:
Argh! You’ve added the .travis.yml file like you were supposed to, so why isn’t it working?
Click one of the Details links to see the results of this build. A new error leads you directly to the problem:
D’oh! Travis knows the name of the scheme, but because it was automatically created and isn’t shared in your GitHub repository, Travis can’t see it. Fix that by going back to Xcode, and from the scheme drop-down, selecting Edit Scheme…
When the scheme editor comes up, check the Shared checkbox at the bottom of the panel:
Click the Close button, then add and commit all shared data (which will include the new shared scheme):
git add MovingHelper.xcodeproj/xcshareddata git commit -m "Added shared scheme"
Push up to GitHub again:
git push -u origin travis-setup
Since you already have an open pull request, Travis will immediately know that you added changes and start building again:
Once the build completes, you should see what you’ve been waiting for: green!
All is well indeed. Click on Show all checks and the dialog will expand, showing you the builds which passed:
Click on either Details link, and you’ll be taken to Travis’ output. You can scroll through and see the details of how your project was built and how your tests ran, but the bottom line – and the good news – is all the way at the end:
Each item with a green checkmark next to it is a passing test – and as you can see with the happy green text at the end, all of the tests are passing! Woohoo!
Go back to your GitHub page and click the green Merge pull request button, then click Confirm merge to officially merge your changes.
Hello, World!
Now that your tests are running automatically, it’s time to tell other people that your tests are passing by adding a badge to your README which shows the current status of the build on Travis.
Before you go too far, make sure you’re up to date with everything in your master branch:
git checkout master git pull origin master
Switch back to your travis-setup branch and merge the changes from master into it:
git checkout travis-setup git merge master
Now that the merge commit has been merged back into your travis-setup branch, open up the README.md file from the root folder of your project in your markdown or plain-text editor of choice.
Add the following lines to the end of the file:
####Master branch build status: Don’t forget to replace
[your-username] with your actual GitHub username.
You’ve just added a link to a graphic which will be a “passing” or “failing” badge served up by Travis based on the status of your build for the branch specified in the
branch URL query parameter.
Save the changes to the README, then add, commit, and push them up:
git add . git commit -m "Add Travis badge to README" git push origin travis-setup
Go back to the GitHub page. Follow the same steps as before to create a new pull request. Name this new pull request Badges, and click Create pull request.
Travis will once again do its business – and since you didn’t change any of the code, the tests will continue to pass:
Again, click the Merge pull request and then Confirm merge buttons to merge your changes. Once merged, you’ll see your badge right on your main MovingHelper GitHub page:
Breaking the Build
Now that you’ve gotten a couple of passing pull requests without changing any code, it’s time to take things to the next level: breaking the build. :]
Start by bringing your master branch up to date with the latest changes you just merged in:
git checkout master git pull origin master
To see the problem you want to fix, build and run the application, and check off one of the boxes. Build and run again. The box is no longer checked. Oops!
When you get a report of a bug from a tester or a user, it’s a good idea to write a test that illustrates the bug and shows when it is fixed. That way, when the tests are run you can be confident that the bug hasn’t magically reappeared – commonly known as a regression.
Let’s make sure that when you mark a task done in the list, the app remembers. Create a new branch for this work and name it to-done:
git checkout -b to-done
Open up Xcode and go to the TaskTableViewCell.swift file. You can see in
tappedCheckbox() that there’s a
TODO comment instead of the actual code to mark a task as done. For the cell to communicate the task state change, it will need a reference to the task and a delegate to communicate the change to. Add variables for these two items below the outlets:
var currentTask: Task? public var delegate: TaskUpdatedDelegate?
Since cells are reused, clear the values of these variables before the cell is reused by overriding
prepareForReuse() and resetting each value to
nil:
public override func prepareForReuse() { super.prepareForReuse() currentTask = nil delegate = nil }
Add a line to the top of
configureForTask(_:) to store the current task:
currentTask = task
Replace the
TODO in
tappedCheckbox() with code to mark the task as done and notify the delegate of the change:
if let task = currentTask { task.done = checkbox.isChecked delegate?.taskUpdated(task) }
Finally, go to MasterViewController.swift, and in
tableView(_:cellForRowAtIndexPath:), add a line just above where the cell is returned, setting the
MasterViewController as the delegate of the cell:
cell.delegate = self
Build and run. Check off an item, then stop the app. Build and run again. Hooray, the item is still checked off!
Commit your changes:
git add . git commit -m "Actually saving done state"
Automation
Now that you have fixed the bug, it’s time to write a test which Travis can run automatically. That way if things change, you’ll know immediately.
First, select the MovingHelperTests group in the Xcode sidebar, then choose File\New\File… and select the iOS\Source\Swift File template. Name this new file TaskCellTests.swift, and make sure it’s being added to the test target, not the main target:
Next, set up the basic test case class by replacing the existing
import statement with the following:
import UIKit import XCTest import MovingHelper class TaskCellTests: XCTestCase { }
Add a test which verifies that when the checkbox in a
TaskTableViewCell is tapped, the associated task is updated:
func testCheckingCheckboxMarksTaskDone() { let cell = TaskTableViewCell() //1 let expectation = expectationWithDescription("Task updated") //2 struct TestDelegate: TaskUpdatedDelegate { let testExpectation: XCTestExpectation let expectedDone: Bool init(updatedExpectation: XCTestExpectation, expectedDoneStateAfterToggle: Bool) { testExpectation = updatedExpectation expectedDone = expectedDoneStateAfterToggle } func taskUpdated(task: Task) { XCTAssertEqual(expectedDone, task.done, "Task done state did not match expected!") testExpectation.fulfill() } } //3 let testTask = Task(aTitle: "TestTask", aDueDate: .OneMonthAfter) XCTAssertFalse(testTask.done, "Newly created task is already done!") cell.delegate = TestDelegate(updatedExpectation: expectation, expectedDoneStateAfterToggle: true) cell.configureForTask(testTask) //4 XCTAssertFalse(cell.checkbox.isChecked, "Checkbox checked for not-done task!") //5 cell.checkbox.sendActionsForControlEvents(.TouchUpInside) //6 XCTAssertTrue(cell.checkbox.isChecked, "Checkbox not checked after tap!") waitForExpectationsWithTimeout(1, handler: nil) }
This is what each part does:
- Create an expectation for which to wait. Since the delegate is a separate object from the test, you may not hit the success block immediately.
- Create an inline struct, conforming to the test delegate, which allows you to check and see whether it was called or not. Since you want this struct to tell you when the expectation has been met, and do a check based on a value you pass it, you make it accept both the expectation and the expected values as parameters.
- Set up the test task and verify its initial value, then configure the cell.
- Make sure the checkbox has the proper starting value.
- Fake a tap on the checkbox by sending the
TouchUpInsideevent which would be called when a user tapped on it.
- Make sure everything gets updated – starting with the checkbox by verifying its state has updated, and then wait for the expectation to be fulfilled to make sure the delegate is updated with the new value.
Build the test, but don’t run it – it’s time to be lazy, kick back, and let Travis do it for you. Commit your changes and push them up to the remote:
git add . git commit -m "Test marking tasks done" git push -u origin to-done
Create a new pull request following the steps you used previously, and call it To-Done. As you probably guessed from the instruction not to run your tests, this build fails:
Click the Details link to get the details of the build failure. Scroll all the way to the bottom, where you’ll see the following:
Scroll up a bit to see information about a crash which occurred while running the tests:
D’oh! The force-unwrap of an
IBOutlet didn’t work, so the test crashed. Why would that be?
If you think about how the
TaskTableViewCell is normally created – through the cell reuse queue managed by a view controller loaded from a storyboard – this crash makes sense. The cell isn’t being loaded from the storyboard, so the
IBOutlets don’t get hooked up.
Fortunately, this isn’t too hard to fix – grab a reference to a cell from an instance of
MasterViewController instantiated from the storyboard, and use its
tableView(_:cellForRowAtIndexPath:) method to grab a valid cell.
Add the following lines at the top of
testCheckingCheckboxMarksTaskDone(), wrapping the code you already added in the
if statement:
var testCell: TaskTableViewCell? let mainStoryboard = UIStoryboard(name: "Main", bundle: nil) if let navVC = mainStoryboard.instantiateInitialViewController() as? UINavigationController, listVC = navVC.topViewController as? MasterViewController { let tasks = TaskLoader.loadStockTasks() listVC.createdMovingTasks(tasks) testCell = listVC.tableView(listVC.tableView, cellForRowAtIndexPath: NSIndexPath(forRow: 0, inSection: 0)) as? TaskTableViewCell //REST OF CODE YOU ALREADY ADDED GOES HERE }
Next, to make sure the test doesn’t pass if
listVC is somehow
nil, add an
else clause to the
if let which fails the test if it gets hit:
} else { XCTFail("Could not get reference to list VC!") }
Now update your existing test code to use the cell you’ve just generated. Replace:
let cell = TaskTableViewCell()
with:
if let cell = testCell { //REST OF THE CODE BELOW SETTING UP THE CELL GOES HERE } else { XCTFail("Test cell was nil!") }
Once again, be lazy and let glorious automation do your work for you. Build the test to make sure the code compiles, but don’t run it. Commit your changes and push them up to the remote:
git add . git commit -m "Update grabbing cell for test" git push -u origin to-done
Again, you have an existing pull request, so when Travis runs the tests, you should see good news in your GitHub repo:
Click the Merge pull request button, then the Confirm merge button, and you’re done.
Congratulations! Thanks to the effort you’ve put in as you’ve worked through this Travis CI tutorial, you now have a base of tests you can use to make sure you don’t break anything as you improve the application, and Travis is set up to run them automatically. No more running tests manually – and there’s still time for happy hour :]
Where To Go From Here
You can download the finished project here.
This tutorial has only scratched the surface of what Travis CI can do. No, it won’t fetch you coffee, or beer, but Travis is useful for considerably more than just running tests.
Further Capabilities of Travis
- Using post-build hooks, it can upload the results of your build to an AWS S3 bucket automatically with minimal configuration.
- You can set up pre-build scripts to install and post-build remove certificates from the keychain to create signed builds.
- If you’re creating signed builds, you can also add post-build scripts to automatically upload builds to HockeyApp or iTunes Connect whenever tests pass after a merge.
Travis isn’t always sunshine and lollipops, however.
A few caveats to keep in mind:
- New versions of Xcode are not typically made available until they’ve been publicly released. This means you can’t use Travis to build a version of your app that’s using a beta SDK.
- Since they have a paid service, Travis has an incentive to upgrade everything in a timely fashion. Sometimes, however, that incentive doesn’t cause them to upgrade fast enough for everyone’s tastes. If you always need to be on the bleeding edge, keep this in mind.
- Build machines can be a bit slower than your local machine. Particularly if you’re running UI tests with KIF, you may run in to instances where the slowness of the build machine means you see race conditions you wouldn’t see on real devices, or test flakiness on the build server you don’t see locally.
- You get a lot of information in the logs from Travis, but you can’t get crash logs without setting up scripts to upload them to a third-party service after a build complete.
- All tests are run on simulators. If you have tests which must be run on a device, Xcode Bots is a better choice since it can run on both simulators and real devices – although this comes with the responsibility to manage provisioning and signing.
Want to know more?
If you’re interested in learning more about continuous integration with Travis, check out the following documentation:
- General Build Configuration Guidelines, which give a good overview of the Travis build process.
- Travis Objective-C documentation, which also covers Swift projects.
- Travis OS X CI Environment documentation, which helps determine what is or is not included in the default environment on OS X, as well as stock environment variables you can access in your .travis.yml file.
I’ve hope you’ve enjoyed this Travis CI. If you’ve got and questions then please feel free to ask them in the comments below! | https://www.raywenderlich.com/109418/travis-ci-tutorial | CC-MAIN-2017-43 | refinedweb | 4,048 | 69.72 |
It's been a while since I've used c++ much and now I'm enountering an annoying problem. It's probably some simple syntax issue (either that or the compiler is broken, but it's never really that..
). I've looked over various things and I can't see what's wrong....I think I'm just too involved at this point and I need a second opinion.). I've looked over various things and I can't see what's wrong....I think I'm just too involved at this point and I need a second opinion.
The problem is that the linker can't seem to find any methods within the class. I'm using gcc 2.95 and I 3.1....I get the same thing with both.
The errors are:
testy.cpp: undefined reference to `test::test(void)'
testy.cpp: undefined reference to `test::nowork(void)'
(I trimmed off the full path)
This is my code:
test.h
test.cpptest.cppCode:class test { public: test(); void nowork(); };
testy.cpp (driver)testy.cpp (driver)Code:#include <iostream> #include "test.h" using namespace std; test::test() { } void test::nowork() { int useless; cout << "hi there!\n"; }
Any help you can give would be appreciated, thanks.Any help you can give would be appreciated, thanks.Code:#include "test.h" #include <iostream> int main() { test will; will.nowork(); } | https://cboard.cprogramming.com/cplusplus-programming/59706-probably-simple-problem-classes.html | CC-MAIN-2017-26 | refinedweb | 228 | 78.55 |
by Vedant Gupta
How to use AI to play Sonic the Hedgehog. It’s NEAT!
Generation after generation, humans have adapted to become more fit with our surroundings. We started off as primates living in a world of eat or be eaten. Eventually we evolved into who we are today, reflecting modern society. Through the process of evolution we become smarter. We are able to work better with our environment and accomplish what we need to.
The concept of learning through evolution can also be applied to Artificial Intelligence. We can train AIs to perform certain tasks using NEAT, Neuroevolution of Augmented Topologies. Simply put, NEAT is an algorithm which takes a batch of AIs (genomes) attempting to accomplish a given task. The top performing AIs “breed” to create the next generation. This process continues until we have a generation which is capable of completing what it needs to.
NEAT is amazing because it eliminates the need for pre-existing data required to train our AIs. Using the power of NEAT and OpenAI’s Gym Retro I trained an AI to play Sonic the Hedgehog for the SEGA Genesis. Let’s learn how!
A NEAT Neural Network (Python Implementation)
GitHub Repository
Vedant-Gupta523/sonicNEAT
Contribute to Vedant-Gupta523/sonicNEAT development by creating an account on GitHub.github.com
Understanding OpenAI Gym
If you are not already familiar with OpenAI Gym, look through the terminology below. They will be used frequently throughout the article.
agent — The AI player. In this case it will be Sonic.
environment — The complete surroundings of the agent. The game environment.
action — Something the agent has the option of doing (i.e. move left, move right, jump, do nothing).
step — Performing 1 action.
state — A frame of the environment. The current situation the AI is in.
observation — What the AI observes from the environment.
fitness — How well our AI is performing.
done — When the AI has completed its task or can’t continue any further.
Installing Dependencies
Below are GitHub links for OpenAI and NEAT with installation instructions.
OpenAI:
NEAT:
Pip install libraries such as cv2, numpy, pickle etc.
Import libraries and set environment
To start, we need to import all of the modules we will use:
import retroimport numpy as npimport cv2import neatimport pickle
We will also define our environment, consisting of the game and the state:
env = retro.make(game = "SonicTheHedgehog-Genesis", state = "GreenHillZone.Act1")
In order to train an AI to play Sonic the Hedgehog, you will need the game’s ROM (game file). The simplest way to get it is by purchasing the game off of Steam for $5. You could also find free find downloads of the ROM online, however it is illegal, so don’t do this.
In the OpenAI repository at retro/retro/data/stable/ you will find a folder for Sonic the Hedgehog Genesis. Place the game’s ROM here and make sure it is called rom.md. This folder also contains .state files. You can choose one and set the state parameter equal to it. I chose GreenHillZone Act 1 since it is the very first level of the game.
Understanding data.json and scenario.json
In the Sonic the Hedgehog folder you will have these two files:
data.json
{ "info": { "act": { "address": 16776721, "type": "|u1" }, "level_end_bonus": { "address": 16775126, "type": "|u1" }, "lives": { "address": 16776722, "type": "|u1" }, "rings": { "address": 16776736, "type": ">u2" }, "score": { "address": 16776742, "type": ">u4" }, "screen_x": { "address": 16774912, "type": ">u2" }, "screen_x_end": { "address": 16774954, "type": ">u2" }, "screen_y": { "address": 16774916, "type": ">u2" }, "x": { "address": 16764936, "type": ">i2" }, "y": { "address": 16764940, "type": ">u2" }, "zone": { "address": 16776720, "type": "|u1" } }}
scenario.json
{ "done": { "variables": { "lives": { "op": "zero" } } }, "reward": { "variables": { "x": { "reward": 10.0 } } }}
Both these files contain important information pertaining to the game and its training.
As it sounds, the data.json file contains information/data on different game specific variables (i.e. Sonic’s x-position, number of lives he has, etc.).
The scenario.json file allows us to perform actions in sync with the values of the data variables. For example we can reward Sonic 10.0 every time his x-position increases. We could also set our done condition to true when Sonic’s lives hit 0.
Understanding NEAT feedforward configuration
The config-feedforward file can be found in my GitHub repository linked above. It acts like a settings menu to set up our training. To point out a few simple settings:
fitness_threshold = 10000 # How fit we want Sonic to becomepop_size = 20 # How many Sonics per generationnum_inputs = 1120 # Number of inputs into our modelnum_outputs = 12 # 12 buttons on Genesis controller
There are tons of settings you can experiment with to see how it effects your AI’s training! To learn more about NEAT and the different settings in the feedfoward configuration, I would highly recommend reading the documentation here
Putting it all together: Creating the Training File
Setting up configuration
Our feedforward configuration is defined and stored in the variable config.
config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction, neat.DefaultSpeciesSet, neat.DefaultStagnation, 'config-feedforward')
Creating a function to evaluate each genome
We start by creating the function, eval_genomes, which will evaluate our genomes (a genome could be compared to 1 Sonic in a population of Sonics). For each genome we reset the environment and take a random action
for genome_id, genome in genomes: ob = env.reset() ac = env.action_space.sample()
We will also record the game environment’s length and width and color. We divide the length and width by 8.
inx, iny, inc = env.observation_space.shapeinx = int(inx/8)iny = int(iny/8)
We create a recurrent neural network (RNN) using the NEAT library and input the genome and our chosen configuration.
net = neat.nn.recurrent.RecurrentNetwork.create(genome, config)
Finally, we define a few variables: current_max_fitness (the highest fitness in the current population), fitness_current (the current fitness of the genome), frame (the frame count), counter (to count the number of steps our agent takes), xpos (the x-position of Sonic), and done (whether or not we have reached our fitness goal).
current_max_fitness = 0fitness_current = 0frame = 0counter = 0xpos = 0done = False
While we have not reached our done requirement, we need to run the environment, increment our frame counter, and shape our observation to mimic that of the game (still for each genome).
env.render()frame += 1ob = cv2.resize(ob, (inx, iny))ob = cv2.cvtColor(ob, cv2.COLOR_BGR2GRAY)ob = np.reshape(ob, (inx,iny))
We will take our observation and put it in a one-dimensional array, so that our RNN can understand it. We receive our output by feeding this array to our RNN.
imgarray = []imgarray = np.ndarray.flatten(ob)nnOutput = net.activate(imgarray)
Using the output from the RNN our AI takes a step. From this step we can extract fresh information: a new observation, a reward, whether or not we have reached our done requirement, and information on variables in our data.json (info).
ob, rew, done, info = env.step(nnOutput)
At this point we need to evaluate our genome’s fitness and whether or not it has met the done requirement.
We look at our “x” variable from data.json and check if it has surpassed the length of the level. If it has, we will increase our fitness by our fitness threshold signifying we are done.
xpos = info['x'] if xpos >= 10000: fitness_current += 10000 done = True
Otherwise, we will increase our current fitness by the reward we earned from performing the step. We also check if we have a new highest fitness and adjust the value of our current_max_fitness accordingly.
fitness_current += rew
if fitness_current > current_max_fitness: current_max_fitness = fitness_current counter = 0else: counter += 1
Lastly, we check if we are done or if our genome has taken 250 steps. If so, we print information on the genome which was simulated. Otherwise we keep looping until one of the two requirements has been satisfied.
if done or counter == 250: done = True print(genome_id, fitness_current) genome.fitness = fitness_current
Defining the population, printing training stats, and more
The absolute last thing we need to do is define our population, print out statistics from our training, save checkpoints (in case you want to pause and resume training), and pickle our winning genome.
p = neat.Population(config)
p.add_reporter(neat.StdOutReporter(True))stats = neat.StatisticsReporter()p.add_reporter(stats)p.add_reporter(neat.Checkpointer(1))
winner = p.run(eval_genomes)
with open('winner.pkl', 'wb') as output: pickle.dump(winner, output, 1)
All that’s left is the matter of running the program and watching Sonic slowly learn how to beat the level!
To see all of the code put together check out the Training.py file in my GitHub repository.
Bonus: Parallel Training
If you have a multi-core CPU you can run multiple training simulations at once, exponentially increasing the rate at which you can train your AI! Although I will not go through the specifics on how to do this in this article, I highly suggest you check the sonicTraning.py implementation in my GitHub repository.
Conclusion
That’s all there is to it! With a few adjustments, this framework is applicable to any game for the NES, SNES, SEGA Genesis, and more. If you have any questions or you just want to say hello, feel free to email me at vedantgupta523[at]gmail[dot]com ?
Key Takeaways
- Neuroevolution of Augmenting Topologies (NEAT) is an algorithm used to train AI to perform certain tasks. It is modeled after genetic evolution.
- NEAT eliminates the need for pre-existing data when training AI.
- The process of implementing OpenAI and NEAT using Python to train an AI to play any game. | https://www.freecodecamp.org/news/how-to-use-ai-to-play-sonic-the-hedgehog-its-neat-9d862a2aef98/ | CC-MAIN-2020-24 | refinedweb | 1,595 | 56.66 |
For.
24xx Serial EEPROM
The EEPROM is using an I²C interface, and devices are available from 128 bit to 1 MBit. Typically they have an erase/write cycle of 1’000’000, much more than typical flash. The devices are ‘hobby friendly’ as they are available in DIP package.
Processor Expert 24AA_EEPROM Component
The 24AA_EEPROM Processor Expert component implements a driver for the 24xx series of serial I²C EEPROM devices.
The following shows the component properties:
- Component name: User name/prefix for driver.
- Device: drop down for different device types (512 bits, 1024 bits, etc), e.g. ‘512’ for 24LC512 or 24AA512 device.
- Block buffer size: The driver supports cross page writes. For this an extra buffer size can be specified.
- Acknowledge Polling: After writing a byte or a page, the driver supports optionally acknowledge polling (see device data sheet). To improve performance, the device specific Page Write Time can be specified.
- Under Connection the I²C bus interface is specified, plus an interface to the optional Write Protection Pin.
- The component features an optional command line/Shell interface.
Component Functions
The component offers a set of functions to read/write data:
ReadByte()
With
byte EE241_ReadByte(EE241_Address addr, byte *data);
a byte is read from the device.
The memory address is device specific. E.g. the 24xx08 device encodes upper address bits in the I²C device address. And depending on the device, an 16bit address or different I²C device addresses needs to be used. This is implemented with conditional compilation and macro wrappers:
byte EE241_ReadByte(EE241_Address addr, byte *data) { 8bit address */ #else /* use 16bit address */ res = GI2C1_WriteBlock(&addr16, 2, GI2C1_DO_NOT_SEND_STOP); /* send 16bit address */ #endif if (res != ERR_OK) { (void)GI2C1_UnselectSlave(); return res; } res = GI2C1_ReadBlock(data, 1, GI2C1_SEND_STOP); /* read data byte from bus */ if (res != ERR_OK) { (void)GI2C1_UnselectSlave(); return res; } return GI2C1_UnselectSlave(); }
Below is a read operation from address 0x0001 which returns the data value 0xAB from a 24LC512 device:
WriteByte()
Writing a byte is performed with the following function:
byte EE241_WriteByte(EE241_Address addr, byte data) { uint8_t res, block[3]; */ block[2] = data; /* switch to read mode */ res = GI2C1_WriteBlock(block, sizeof(block), */ #endif if (res != ERR_OK) { (void)GI2C1_UnselectSlave(); return res; } return GI2C1_UnselectSlave(); }
❗ Acknowledge polling is not implemented in an ideal way here. The problem is that the underlying Processor Expert I²C driver does not allow just to send the I²C address byte: it requires at least a data byte sent. As such, I’m sending a dummy 0xFF byte.
Below is how this looks on the bus with writing 0x8A to the address 0x0012:
With Acknowledge Polling enabled, the driver checks right after the write operation if the device responds with an ACK:
The driver retries until a successful ACK is received:
💡 The dummy 0xFF value is required by the underlying Processor Expert I2C_LDD driver.
ReadBlock()
Reading more than a single byte is done with
ReadBlock():
byte EE241_ReadBlock(EE241_Address addr, byte *data, word dataSize) { address */ #else res = GI2C1_WriteBlock(&addr16, 2, GI2C1_DO_NOT_SEND_STOP); /* send 16bit address */ #endif if (res != ERR_OK) { (void)GI2C1_UnselectSlave(); return res; } res = GI2C1_ReadBlock(data, dataSize, GI2C1_SEND_STOP); if (res != ERR_OK) { (void)GI2C1_UnselectSlave(); return res; } return GI2C1_UnselectSlave(); }
Below is the sequence to read 16 bytes from the address 0x0010:
WriteBlock()
With WriteBlock() multiple bytes can be written to the device:
res = EE241_WriteBlock(0x10, (uint8_t*)"Hello", sizeof("Hello"));
As a write cannot be performed over EEPROM page boundaries, the write sequence gets splitted up:
byte EE241_WriteBlock(EE241_Address addr, byte *data, word dataSize) { uint8_t res, i, *p, block[EE241_BLOCK_BUF_SIZE+2]; /* additional 2 bytes for the address */ uint16_t eepromPage = (uint16_t)(addr/EE241_PAGE_SIZE); uint8_t offset = (uint8_t)(addr%EE241_PAGE_SIZE); if (dataSize>EE241_PAGE_SIZE) { return ERR_OVERFLOW; /* writing such a block is not implemented yet */ } if (dataSize==0 || dataSize>EE241_BLOCK_BUF_SIZE) { return ERR_OVERFLOW; /* you may increase the buffer size in the properties? */ } if (offset+dataSize <= EE241_PAGE_SIZE) { /* no page boundary crossing */ */ /* copy block */ p = &block[2]; i = (uint8_t)dataSize; while(i>0) { *p++ = *data++; i--; } res = GI2C1_WriteBlock(block, dataSize+2, */ if (res != ERR_OK) { (void)GI2C1_UnselectSlave(); return res; } return GI2C1_UnselectSlave(); #endif } else { /* crossing page boundaries: make two page writes */ res = EE241_WriteBlock(addr, data, (uint16_t)(EE241_PAGE_SIZE-offset)); /* first page write */ if (res != ERR_OK) { return res; } res = EE241_WriteBlock((EE241_Address)((eepromPage+1)*EE241_PAGE_SIZE), data+(EE241_PAGE_SIZE-offset), (uint16_t)(dataSize-(EE241_PAGE_SIZE-offset))); /* first page write */ if (res != ERR_OK) { return res; } } return res; }
❗ The driver currently only supports up to two memory pages.
In a logic analyzer writing the string “Hello” to the address 0x0010 then looks like this (without the acknowledge polling):
Shell Command Line Interface
With the optional shell interface, I can read/write to the device and show the status:
Example Project
I have committed on GitHub an example project.
It includes following components:
- 24AA_EEPROM: Microchip 24xx serial EEPROM driver
- GenericI2C: common driver for I²C bus access (driver on top of I2C_LDD)
- Timeout: Manages timer based timeout of the bus
- I2C_LDD: Low level I²C device driver
- TimerInt: 1 ms timer interrupt for Timeout component, driver on top of TimerUnit_LDD
- TimerUnit_LDD: low-level timer driver
- Wait: busy waiting driver
The program uses the driver
Test() function to verify everything is ok:
static uint8_t res; ... res = EE241_Test(); if (res!=ERR_OK) { for(;;) {} /* failure */ }
Summary
Using the 24xx external serial EEPROM gives storage room for many applications. And the Processor Expert driver makes usage of it very simple for me. All the sources and drivers are available on GitHub/SourceForge (see this post how to download and install the components).
Happy EEproming 🙂
You might also want to look at the SPI SRAM chips.
Yes, I have seen these, but not used any in my designs.
I used the 23LC1024 to add another 128K of RAM to an ARM chip after I “ran out”. Slow, of course, but I was stuck. Works up to 5V, too!
Somewhat related…
On one of my reverse-engineering projects I made a wiretap for one of those serial EEPROMs in a automotive ECU. I used S08JS16 and connected to the serial memory chip. Luckily the target ECU’s micro talked to the EEPROM slowly enough I was able to monitor all the signals, decode, an spy on every read and write in real time.
Pic:
USB to the PC. Ribbon cable to USBDM.
Interesting, thanks for sharing. I did something similar in this project:
Hi Erich,
excuse for the OT reply… but ever embedded component matter about it.
Have you try to enabled WatchDog on your embedded component “WAIT”?
On my small app, around an FRDM-KL25Z board and under CW Developer Studio 10.4, it cause an error at generation code of PE:
ERROR: This component is not implemented in this version!
Where i make a mistake?
TNX!
Hi Antonio,
indeed, it does not work (yet) with Kinetis, as Kinetis has a different watchdog component. If you need it, I could implement it, but you would need to give me some time.
Yes Erich, i think necessary the WDog especially on automotive apps. Dont worry, take it all the time you need.
Thanks Erich!
Understood. Keep in mind that I had added the watchdog to Wait to prevent watchdog timeout inside the Waitms routine. All what it does is calling the watchdog every milli-seconds there.
Are you using my sources on GitHub? I’m committing my change in a few minutes.
I have pushed the updated *.PEupd files on GitHub now:
Let me know if things are working on your end.
Thanks!
WDog run perfectly also on Kinesis.
Good work, Erich, tnx.
Hi Antonio,
thanks for the feedback, great!
Erich
Sorry Erich,
my analysis is hurried… In the generated code of WAIT methods, the parameter of WDog_Clear function added at WAIT delay loop, is the pointer ‘WDog_DeviceData’ but is undeclared.
This causes an error.
If you read in the code generated of WatchDog_LDD driver, the typedef defined for this parameter (argument of function WDog_Clear) is named ‘WDog_TDeviceData’, may be the cause of error?
Hi Antonio,
sorry, I missed to tell you that the WDog component needs to be initialized. In the WDog1 component set ‘Enabled in init. code’ to ‘yes’. then that WDog_TDeviceData gets created.
Ok Erich,
but the option to set yes must not only the ‘Enabled in init. code’, but also the ‘Auto initialization’ must be set to yes, otherwise the PE not define (in WDog.h file) the WDog_DeviceData token.
Well Erich, now (and previously) WDog run perfectly also on Kinesis.
TNX
Hi Antonio,
you are 100% correct 🙂
Erich
Hi Eric,
Am trying to implement the eeprom Test in FreeRTOS. Have the lastest components installed. Fails and goes to PE_DEBUGHALT(); in GI2C1.c in the GI2C1_WriteBlock code. Am using I2C Channel 1 with TMOUT1 RTOS enabled, and GI2C1 RTOS enable. Any idea why this fails? Works well without FreeRTOS.
Hi John,
I believe you run into a hard fault in GI2C1_RequestBus() because GI2C1_busSem semaphore is NULL.
Is GI2C1_Init() called? There the semaphore will be initialized, and usually it gets called before main().
Erich,
GI2C1_Init() is initialized in PE_low_level_init() . Gets to line 113 but not 114 in EE241.c. Fails 6th time in loop.
Hmm, somehow I have only comments on these lines? Maybe we are not using the same sources.
I’m using
** Component : 24AA_EEPROM
** Version : Component 01.023, Driver 01.00, CPU db: 3.00.000
My 24AA_EEPROM component reads the same at the top of the file.
Processor : MKL25Z128VLK4
** Component : 24AA_EEPROM
** Version : Component 01.023, Driver 01.00, CPU db: 3.00.000
Lines 113 and 114 in EE241.c are:
res = GI2C1_WriteBlock(block, 1, GI2C1_SEND_STOP); /* send address and data */
} while(res!=ERR_OK); /* wait until we get an ACK */
Aso using a 256 device, so the conditional compile code will affect the line numbers.
Hi John,
ok, now the line numbers make sense to me. Do you know which interrupt fires? You might need to enable ‘own handler for every interrupt’ in the CPU component (see). If this is a hard fault, then I suggest to use the hard fault component ().
As you are using the timeout componen: make sure you call TMOUT1_AddTick() from the RTOS tick handler in Events.c (otherwise the timeout does neve time out).
I hope this helps?
Eric,
I did add TMOUT1_AddTick() to the tick handler in Events.c, but it still failed. I must work on something else for a while, then dig into the hard fault interrupt. When the EEPROM test is by- passed, everything else works.
Hi John,
not sure what is causing this. For now, I suggest you do not use that Test() function ;-). I do not have the same EEPROM type available (I have now ordered two pieces). But I think it is not related to the EEPROM type. If you want (and can), you can send me your project to my email address mentioned on the About page of this blog, and I’ll try to have a look to see what the problem is. But from your description it could be a stack overflow or memory corruption problem. You might increase the stack size to see if the problem goes away?
John,
I have finally received my 24AA256 EEPROM from Farnell, and checked your application. I see that you have only 40 stack units (=40*4=160 bytes) available as minimal stack size. But the EE241_WriteBlock() is using a local buffer which easily could cause a stack overflow. I suggest to increase the FreeRTOS stack size to a higher value (at least 100 units).
I copied the files from the GitHub page, there was no compilation error but the FRDM-KL25Z not communicate with the EEPROM, could not identify the error that the function ‘EE241_Test ()’ returns. I am using 24LC08B, I changed ownership Device for ‘8 ‘and Page Write Time for ‘3’. I’ve changed the EEPROM. Can anyone help me?
Hi Bruno,
can you check the signals with a logic analyzer? Maybe your pin connections are not correct?
I do not possess signal analyzer. I checked the pins, all right.
By doing Debug, I found that the error is only to read EEPROM, the write does not return error.
EE241.C:
res = EE241_ReadByte(0x0000, &val);
if (res != ERR_OK) {
Err();
return res;
}
if (val != 0) {
Err(); //---RETURN ERRO this point
return ERR_FAULT;
}
Another error that appears in the Debug:
GI2C1.C :
timeout = TMOUT1_GetCounter(GI2C1_TIMEOUT_TICKS(dataSize+1)); /* set up timeout counter */
Erro: No source available for “__aeabi_idiv (0x00000410)() “
Hi Bruno,
I suggest that need a logic analyzer. These kind of problems are hard or impossible to solve without it. It would be like if you do not have a debugger ;-).
If you have a spare FRDM board, then you can consider using it as a low cost logic analyzer (). As for myself, spending Euro 100 for a Salae logic analyzer was probably the best engineering investment I ever made: it saved me problably hunderds of hours of bug finding time.
As for your problem: It seems that the write and read reports success, but the value read back is wrong. It should have written zero to the address 0x0000, but it seems that it reads back something different. Again, without a logic analyzer this is nearly impossible to debug.
As for the ‘no source available’: it seems that the debugger settings are missing a path to the source file where __eabi_idiv() is defined. But this is not a real problem. What you would need is a logic analyzer (or an oscilloscope).
I run test() OK.
when I enable “Shell” property, CW would add 3 Component(Shell/Utiliy/AS1), When config “Shell” component itself, there is a Utility property, but the dropdown menu is empty, and the details show “Unassigned interface” in red.
I just install CW10.5, is’t the new version’s problem?
Can anyone help me?
I create a test project in “Processor Expert Software”, there is no problem to generate the “Utility” property.
You mean it works in the ‘Processor Expert Driver Suite’? Note that the Driver Suite and CodeWarrior are using different folders/locations for the components. So it could be that you have loaded the Utility in the Driver suite, but not in CodeWarrior?
Do you have the ‘Utility’ component listed in the component library?
Yes, I have install Utility component in both, Utility property can enable in EE241 component, but failed to Shell component.
Maybe something went wrong with the *.PEupd file import. I have just published new files on
Can you import and try the new files?
I’m using git to sync github file, not install by .PEupd
Hi Erich,
I have a question about “do acknowledge polling” in WriteBlock method , your code are:
do {
res = GI2C1_WriteBlock(block, 1, GI2C1_SEND_STOP); /* send address and data */
} while(res!=ERR_OK); /* wait until we get an ACK */
but if external EE device not answer “ack” signel, it’s would make a deadlock, although
it’s a Little probability event. I would suggest like this:
for(i=0; i40 /* send address and data */
if(res == ERR_OK)
break;
}
the maggic number ‘5’, I think the EE device have 5m Self-timed Write Cycle, it’s enough to most EE device.
Maybe are the Web service problem, the code would like this:
for(i=0; i<5; i++)
{
res = GI2C1_WriteBlock(block, 1, GI2C1_SEND_STOP);
if(res == ERR_OK)
break;
}
Yes, good point. I think I add a timeout there using the Timeout component. That way it would leave the loop after a configured number of milli-seconds.
I have implemented a timeout in the component, see
Pingback: Tutorial: Using the FRDM-KL25Z as Low Power Board | MCU on Eclipse
Hi Erich,
I copied example project using 24LC256,I have a question about Shell interface, i use termite can’t show status and read/write to the device ,but i have config Shell component and complier is ok ,Can anyone help me?
Hi Peter,
could you describe your problem a bit more? I suggest that you check if you are using the correct virtual COM port used. The other thing is: do not have the virtual COM port open if you unplug/replug the board: Close the COM port first, then unplug the board, then plug the board in, then open the COM port. Otherwise the COM port will be locked/open and you cannot communicate. Additionally the OpenSDA USB CDC will reset the USB traffic during Power-On Reset of the FRDM board.
Hi,
I from Brasil, I would like know if possible save data in EEPROM of Freedom Board KL25Z.
Sorry, my english
Hi Fernando,
the FRDM-KL25Z has no EEPROM on it, so you would need to use an external EEPROM in order to do this. Except you want to store your data in the microcontroller FLASH memory?
Greetings to Brasil! 🙂
Thank you,
If possible save data in memory FLASH, and after turn off FDRM and read data?
yes, of course 🙂 You can program the FLASH by the application at runtime. I’m doing this for example to store calibration data in my Sumo Robots.
I very good,
I’ll try, thank you!
Hi Erich,
Thank you for all your I2C-related tutorials. They have been very helpful!
1) Do you know if the KL46Z plus GI2C/I2C_LDD component combination is limited to only receiving eleven 8-bit words at a time?
2) Why is the GI2C component’s implementation limited to sending only”GI2Cx_WRITE_BUFFER_SIZE – 1″ words? Why does the GI2C component have problems when configuring the “Write Buffer Size” property to more than 16 byte-sized words?
I’ll explain myself:
I have a KL46Z project that uses the GI2C component with the underlying I2C_LDD component. So far I can send and receive short data blocks between the KL46Z and the I2C-enabled sensor I’m working with. However, if I try to receive more than 11 byte words I get a hard fault (I’m using your hard fault component for debugging). Could this have something to do with the ASIC design? I didn’t find anything explaining this limitations in the KL46Z’s reference manual.
Furthermore, GI2C’s implementation is limited to sending only “GI2Cx_WRITE_BUFFER_SIZE -1” bytes by the following code (line 271 in the GI2Cx.c source file):
if (memAddrSize+dataSize>GI2C1_WRITE_BUFFER_SIZE) {
return ERR_FAILED;
}
“memAddrSize” is the number of address bytes and “dataSize” is the size of the data buffer in bytes. The WriteAddress() method is declared as:
GI2C1_WriteAddress(byte i2cAddr, byte *memAddr, byte memAddrSize, byte *data, word dataSize)
So for example, if I want to send 16 byte-sized words I would call:
GI2C1_WriteAddress(slave_addr, &dest_reg_addr,1, &tx_data, 16)
However, this means that WriteAddress()’s implementation would perform the following check:
if(1+16>16){
return ERR_FAILED;
}
This causes WriteAddress() to prevent developers from sending as many bytes as defined using the “Write Buffer Size” property.
Thanks in advance! Any insight would be appreciated!
Hi Carlos,
first, the component only supports 8bit units on the bus (no 11bit units, etc). But you should be able to send more data (as a block). So I assume a ‘word’ are 8bits for you?
And if you want to send larger blocks, then you need to increase the WRITE_BUFFER_SIZE.
I hope this helps.
Hello again Erich,
I’ve been using your hard fault component for debugging the issue I posted above and I have a couple of questions.
The following values are loaded to the stacked registers when your hard fault handler is called:
stacked_pc is 0x400.
stacked_r3 is 0x0.
stacked_lr is 0x5f2d.
Using the disassembly view with address 0x400 gives me several instructions of the type “.short 0xffffffff”.
I believe that having 0x0 for stacked_r3 means that a NULL pointer was accessed.
The stacked linked register leads me to the following block from GI2C1.c:
if (GI2C1_UnselectSlave()!=ERR_OK) {
return ERR_FAILED;
}
So perhaps the processor was trying to execute the UnselectSlave() function?
Is this the proper interpretation for these stacked register values? If this is the case then I’m not too sure how trying to receive more than 11 bytes is a problem. Except maybe if my I2C-enabled sensor wasn’t able to send more than 11 bytes? I tried looking at the sensor with an oscilloscope but the presence of the oscilloscope probes messes up with the execution of the whole firmware.
Thanks again!
Hi Carlos,
it looks the problem is at 0x5f2d. That r3 is zero does not mean that this is a problem. It would be only if e.g. the assembly code around 0x5f2d uses that register e.g. for a pointer access. The hardfault could be as well that at this place the function UnselectSlave() returns, but the stack is corrupted. Can you try to increase the stack size if this has an impact?
Hi Carlos,
if the presence of an oscilloscope is messing up your firmware, then this concerns me: either something is wrong with your probe, or your hardware really is that fragile that it will not stand a real environment? Maybe this is the source of your problem? Why is there a problem with your probe?
Hi Erich,
Thanks for all the replies. I did try increasing the stack size but that didn’t solve the problem. However, I think I may have found the actual cause of the problem. I will write back as soon as I confirm this. I think it makes sense for the hard fault to occur. This is why:
The I2C-enabled sensor I’m using came with some generic drivers. These drivers are abstracted from the target microcontroller (the KL46Z in my case). The abstraction required me to implement a macro so these drivers can use the Generic I2C component. I already spotted some pointer issues in my I2C wrappers that bridge the drivers and the Generic I2C component. Fixing these problems I spotted will let me know whether this is the sole cause of the hard fault.
As for the scope probe, I’m not sure. I haven’t seen impedance matching/circuit loading problems like these before. Not even when I have probed 125 MHz Ethernet controller chips. I’ll also post about this as soon as I figure this out.
Thanks again!
Pingback: Configuration Data: Using the Internal FLASH instead of an external EEPROM | MCU on Eclipse
Hello Erich,
I am trying to use the EEPROM Driver along with FREERTOS component.
I find that the mI2C_MasterSendBlock()
Enters
taskENTER_CRITICAL();
in which Interrupts are disable.
Then
Enters
taskEXIT_CRITICAL();
in which it should enable Interrupts again
but it does not.
So when the I2C LDD driver gets here:
byte GI2C1_WriteBlock(void* data, word dataSize, GI2C1_EnumSendFlags flags)
{
byte res = ERR_OK;
for(;;) { /* breaks */
GI2C1_deviceData.dataTransmittedFlg = FALSE;
res = mI2C_MasterSendBlock(GI2C1_deviceData.handle, data, dataSize, flags==GI2C1_SEND_STOP?LDD_I2C_SEND_STOP:LDD_I2C_NO_SEND_STOP);
if (res!=ERR_OK) {
break; /* break for(;;) */
}
do { /* Wait until data is sent */
} while (!GI2C1_deviceData.dataTransmittedFlg);
break; /* break for(;;) */
} /* for(;;) */
return res;
}
it gets stuck on the while loop waiting for TransmittedFlg to be set.
But that never happens.
Any Ideas why?
Are you sure that interrupts are enabled when SendBlock() gets called? I suspect that interrupts are disabled, e.g. if you call any I2C functions before the RTOS is started?
So are you sure interrupts are enabled (and you call the I2C e.g. from a task context)?
Hi Erich,
I’m trying to use a 24AA1026 EEPROM in one of my project, and I’m working with a TWR K60 board. When using the EE241 component, I encounter these following three problems:
1. “EE241_WriteByte” function always get blocked here :
do { /* Wait until data is sent */
} while (!GI2C1_deviceData.dataTransmittedFlg);
which is in the lower component GI2C. To solve this problem temporarily, I enabled the Timeout of GI2C. So I can jump out of this routine, but I still have no idea where the problem is. (I noticed that it is the same problem with Moise?)
2. “GI2C1_ProbeACK” function always returns ERR_FAILED. That is to say my EEPROM never sends back or my micro never receives a AKG signal, right? Moreover, I find that this time, even if I enabled Timeout for EE241, it won’t break the ACK polling loop.
3. Both “EE241_WriteByte” and “EE241_WriteBlock” get stuck because of the loop of waiting for the interrupt flag. But, if I use “EE241_ReadByte” or “EE241_ReadBlock” to check the address that I’ve just written to, I find the data is there. So does that mean only the interrupt flag isn’t set correctly?
Note that both “EE241_ReadByte” and “EE241_ReadBlock” works well and I should have enabled the interrupt. I did two tests, one with FreeRTOS, another without.
Do you have any ideas ?
Many thanks!
Hi Kenan,
it is really hard to tell what is going on. Have you checked the bus activites with a logic analyzer. It sounds to me that either your I2C bus is not configured properly, or your have cable/connection problems (proper dimension of the I2C pull-ups? length of cables?). And you need to check with the debugger if your interrupts are enabled.
I hope this helps.
Hello Kenan,
I am using the 24LC512 EEPROMs and I have same
issue with the “GI2C1_deviceData.dataTransmittedFlg”
not being set by the Interrupts.
I have not being able to solve this issue. So I decided to use barebone drivers from Freescale’s website.
See this link:
The very last comment there has the i2c.zip file with barebone drivers.
Hopefully some one can solve this issue very soon, because
Erich’s PE driver is great. I want to use it, but it does not work in my Project.
If the I2C driver does not work, the most likely reason is that interrupts are disabled. Are you 100% sure that you have interrupts enabled properly? I suggest to check this in the debugger (PRIMASK core register) and verify that the least significant bit is NOT set.
Hi Erich,
I’ve tried to use this component, but when I call the function EE241_Test() it’s just return an error code (27U). I’m using a 24AA64 EEPROM and I’ve selected the device 32. Can you help?
I think you are not using the I2C bus properly, and probably you have missed to add the timeout ticks? Are you calling TMOUT1_AddTick() in Event.c? Have you debugged your project to see what returns the error code 27?
Have a look at the project on GitHub:
Hi Erich,
I am trying to use a different EEPROM for the same project part# ISSI24C16A, Should there be any modifications in the same as the Pin configrations all seems to be the same.
But when i try this on the EEPROM nothing is getting displayed on the Serial Terminal.
Please help
Is this ISSI24C16A compatible to the 24C16A? Do you have a good link to the data sheet?
Ya you can find the same below
Hi Erich,
I have noted that there is a component called AT25HP512, but when I try to include it in a project it flags an error because it cannot find the EEPROM_SPI driver. I have found said driver on your GitHub, but I can’t seem to get it loaded into Processor Expert. Please advise.
Thanks
Mark Watson
Laramie WY
Hi Mark,
I have not used that component for a very long time, and I confirm it is broken :-(. I see how I can fix it asap. Sorry about this.
Erich
Hi Mark,
I have now commited a fix on GitHub (the sources), but not released new component(s) yet. I have right now no hardware to test it, so I send you that comonent by email.
Erich
Excelent tutorial! Thanks
Hi Erich, thank you for the post was very usefull; i have a question : i want to store more than 16 bits example a web page that have 20 bits , something like; with
res = EE241_WriteBlock(0x2, (uint8_t*)pin, sizeof(“”));
i only stored.
maybe the method
res = EE241_WriteBlock(EE241_PAGE_SIZE-5, (uint8_t*)”Hello World!”, sizeof(“Hello World!”));
could work but what adress is “EE241_PAGE_SIZE-5” , i need store a lot of data in diferent adresses and i need to know the map of each one, have an idea how can i do this.
Regards.
Hi Marcela,
. It seems that yo have that setting set to 24?
I think you meant 20 BYTES (not bits). WriteBlock() is using an internal buffer size. See the ‘block buffer size’ in
I hope this helps,
Erich
yes it seems to work but now i have troubles with the write block , i use for example: res = EE241_ReadBlock(0x5, data, sizeof(data)); // lee valor velocidad limite
latitud=data; but i need to read another adresses , then when i try to read two or more the latitud variable and the others variables have the same value , i know that it is for use the same temporal variable “data” but if i use another name with the same type the task ReadBlock do not works ok.
Hi Marcela
I recommend that you use a logic analyzer or oscilloscope to inspect the signals to your EEPROM, if everything is sent over the wires as it should.
I hope this helps,
Erich
I have a problem with a S9KEAZN16AMLC automotive part and a 24LC32A EEPROM from microchip. I am starting out with the EEPROM driver from the PE components. The program gets stuck on a never ending loop which leads me to suspect that the I2C.datatransmittedflag is never set. I tried scoping the I2C lines out and found that the Controlbyte (0xA0) and the dummy byte (0xFF+ACK) seem to be working but it is the writing and reading that seems to be in error. The primask registers is read to be 0x00. I looked at the registers tab in the debug perspective. I was wondering how this issue was overcome. I am running the I2C peripheral at 100kHz clock and with 2ms page write time on the EEPROM.
It seems to me that you are using the I2C driver in interrupt mode, but your interrupts are disabled? Can you check with the debugger when you are inside the never ending loop checking for I2C.datatransmittedflag if your interrupts are turned on?
This is the status of the I2C registers upon stepping through the code until the part where the loop gets stuck waiting for the data transmitted flag (read MSB first)
I2C status register = 10100010
IICIF bit in the I2C status register is set already upon entering this part of the loop in the writeblock routine.
do
{
}while(!GI2C1_deviceData.dataTransmittedFlg);
Also, I looked at the primask register upon entering and exiting critical section. The interuupts are disabled and enabled upon enter and exit respectively. Is ther any kind of debug that I can do?
Thanks for the help. Much appreciated.
So the PRIMASK looks ok then. Have you checked your I2C data and clock lines with a logic analyzer or oszilloscope? I believe your device does not respond to your commands and the address you send.
I have a scope connected and I see the 0xA0 along with the start and atop and the dummy 0xFF+ACK that you send. But the address and data don’t seem to be written and read. Would you like to take a look at the scope info and my project? Thanks. I can email it to you.
sure you can send it to me.
I just emailed the project and a screengrab of the scope to you in the email id ending with hslu.ch. Mine ends with “umn.edu”. In case it ends up in your junk/spam folder. Thanks a ton.
Thank you for that scope image. But I don’t see your device sending an ACK as shown in
LikeLiked by 1 person
Hi Erich,
I was just checking why the device was not sending an ACK inspite of me sending the control byte and the like. Is there a way to test an EEPROM?
PIN7 SCL (from uC) connected to pin 6 of the Chip through a 1k pullup to 3.3Vdc.
PIN8 SDA (from uC) connected to pin 5 through 1k pullup to 3.3Vdc
A0,A1,A2 WP and Vss of the chip is grounded.
Vdd is fixed at 3.3Vdc and decoupled to ground using a 100nF.
Do I have to play with the pullups? And 3.3Vdc is within the max of 5.5Vdc from the datasheet.
Kind of running out of options!
Is there a way to erase the whole EEPROM and then reprogram it?
Also in order to check if the EEPROm s responding through hyperterminal/Termite I would like to know what connections need be made. Thanks!
Can you check if you are using the correct EEPROM/device type on your board, as different devices can have different I2C addresses.
And you don’t need to erase it first: it has to respond with the ACK signal if it responds to the I2C address you put on the bus.
Oh I just realised that I had acknowledgement polling enabled when I tried read/write and so I disabled acknowledgement poll on the PE component and the read/write happens as expected.
Thank you for your help.
I am using a custom board and I am programming using a Jlink. I would like to know if there is a way for the shell interface to communicate with my board. Or is it absolutely essential to have Open SDA in order for the shell interface and termite communication to take place?
Ah, that makes sense now. I did not realize that you were using polling mode.
As for the shell interface: all what you need is either a USB CDC, UART or Segger RTT connection. So you can do that with any board and you do not need OpenSDA.
Sure. Thanks.
I have a follow-up question though. I am trying to build a temperature logger and write temperature values on the EEPROM. I am using the CPU’s internal temperature sensor /ADC and reading the values that I need to write on FreeMaster. I was thinking if there is a way to write float values on the EEPROM and if so how to log it for extended periods of times. I have a variable avgCpuTemp (it varies from 29 to 32 degree C) and I am trying to write it inside the ADC ISR. And the ADC is hardware triggered. I don’t want the ADC to miss triggers or write incorrect data on my EEPROM. Is there a better way to do this?
The solution would be to use a buffer/queue or ring buffer.
Use an RTOS like FreeRTOS. From the ADC ISR, put the values into a queue. The queue is written from a task to the EEPROM.
Hi Erich, I have a question with regard to reading the data from the EEPROM on a terminal program. I would like to read it from the EEPROM without the use of a debugger like SEGGER/OpenSDA. I have a TTL to RS232 cable connected to my PC. I am able to send strings and read the data independent of the EEPROM i.e. UART communication between uC and PC is established. What I would like to know of is a way for accessing EEPROM data and read EEPROM through this connection. Thanks.
Yes, I’m using the Shell component for this, with the command line interface to the EEPROM. See the I2CSpy in
Hi Erich,
I am trying to write a structure that represents a log record of errors that looks like this.
struct
{
uint16–;
uint16–;
uint8;
uint32;
} logrecord;
byte* logpointer = (byte*)&logrecord;
i have a byte pointer to point to the whole record and copy to block.
What I have a problem with is writing multiple records on the EEEPROM 24LC32A. Is there a way I can write the whole record in one shot, keeping in mind the offsets in addresses because of writing multiple bytes of data. Any pointers would be greatly helpful- approach wise.
You can use the WriteBlock() method of the component for this.
Yes, WriteBlock would work but when I scoped the data on the SDA and SCL lines – I see that the page size of 8 was an issue.
My routine goes something like this-
for(startaddress = 5; startaddress <= 0x0FFF; startaddress+sizeof(errLogEE_record))
{
res = EE241_WriteBlock(startaddress, errLogEE_ptr, sizeof(errLogEE_record) );
if(res == ERR_OK) //res never was ERR_OK
errLogEE_ptr+=sizeof(errLogEE_record);
}
Sorry about the bad indentation-
I tried increasing the page size in EE241.h to 10 from 8 and it seemed to capture all the bytes in the record but the next subsequent write proved to not be functional- which makes me believe that res != ERR_OK
I have 8 such records to be written at any point of time. Logic wise- Is there an error in my approach?
Thanks.
It seems like the code is getting stuck waiting for the i2c.transmitted flag. Does this have to do with fact that I changed the Page size in the header? I seem to have no issues writing a byte/ using your test code.
You shall not change the page size in the header, you cannot change that way the how the hardware works. If the i2c.transmitted does not get set then usually your interrupts are not working?
LikeLiked by 1 person
Hi Erich,
I did check the primask register and followed if the enable and disable interrupts are functional as the code enters and exits the critical section. They seem to be operational.
Further more I have condensed my structure to be 8 bytes such that it fits snugly into the page size boundary as defined in the header. But I have a question isn’t the page write 32 bytes before the data is saved and why are we restricting the hardware to do only 8 byte writes?? Any other debug tips? Thanks
On further analysis, i see that the first block of 8 bytes gets written but the second block of 8 bytes that I want written on the address gets written, the second block of 8 bytes that I want written in the same address results in the transmitted flag getting stuck in the do..while loop. Is there a reason why this is the case? Thanks.
What if you add a delay between the 8 bytes block writes?
res = EE241_WriteBlock(0, (uint8_t*) “hello123”, sizeof(“hello123″) );
WAIT1_Waitms(5);
res = EE241_WriteBlock(1, (uint8_t*)”india101”, sizeof(“india101”) );
These are pretty much the two blocks that I am trying to write but block 2 gets stuck on the transmitted flag error. Is my first argument – address wrong? Also, my block buffer size is 8 now. if that helps. Thanks.
I don’t see anything wrong with what you do, there must be something else you are missing. Are you using my example project from GitHub?
Individual byte writes and reads work for me. It is the block writes that I am having an issue with. I am not sure if I am using the latest version of the project that you have. Let me check and get back you on that.
LikeLiked by 1 person
I have successfully used to internal Non volatile Memory and the SERIAL EEPROM for my project. Thanks for the help.
very good, congratulations!
Dear Erich,
I wanted to ask for help.
it’s days that I’m stuck on a problem.
I implemented the Kl25Z card
RTC1_SetTime (8,12,13,55); // it works great
uint8_t res, Read1;
res = EE241_Test (); // res = 0x00
if (res! = ERR_OK) {
}
res = EE241_WriteByte (0x000f, 10); // res = 0x00
res = EE241_ReadByte (0x000f, Read1); // res =?
When executing the instruction res = EE241_ReadByte (0x000f, Read1); hangs in the routine
PE_ISR (Cpu_Interrupt)
{
/ * This code can be changed using the CPU component “Build Options / Unhandled int code” * /
PE_DEBUGHALT ();
}
and it does not come out anymore.
Please could you help me?
The eeprom is a 24Lc256
Thank you very much
Can you turn on ‘one for every interrupt’ in the CPU settings (see)?
I guess you get a hard fault.
Make sure your RTC is clocked, btw.
Thanks for the reply,
I set up as you advised me, but nothing has changed, it always hangs in the same place.
If you want I can send you my project email.
Thank you very much for your help
With that change, you should see now which interrupt has fired?
nothing has changed, everything is the same as always, always stuck in the same place
Then you did not properly follow. With that setting (and if you have generated code, built and download it) you will be now in a differerent interrupt handler which tells with its name what interrupt has fired.
unfortunately, it does not always stop here PE_DEBUGHALT ();
Thank you
Could I send you my project so you can look if there’s a solution?
Thanks very much
You can, but very likely I will not be able to look into it as I’m travelling and I don’t have any hardware with me.
Why not post it on the NXP community forum? Maybe someone else can have a look too?
Ok thanks. | https://mcuoneclipse.com/2013/08/18/driver-for-microchip-24xx-serial-eeprom/?like_comment=8458&_wpnonce=82b04a8e31 | CC-MAIN-2021-04 | refinedweb | 6,813 | 73.37 |
It looks like you're new here. If you want to get involved, click one of these buttons!Sign In
It looks like you're new here. If you want to get involved, click one of these buttons!
Hello, guys. Now I retrained an Inception-v3 model to fine-tune it's output layer to 11 classes. Originally it may output 1001 classes but in our case we only need to calssify 11 classes so we retrained it.It works well but when I tried to compile it into graph some error happens and please help me.
For this model, I have a frozen .pb file and some ckpt files like model.ckpt.meta or model.ckpt.index and so on.
And in terminal, I use the command:
(tensorflow) wxy@wxy-mipro:~/Documents/TensorFLow/retrained/ckpt$ sudo mvNCCompile model.ckpt.meta -in=input -is 299 299 -o inception-V3-retrained.graph
and it outputs: 237, in parse_tensor
inputTensor = graph.get_tensor_by_name(inputnode + ':0')
File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py", line 3207, in get_tensor_by_name
return self.as_graph_element(name, allow_tensor=True, allow_operation=False)
File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py", line 3035, in as_graph_element
return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py", line 3077, in _as_graph_element_locked
"graph." % (repr(name), repr(op_name)))
KeyError: "The name 'input:0' refers to a Tensor which does not exist. The operation, 'input', does not exist in the graph."
@WuXinyang You can try using Tensorflow's summarize graph tool to check for your input and ouput nodes.. This should give you the input and output node names for your model and you can try again with the -in and -on options.
@WuXinyang I can try to help debug your issue if you can provide your files (pb, meta files). Thanks.
@WuXinyang It looks like your input node's name is:
input/BottleneckInputPlaceholder, so the entire command would be something like
mvNCCompile model.ckpt.meta -is 299 299 -in=input/BottleneckInputPlaceholder -on=softmax -o inception-V3-retrained.graph.
However it seems that we don't have support for tf.range() operation yet. Looking at tf.range(), it seems to be a copy of the python range function and you should be able to replace the tf.range in your code with a constant. For example,
tf.constant(list(range(4))).
@Tome_at_Intel , hi, thanks for your advice, I tried the summarize_graph and it outputs:
No inputs spotted.
No variables spotted.
Found 1 possible outputs: (name=final_result, op=Softmax)
Found 21842558 (21.84M) const parameters, 0 (0) variable parameters, and 99 control_edges
Op types used: 489 Const, 101 Identity, 99 CheckNumerics, 94 Relu, 94 BatchNormWithGlobalNormalization, 94 Conv2D, 11 Concat, 9 AvgPool, 5 MaxPool, 1 DecodeJpeg, 1 ExpandDims, 1 Cast, 1 MatMul, 1 Mul, 1 PlaceholderWithDefault, 1 Add, 1 Reshape, 1 ResizeBilinear, 1 Softmax, 1 Sub
So, I still did not get the inputs node's name
And when I tried the command with the outputs name:
(tensorflow) wxy@wxy-mipro:~/Documents/TensorFLow/retrained/ckpt$ sudo mvNCCompile model.ckpt.meta -in=input -on=final_result -is 299 299 -o inception-V3-retrained.graph
it will get the same KeyError. So now I think the problem must be about the inputs node?
@Tome_at_Intel Thanks!!! I upload it into my Google Drive, the share link is as below:
@Tome_at_Intel Thanks for your advice! I tried this network by using and modifying this script offered by Google:
And I checked this script, there no tf.range() is involved, so maybe some modules or packages it calls involve the tf.range()...So now I shall inspect every packages and modules it calls to check the tf.range(), right? It will be quite a huge work
..
Btw, I use tensorflow in my Conda environment with Python 2.7, and I find that your toolkit is in Python 3.6, will it be the problem?
@WuXinyang Regarding the Python issue, it should be okay because we do have support for Python 2.7 in our API now. Regarding the range issue, I'm not sure where your network is using tf.range(), but that is the issue I'm seeing on my side when I run the compile command I listed above. Can you confirm that you are getting the range error as well?
@Tome_at_Intel Yeah I got the same error like you. I'm sorry that I did not mention it before.
The error I got in my side is:
[Error 5] Toolkit Error: Stage Details Not Supported: Range
@Tome_at_Intel Hi, do you have any other suggestions for retraining a Inception-v3 model?
I ever retrained it based on the scripts offered by Google's Tensorflow Slim library. Since I was not that familiar with Tensorflow that time, so I chose to make some modifications on Slim's scripts and retrained it. I never tried to retrain it totally from scratch by my own codes.
I think maybe I can retrain it again in another way, which can avoid the tf.range() method. Do you have some advice? Thanks a lot!
@WuXinyang I think your latter plan may be the best plan of action. Let me know if you find success.
@Tome_at_Intel Hi recently, I tried one script in this page, but modified it into this way:
import numpy as np
import tensorflow as tf
from tensorflow.contrib.slim.nets import inception
slim = tf.contrib.slim
def run(name, image_size, num_classes):
with tf.Graph().as_default():
image = tf.placeholder("float", [1, image_size, image_size, 3], name="input")
with slim.arg_scope(inception.inception_v3_arg_scope()):
logits, _ = inception.inception_v3(image, num_classes, is_training=False, spatial_squeeze=False)
probabilities = tf.nn.softmax(logits)
#init_fn = slim.assign_from_checkpoint_fn('inception_v1.ckpt', slim.get_model_variables('InceptionV1'))
run('inception-v3', 299, 11)
and then I got many errors like this:
....
W tensorflow/core/framework/op_kernel.cc:1192] Not found: Key InceptionV3/Mixed_7b/Branch_0/Conv2d_0a_1x1/weights not found in checkpoint
W tensorflow/core/framework/op_kernel.cc:1192] Not found: Key InceptionV3/Mixed_7b/Branch_2/Conv2d_0c_1x3/weights not found in checkpoint
W tensorflow/core/framework/op_kernel.cc:1192] Not found: Key InceptionV3/Mixed_7b/Branch_1/Conv2d_0a_1x1/weights not found in checkpoint
W tensorflow/core/framework/op_kernel.cc:1192] Not found: Key InceptionV3/Mixed_7b/Branch_1/Conv2d_0a_1x1/BatchNorm/beta not found in checkpoint
.....
seems I need to make sure the every node of the retrained model the same as in ckpt? Do you have some new solutions now for my kind of problem? Since I noticed that many people are proposing the same questions like me in this forum: how to make retrained fune-tuned tensorflow model run on NCS? So I hope if you can develop some methods for this popular questions?
@Tome_at_Intel Btw may I ask that in the network folder which I uploaded onto Google Drive, is the output_graph.pb a frozen graph or non-frozen one? Shall I first freeze it before compile or not?
@WuXinyang Hi, pb files are considered "frozen" . For this model you are referring to, can you give me more information about the model? Is it a retrained version of the model with tf.range() removed? Or is it the same model and you are just trying to run a saver script on it?
Edit: Made a mistake. pb files can be frozen or unfrozen.
@Tome_at_Intel
So it is just a try with a saver script. This sacer script is from your website, and in your website this script is used for Inception-V1. So i think maybe i can use it for my retrained Inception-V3.
Hi, First very thanks to your fast reply.
Second, this model is the same model as the original one, namely without removing tf.range(), in fact it's kind of difficult for me to remove it
FInally and most important , with the original output_graph.pb, I just suddenly half-successfully compiled it with the following code:
(tensorflow) wxy@wxy-mipro:~/tensorflow/model$ sudo mvNCCompile output_graph.pb -s 12 -is 299 299 -in=input/BottleneckInputPlaceholder -on=final_result -o retrained.pb
And I call it half-successfully, because the output of it is only a file with 45.9kb. This file can be loaded into NCS, but i am really doubt if it really contains any useful information? Since when I tried it with my inference code seems it cannot make any right inference.
Btw, although I can compile it now, but you see, I only changed the -in and -on. I still did not remove tf.range().
And also, after this compile, there are some warning information printed as following:
(tensorflow) wxy@wxy-mipro:~/tensorflow/model$ sudo mvNCCompile output_graph.pb -s 12 -is 299 299 -in=input/BottleneckInputPlaceholder -on=final_result -o retrained.pb))
/usr/local/bin/ncsdk/Controllers/FileIO.py:52: UserWarning: You are using a large type. Consider reducing your data sizes for best performance
"Consider reducing your data sizes for best performance\033[0m")
@Tome_at_Intel
Btw, I want to say my environment is Ubuntu 17.10 and I use tensorflow in my Anaconda virtual environment with Python 2.7.
@Tome_at_Intel Hi I saw your edit today, and I want to say the output_graph.pb which I uploaded is a frozen one. I managed to use tensorflow's graph_transform tools to transform the ckpt and meta files of my retrained network into a frozen_graph.pb, and this file is exactly the same as the output_graph.pb. I use mvNCCompile to compile the frozen_graph.pb and got a same file with 45.9kb size.
@WuXinyang Are you able to run an inference with the graph file you generated?
@Tome_at_Intel Yes I can load it into NCS and get inference result, but the result is wrong. No matter I feed it any different images, it will just make one same inference, which is carrot with 100% possibility( I retrained this model for a fruits&vegetables classification problem and carrot is one class of totally 11 classes). And if I feed the same images into the network without NCS, it will output right inferences.
@WuXinyang If your network has changed since the last time you linked it to me, I'd like to try out your network again and see if I can help you out.
@Tome_at_Intel it's just that network the last time I linked to you, there is no change. The only difference is now I change the compile command:
(tensorflow) wxy@wxy-mipro:~/tensorflow/model$ sudo mvNCCompile output_graph.pb -s 12 -is 299 299 -in=input/BottleneckInputPlaceholder -on=final_result -o retrained.pb
And it output a file with 45.9kb, which is surely not right.
@Tome_at_Intel the file is just still the same as in this link:
@Tome_at_Intel Hello? Can you give me some help? The file is just the same file, but I can not get meaningful compiled file, although there is no error message at all.
@WuXinyang I'll take a look at it WuXinYang and let you know what I find. Thank you for your patience. | https://ncsforum.movidius.com/discussion/589/keyerror-the-name-input-0-refers-to-a-tensor-which-does-not-exist-when-compile-retrained-model | CC-MAIN-2018-17 | refinedweb | 1,830 | 58.99 |
Monitoring change through time using satellite imagery filmstrip plots
Background¶
Understanding how natural and human landscapes have changed through time can provide vital information about the health of local ecosystems and development of the built environment. For example, data on changes in the distribution of vegetation in the landscape can be used to monitor the impact of deforestation, or track the recovery of forests after habitat restoration or extreme natural events (e.g. bushfires). Tracking changes within urban areas can be used monitor the growth of infrastructure such as ports and transport networks, while data on coastal changes can be vital for predicting and managing the impacts of coastal erosion or the loss of coastal wetlands (e.g. mangroves).
Although these examples of change can be tracked using direct on-the-ground monitoring (e.g. vegetation surveys), it can be extremely challenging and expensive to obtain a comprehensive understanding of these processes at a broader landscape scale. For many applications, it can also be extremely useful to obtain a record of the history of a location undergoing change. This typically requires historical monitoring data which is unlikely to be available for all but the most intensively monitored locations.
Digital Earth Australia use case¶
More than 30 years of satellite imagery from the NASA/USGS Landsat program is freely available for Australia, making this a powerful resource for monitoring natural and human-driven change across the Australian continent. Because these satellites image every location over Australia regularly (approximately once every 16 days), they provide an unparalleled archive of how many of Australia’s landscapes have changed through time.
Analysing change from individual satellite images can be made difficult by the presence of clouds, cloud shadow, sunglint over water, and dynamic processes like changing tides along the coastline. By combining individual noisy images into cleaner, cloud-free “summary” images that cover a longer time period (e.g. one or multiple years), we can obtain a clear, consistent view of the Australian environment that can be compared to reveal changes in the landscape over time.
Description¶
In this example, Digital Earth Australia Landsat data is extracted for a given time range and location, and combined using the geometric median (“geomedian”) statistic to reveal the median or ‘typical’ appearance of the landscape for a series of time periods (for more information about geomedians, see the Geomedian composites notebook).
For coastal applications, the analysis can be customised to select only satellite images obtained during a specific tidal range (e.g. low, average or high tide).
The results for each time period are combined into a ‘filmstrip’ plot which visualises how the landscape has changed in appearance across time, with a ‘change heatmap’ panel highlighting potential areas of greatest change:
Getting started¶
To run this analysis, run all the cells in the notebook, starting with the “Load packages” cell.
Load packages¶
Import Python packages used for the analysis.
[1]:
%matplotlib inline from datacube.utils.cog import write_cog import sys sys.path.insert(1, '../Supplementary_data/') from notebookapp_changefilmstrips import run_filmstrip
The following cell sets important required parameters for the analysis:
output_name: A name that will be used to name the output filmstrip plot file
time_range: The date range to analyse (e.g.
time_range = ('1988-01-01', '2017-12-31'))
time_step: This parameter allows us to choose the length of the time periods we want to compare (e.g.
time_step = {'years': 5}will generate one filmstrip plot for every five years of data in the dataset;
time_step = {'months': 18}will generate one plot for each 18 month period etc. Time periods are counted from the first value given in
time_range.
Optional parameters:
tide_range: This parameter allows you to generate filmstrip plots based on specific ocean tide conditions. This can be valuable for analysing change consistently along the coast. For example,
tide_range = (0.0, 0.2)will select only satellite images acquired at the lowest 20% of tides;
tide_range = (0.8, 1.0)will select images from the highest 20% of tides. The default is
tide_range = (0.0, 1.0)which will select all images regardless of tide.
resolution: The spatial resolution to load data. The default is
resolution = (-30, 30), which will load data at 30 m pixel resolution. Increasing this (e.g. to
resolution = (-100, 100)) can be useful for loading large spatial extents.
max_cloud: This parameter allows you to exclude satellite images with excessive cloud. The default is
50, which will keep all images with less than 50% cloud.
ls7_slc_off: Whether to include data from after the Landsat 7 SLC failure (i.e. SLC-off). Defaults to
False, which removes all Landsat 7 observations after May 31 2003. Setting this to
Truewill result in extra data, but can also introduce horizontal striping in the output filmstrip plots.
If running the notebook for the first time, keep the default settings below. This will demonstrate how the analysis works and provide meaningful results.
[2]:
# Required parameters output_name = 'example' time_range = ('1988-01-01', '2017-12-31') time_step = {'years': 5} # Optional parameters tide_range = (0.0, 1.0) resolution = (-30, 30) max_cloud = 80 ls7_slc_off = False
Select location and generate filmstrips¶
Run the following cell to start the analysis. This will plot an interactive map that is used to select the area to load satellite data for.
Select the
Draw a rectangle or
Draw a polygon tool on the left of the map, and draw a shape around the area you are interested in.
For the first run, try drawing a square around Sydney Airport and Port Botany to see an example of change driven by urban and coastal development.
When you are ready, press the green
done button on the top right of the map. This will start loading the data, and then generate a filmstrips plot.
Depending on the size of the area you select, this step can take several minutes to complete. To keep load times reasonable, select an area smaller than 200 square kilometers in size (this limit can be overuled by supplying the
size_limitparameter in the
run_filmstrip_appfunction below).
Once the analysis reaches the
Generating geomedian compositesstep, you can check the status of the data load by clicking the Dashboard link under Client below.
[3]:
geomedians, heatmap = run_filmstrip_app(output_name, time_range, time_step, tide_range, resolution, max_cloud, ls7_slc_off)
Starting analysis...
Finding datasets ga_ls5t_ard_3 ga_ls7e_ard_3 (ignoring SLC-off observations) ga_ls8c_ard_3 Applying pixel quality/cloud mask Returning 737 time steps as a dask array Generating geomedian composites and plotting filmstrips... (click the Dashboard link above for status)
Using filmstrip plots to identify change¶
The filmstrip plot above contains several colour imagery panels that summarise the median or ‘typical’ appearance of the landscape for the time periods defined using
time_range and
time_step. If you ran the analysis over the Sydney Airport and Port Botany area, inspect each of the imagery plots. Some key examples of change that appear include:
The 1994 construction of Sydney Airport’s third runway in the second panel (covering the five year period between 1993 and 1998)
The 2011 expansion of Port Botany visible as construction in the fifth panel, and completed by the sixth panel
Increasing commercial and industrial development (e.g. large white roofs) in the suburb of Mascot north of Port Botany
Change heatmap¶
To make it easier to identify areas that have changed between each filmstrip panel, the final panel provides a “change heatmap”. This highlights pixels whose values vary greatly between the panels in the filmstrip plot. Bright colours indicate pixels that have changed; dark colours indicate pixels that have remained relatively similar across time.
Compare the “change heatmap” panel against the colour imagery panels. You should be able to clearly see Sydney Airport’s third runway and the Port Botany port expansion highlighted in bright colours.
Technical info: The “change heatmap” is calculated by first taking a log transform of the imagery data to emphasize dark pixels, then calculating standard deviation across all of the filmstrip panels to reveal pixels that changed over time.
Downloading filmstrip plot¶
The high resolution version of the filmstrip plot generated above will be saved to the same location you are running this notebook from (e.g. typically
Real_world_examples). In JupyterLab, use the file browser to locate the image file with a name in the following format:
filmstrip_{output_name}_{date_string}_{time_step}.png
If you are using the DEA Sandbox, you can download the image to your PC by right clicking on the image file and selecting
Download.
Export GeoTIFF data¶
It can be useful to export each of the filmstrip panels generated above as GeoTIFF raster files so that they can be loaded into a Geographic Information System (GIS) software for further analysis. Because the filmstrip panels were generated using the “geomedian” statistic that preserves relationships between spectral bands, the resulting data can be validly analysed in the same way as we would analyse an individual satellite image.
To export the GeoTIFFs, run the following cell then right click on the files in the JupyterLab file browser and select
Download.
[4]:
# Export filmstrip panels for i, ds in geomedians.groupby('timestep'): print(f'Exporting {i} data') write_cog(geo_im=ds.to_array(), fname=f'geotiff_{output_name}_{i}.tif', overwrite=True) # Export change heatmap print('Exporting change heatmap') write_cog(geo_im=heatmap, fname=f'geotiff_{output_name}_heatmap.tif', overwrite=True)
Exporting 1988-01-01 data Exporting 1993-01-01 data Exporting 1998-01-01 data Exporting 2003-01-01 data Exporting 2008-01-01 data Exporting 2013-01-01 data Exporting change heatmap
[4]:
PosixPath('geotiff_example_heatmap.tif')
Next steps¶
When you are done, return to the Analysis parameters section, modify some values and rerun the analysis. For example, you could try:
Modify
time_rangeto look at a specific time period of interest (e.g.
time_range = ('1990-01-01', '2000-01-01').
Setting a shorter
time_step(e.g.
time_step = {'years': 2}) for a more detailed look at how the landscape has changed over shorter time periods.
Inspecting change along the coastline after controlling for tide using the
tide_rangeparameter (e.g.
tide_range = (0.0, 0.3)to look at the landscape during the lowest 30% of tides). For the best results, test this out in an area with high tides such as Roebuck Bay in West Australia’s Kimberley:
[5]:
import datacube print(datacube.__version__)
1.8.5
Browse all available tags on the DEA User Guide’s Tags Index
Tags: NCI compatible, sandbox compatible, landsat 5, landsat 7, landsat 8, load_ard, mostcommon_crs, tidal_tag, rgb, image compositing, geomedian, filmstrip plot, change monitoring, real world, widgets, interactive, no_testing | https://docs.dea.ga.gov.au/notebooks/Real_world_examples/Change_filmstrips.html | CC-MAIN-2022-05 | refinedweb | 1,743 | 50.97 |
This translation is incomplete. Please help translate this article from English
本教程擴充了 LocalLibrary 網站,為書本與作者增加列表與細節頁面。此處我們將學到通用類別視圖,並演示如何降低你必須為一般使用案例撰寫的程式碼數量。我們也會更加深入 URL 處理細節,演示如何實施基本模式匹配。
Overview
本教程中,通過為書本和作者添加列表和詳細信息頁面,我們將完成第一個版本的 LocalLibrary 網站(或者更準確地說,我們將向您展示如何實現書頁,並讓您自己創建作者頁面!) )
該過程在創建索引頁面,我們在上一個教程中展示了該頁面。我們仍然需要創建URL地圖,視圖和模板。主要區別在於,對於詳細信息頁面,我們還有一個額外的挑戰,即從URL對於這些頁面,我們將演示一種完全不同的視圖類型:基於類別的通用列表和詳細視圖。這些可以顯著減少所需的視圖代碼量,有助於更容易編寫和維護。
本教程的最後一部分,將演示在使用基於類別的通用列表視圖時,如何對數據進行分頁。
Book list page
該書將顯示每條記錄的標題和作者,標題是指向相關圖書詳細信息頁面的超鏈接。該頁面將具有與站點中,所有其他頁面相同的結構和導航,因此,我們可以擴展在上一個教程中創建的基本模板 (base_generic.html)。
URL mapping
開啟/catalog/urls.py,並複製加入下面粗體顯示的代碼。就像索引頁面的方式,這個path()函數,定義了一個與URL匹配的模式('books /'),如果URL匹配,將調用視圖函數(views.BookListView.as_view())和一個對應的特定映射的名稱。
urlpatterns = [ path('', views.index, name='index'), path('books/', views.BookListView.as_view(), name='books'), ]
正如前一個教程中所討論的,URL必須已經先匹配了/ catalog,因此實際上將為URL調用的視圖是:/ catalog / books /。
我們將繼承現有的泛型視圖函數,該函數已經完成了我們希望此視圖函數執行的大部分工作,而不是從頭開始編寫自己的函數。對於基於Django類的視圖,我們通過調用類方法as_view(),來訪問適當的視圖函數。由此可以創建類的實例,並確保為HTTP請求正確的處理程序方法。
View (class-based)
我們可以很容易地,將書本列表列表編寫為常規函數(就像我們之前的索引視圖一樣),進入查詢數據庫中的所有書本,然後調用render(),將列表傳遞給指定的模板。然而,我們用另一種方法取代,我們將使用基於類的通用列表視圖(ListView)-一個繼承自現有視圖的類。因為通用視圖,已經實現了我們需要的大部分功能,並且遵循Django最佳實踐,我們將能夠創建更強大的列表視圖,代碼更多,重複次數最多,最終維護所需。
開啟catalog / views.py,將以下代碼複製到文件的底部:
from django.views import generic class BookListView(generic.ListView): model = Book
就是這樣!通用視圖將查詢數據庫,以獲取指定模型(Book)的所有記錄,然後呈現/locallibrary/catalog/templates/catalog/book_list.html的模板(我們將在下面創建)。在模板中,您可以使用所謂的object_list或book_list的模板變量(即通常為“ the_model_name_list”),以訪問書本列表。
Note: This awkward path for the template location isn't a misprint — the generic views look for templates in
/application_name/the_model_name_list.html (
catalog/book_list.html in this case) inside the application's
/application_name/templates/ directory (
/catalog/templates/).
您可以添加屬性,以更改上面的某種行為。例如,如果需要使用同一模型的多個視圖,則可以指定另一個模板文件,或者如果book_list對於特定模板用例不直觀,則可能需要使用不同的模板變量名稱。可能最有用的變更,是更改/過濾返回的結果子集-因此,您可能會列出其他用戶閱讀的前5本書,而不是列出所有書本。
雖然我們不需要在這裡執行此操作,但您也可以覆寫某些類別方法。
例如,我們可以覆寫get_queryset()方法,來更改返回的記錄列表。這比單獨設置queryset屬性更靈活,就像我們在前面的代碼片段中進行的那樣(儘管在這案例中沒有太大用處): not just to an integer, and pass it to the view as a parameter named
pk (short for primary key). scary!
Lets consider a few real examples of patterns:
You can capture multiple patterns in the one match, and hence encode lots of different information in a URL.
Note: As a challenge, consider how you might encode). list of books') # from django.shortcuts import get_object_or_404 # book = get_object_or_404(Book, pk=primary_key)).
Note: The
get_object_or_404() (shown commented out above) is a convenient shortcut to raise an
Http404 exception if the record is not found.> {% for genre in book.genre.all %} {{ genre }}{% if not forloop.last %}, {% endif %}{% endfor %}< %}
The author link in the template above has an empty URL because we've not yet created an author detail page. Once that exists, you should update the URL like this:
<a href="{% url 'author-detail' book.author.pk %}">{{ book.author }}</a>. Since you don't do anything to declare the relationship in the other ("many") model, it didn't reach Pagination (yet, but soon enough),.
And last, but not least, you should sort by an attribute/column that actually has a index (unique or not) on your database to avoid performance issues. Of course, this will not be necessary here (and we are probably getting ourselves too much ahead) if such small amount of books (and users!), but it is something to keep in mind for future projects.-built"> <p>Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.</p> <.
Thats behaviour. line will change to add the template tag shown in bold below.
<p><strong>Author:</strong> <a href="{% url 'author-detail' book.author.pk %}">{{ managable | https://developer.cdn.mozilla.net/zh-TW/docs/Learn/Server-side/Django/Generic_views | CC-MAIN-2020-05 | refinedweb | 485 | 51.24 |
Apr 07, 2016 05:40 PM|NXTwoThou|LINK
Our shop has been incredibly behind the times(mostly due to finances) and outside factors are finally forcing the boss to spend money on replacing our aging servers(aka, UPS integration won't work with Server 2003 past May 2016 due to SSL). I'm almost ready to swap out one of our three Server 2003 boxes with the Server 2012R2 box I've been setting up but discovered a huge issue that I've not figure out how to solve yet.
We have admin tools that create websites dynamically. The first task in this is finding out the next available SiteID that we can use on all of the servers. Here's the code:
private int GetMaxSiteID(string WebServer, string UserName, string Password)
{
int MaxSiteID = 1;
using (DirectoryEntry root = new DirectoryEntry("IIS://" + WebServer + "/W3SVC", WebServer + "\\" + UserName, Password, AuthenticationTypes.FastBind))
{
foreach (DirectoryEntry e in root.Children)
{
if (e.SchemaClassName == "IIsWebServer")
{
int ID = Convert.ToInt32(e.Name);
if (ID >= MaxSiteID)
MaxSiteID = ID + 1;
}
}
}
return MaxSiteID;
}
I'd just call GetMaxSiteID("WebServer1","MyUserName","MyPassword") and I could get my next available SiteID. I'd run this for all three web servers and get my results in about 6 seconds when run from any of the two Server 2003 boxes and the one Server 2003R2 box. I have slightly altered code that's thread safe and I get it down to about 3 and a half seconds on the production machines. Slightly longer if I switch from FastBind to Secure.
When I run this on the new Server2012R2 box, it takes around *200* seconds to run when connecting to the Server 2003 machines and 100 seconds for the Server 2003R2 box and 19 seconds just to run on itself! The insane part is when I use the Server 2003 box to connect to the Server 2012R2 box, it only takes 2.5 seconds, why would the reverse take 224 seconds?
I figured I had some wrong code somewhere, so I ran it in debug mode on my Windows 10 machine and ended up getting even worse results! What am I missing here? I'm used to upgrading giving me performance improvements, not making the whole thing unusable. I could possibly rewrite the code for WMI, but considering the plan of attack on these servers is to swap a box out and repurpose the outgoing one, I'm going to be a mixed environment for several weeks. I'm hoping it's just some setting I need to turn on to get it to perform like it did under Server 2003.
Here's my timing numbers to show why it feels crazy.
Count of sites is 560
WebServer1 Server 2003
WebServer2 Server 2003
WebServer3 Server 2003R2
WebServer5 Server 2012R2
DevMachine Windows 10 16042-2217
WS1 running on WebServer1 0.859
WS2 running on WebServer1 3.500
WS3 running on WebServer1 2.391
WS5 running on WebServer1 2.531
WS1 running on WebServer2 5.000
WS2 running on WebServer2 1.640
WS3 running on WebServer2 3.922
WS5 running on WebServer2 4.031
WS1 running on WebServer3 3.156
WS2 running on WebServer3 4.328
WS3 running on WebServer3 0.781
WS5 running on WebServer3 1.609
WS1 running on WebServer5 214.047
WS2 running on WebServer5 198.594
WS3 running on WebServer5 92.812
WS5 running on WebServer5 19.250
WS1 running on DevMachine 224.620
WS2 running on DevMachine 314.421
WS3 running on DevMachine 142.573
WS5 running on DevMachine 161.133
Apr 07, 2016 08:41 PM|bbcompent1|LINK
There could literally be a hundred different things here but my first question is about the new server hardware.
It is not as simple as saying "Oh, this is probably what is causing you grief..." Generally, there are underlying symptoms that cause the problem. I suspect the server is low on memory; when ordering memory, I always max the machine out and never grab just the bare minimum to get the OS to load. That is always a bad idea. High spindle speed hard drives (10K+) always help. Having at least 2 processors with hyperthreading helps increase the speed. Post back with your configuration and lets see what we can do to get you up to speed.
Apr 07, 2016 11:25 PM|NXTwoThou|LINK
That's the thing that's easy to miss. I had issues with the new server so I tried it on my development machine. Same insane slowdown. I don't think it's the hardware, I think it's the OS. For reference, my development machine is a Core i7-3770 with 32GB. The 2TB drive is a spinner and isn't particularly fast. The Server 2012R2 machine is a Xeon X5355 with 8GB and a SSD. The one Server 2003 machine that's close by is a Core 2 Duo with 4GB. The other two are pretty much the same. One running Server2003R2 is RAID1, the other two are a single spinning drive(SATA).
After an employee left, I was able to pull up VS2008 on his Vista machine and run the code from there because of my OS suspicion.
WS1 running on Vista 8.1432s
WS2 running on Vista 8.0496s
WS3 running on Vista 2.34s
WS5 running on Vista 8.0652s
Unfortunately I don't have windows 7 machine to try this on. This Vista machine is pretty pathetic, btw, I'm honestly surprised it had such a low time to the Server2003R2 machine.
To summarize. If I use a Server 2003, Server 2003R2, or Vista machine to grab all the SiteIDs from the Server 2012R2 machine, it takes 8 seconds or less. When I use the Server 2012R2 machine to grab it's own SiteIDs, it takes 19 seconds. If I use either of the Server 2003 machines or the Server 2003R2 machine to connect to each other, I can get the SiteIDs in under 5 seconds. If I use the Server 2012R2 machine or my Windows 10 machine to get the SiteIDs from any of the Server 2003 or 2003R2 machines, it takes 100 to 200 seconds. Using my Windows 10 machine to get the SiteIDs from the Server 2012R2 machine takes 161 seconds.
Apr 07, 2016 11:51 PM|NXTwoThou|LINK
I have VirtualBox on my dev machine with an XP VM(it has Borland C++ 4.02 and Visual Studio 2003 on it for maintaining some creepy old code). I could pretty quickly in the morning put Visual Studio 2008 on it and run the same sample code I did on the Vista machine. Would that satisfy the hardware question?
Apr 08, 2016 11:16 AM|bbcompent1|LINK
Hm, that is indeed curious. I would recommend you run a memory test on those machines, just to rule it out. There is a possibility that you may be running 64-bit windows on a 32-bit system. That would make the bloody thing crawl - speaking from experience :) Can you check the OS to ensure you are not running that way? Windows Server 2012 R2 requires a 64 bit platform but I have seen some able to run it on 32-bit. Check that and get back to me.
Apr 08, 2016 11:20 AM|bbcompent1|LINK
You might remember me mentioning Hyper-V on the server, run through this article and check the hyperthreading/memory configuration: I can attest to the fact if these guys are misconfigured, it will be slow as dirt (like running a X486 machine) Let me know if any of these tips helped.
Apr 08, 2016 12:50 PM|NXTwoThou|LINK
Hyper-V is not enabled on the Server 2012R2, nor is it on my development machine(W10 Home). Zero other performance issue with either 2012R2 or W10. I turned my code into a console app so I could run it in VirtualBox. Here's my numbers for my development machine.
WebServer3 1947902744(560) took 125.2647592s
WebServer5 1947902744(560) took 128.763759s
WebServer1 1947902744(560) took 204.8024641s
WebServer2 1947902744(560) took 224.6752318s
Here's the same program running on my XP VirtualBox VM.
WebServer3 1947902744(560) took 2.8927188s
WebServer5 1947902744(560) took 2.4523135s
WebServer1 1947902744(560) took 3.9160863s
WebServer2 1947902744(560) took 4.4755272s
Obviously not a hardware issue.
I need to point out again that from XP to Server2012R2, it only took 2.5 seconds. Windows 10 to Server2012R2 it took 128.8 seconds. Server2012R2 to itself just now, 22.2 seconds.
Since it's a program, I'm able to dump it on more machines around here to test with. Two more XP machines, exact same sub 6 second results. Two Windows 10 machines, same over 100 second results. I've got a Server 2008R2 machine, but I'm getting the unhelpful "Unknown error( 0x80005000)", so I'm unable to test the speed with that until I figure out the error.
Apr 08, 2016 01:10 PM|NXTwoThou|LINK
Server 2008R2
WebServer5 1947902744(560) took 6.6456117s
WebServer3 1947902744(560) took 7.0044123s
WebServer1 1947902744(560) took 7.4568131s
WebServer2 1947902744(560) took 7.7844137s
Apr 08, 2016 01:35 PM|NXTwoThou|LINK
I got the components installed on our other Server2012R2 machine(replacement SQL Server that's not ready yet. Two physical CPUs, 32GB ram, 5 disk array). It's the last machine I have to play with unless I bring my W10 notebook from home.
WebServer5 1947902744(560) took 61.312415s
WebServer3 1947902744(560) took 95.9423441s
WebServer1 1947902744(560) took 196.162926s
WebServer2 1947902744(560) took 279.1365475s
I added some lower level info..
Here's the timings during calls on Server2003 to Server2012R2.
DirectoryEntry root = new DirectoryEntry 46.8861ms
DirectoryEntry e in root.Children 328.2027
Pretty consistent pattern all the way to the end. Here's the same thing on my Windows 10 machine(which is about the same on all the other newer machines).
DirectoryEntry root = new DirectoryEntry 15.6294ms
DirectoryEntry e in root.Children 731.6665ms
DirectoryEntry e in root.Children 153.2571ms
DirectoryEntry e in root.Children 146.7677ms
DirectoryEntry e in root.Children 153.2511ms
DirectoryEntry e in root.Children 147.1619ms
DirectoryEntry e in root.Children 168.8826ms
DirectoryEntry e in root.Children 162.8028ms
DirectoryEntry e in root.Children 137.689ms
DirectoryEntry e in root.Children 162.3126ms
DirectoryEntry e in root.Children 153.68ms
DirectoryEntry e in root.Children 147.216ms
DirectoryEntry e in root.Children 153.6665ms
DirectoryEntry e in root.Children 146.7686ms
DirectoryEntry e in root.Children 153.4868ms
DirectoryEntry e in root.Children 165.9102ms
DirectoryEntry e in root.Children 150.1817ms
DirectoryEntry e in root.Children 153.6632ms
DirectoryEntry e in root.Children 146.7526ms
DirectoryEntry e in root.Children 168.8699ms
DirectoryEntry e in root.Children 147.1472ms
DirectoryEntry e in root.Children 153.235ms
DirectoryEntry e in root.Children 162.7893ms
DirectoryEntry e in root.Children 138.05ms
DirectoryEntry e in root.Children 162.7808ms
This has got to be some sort of caching/authorization-retry thing that's different with the newer OSs.
All-Star
32809 Points
Microsoft
Apr 10, 2016 02:12 AM|Angie xu - MSFT|LINK
Hi,
You could try Windows Performance Monitor, and check whether this is OS issue, or application specific.
In the navigation tree, expand Monitoring Tools , and then click Performance Monitor.
For more information about using Windows Performance Monitor, see.
Moreover, I think you can also get help from Microsoft support () directly, Microsoft support engineers will evaluate this seriously, and they will give positive response about this issue.
Have a good day.
Regards,
Angie
Apr 11, 2016 01:37 PM|NXTwoThou|LINK
What counters are you wanting me to profile for you?
I'm unsure what you mean by "application specific" as the same application has been used on at least 12 machines so far. The only performance issue I have is on Windows 10 or Server 2012R2 machines(note, have no Windows 7, 8, 8.1, nor anything less than XP to test with.)
Apr 11, 2016 01:41 PM|NXTwoThou|LINK
As for contacting support.microsoft.com. We do not have the funds for the $499 support incident. As the original post stated, we've taken this long to upgrade due to lack of funds. We're making due to ebay purchases here. It'd be great to be a large shop, but we aren't one. I was hoping someone ran into this issue when they did their own upgrade and it was some simple setting in newer versions of Windows that I just didn't know the correct search terms to find.
Apr 11, 2016 03:27 PM|bbcompent1|LINK
NX, I suspect the problem is the swap (virtual) memory setting is too high. Can you check in the following area please?
Right Click My Computer
> properties
> Advanced Systems Settings
> Performance Settings
> Visual Effects (Tab) - Adjust for best performance
> Advanced (Tab) - Processor scheduling > Best Performance
- Virtual Memory (Paging File) > Set to 2048
Reboot and see if it is any better.
Apr 11, 2016 03:52 PM|NXTwoThou|LINK
I set "Adjust for best performance" under Visual Effects, "Adjust for best performance of: Programs" under Advanced, turned off Automatically manage paging file and set the custom initial and max size to 2048 on my development machine and reran the test. As I suspected, exactly the same results. Since this machine has 32GB of ram and task manager shows I'm currently using 3.3GB, I was pretty sure it wasn't a swap file issue. Considering I've run this test on multiple machines with wildly different hardware and the one consistent issue is which version of Windows it's running I didn't expect it to make a difference. I don't see a point in running the same test on the other machines.
This issue does not happen on one computer. It happens on multiple Windows 10 and multiple Server 2012R2 machines. It does not happen on multiple Server 2008R2, Server 2003, Vista, nor XP machines. I do not have Windows 7, 8, Server2012, nor 8.1 machines to test with. I suspect 7 will perform just like the Server2008R2 machines though. It's 50/50 if the 8 will. I suspect they'll act like 10 and 2012R2.
Here's the results of that run using your settings before I canceled it.
DirectoryEntry root = new DirectoryEntry 0ms
DirectoryEntry e in root.Children 4865.1404ms
DirectoryEntry e in root.Children 377.9744ms
DirectoryEntry e in root.Children 363.5256ms
DirectoryEntry e in root.Children 353.7015ms
DirectoryEntry e in root.Children 331.405ms
DirectoryEntry e in root.Children 401.2427ms
DirectoryEntry e in root.Children 352.2134ms
DirectoryEntry e in root.Children 300.3224ms
DirectoryEntry e in root.Children 284.9306ms
DirectoryEntry e in root.Children 316.2555ms
DirectoryEntry e in root.Children 321.8109ms
Here's the source for what I'm using so it's easy for someone else to apply it to their own server
using System; using System.DirectoryServices; namespace IISNewSiteID { class Program { static void Main(string[] args) { if (args == null || args.Length != 3) { Console.WriteLine("IISNewSiteID.exe WebServer UserName Password"); Console.WriteLine("Example: IISNewSiteID WebServer1 WebServer1\\MyUserName MyPassword"); } else { DateTime dt = DateTime.Now; int MaxSiteID = 1; using (DirectoryEntry root = new DirectoryEntry("IIS://" + args[0] + "/W3SVC", args[1], args[2], AuthenticationTypes.FastBind)) { Console.WriteLine("DirectoryEntry root = new DirectoryEntry " + DateTime.Now.Subtract(dt).TotalMilliseconds + "ms"); DateTime dt2 = DateTime.Now; foreach (DirectoryEntry e in root.Children) { Console.WriteLine("DirectoryEntry e in root.Children " + DateTime.Now.Subtract(dt2).TotalMilliseconds + "ms"); dt2 = DateTime.Now; if (e.SchemaClassName == "IIsWebServer") { int ID = Convert.ToInt32(e.Name); if (ID >= MaxSiteID) MaxSiteID = ID + 1; } } } Console.WriteLine("Next available SiteID " + MaxSiteID + " took " + DateTime.Now.Subtract(dt).TotalSeconds + "s "); } } } }
Here's a onedrive link to a zip file that has the project, source, and .NET 4.0 framework compiled version of it(I've tried 2.0, 4.0, and 4.6(on the newer machines only)).
Apr 11, 2016 08:06 PM|bbcompent1|LINK
This one is definitely beyond my skill set at this point. You've done everything I would have tried to this point. To be honest, I have not seen the more recent versions of Windows Server do this. A suggestion I had was maybe you could find a PowerShell script that performs this function? Generally PS is considerably faster than running a compiled console application as I have seen. Plus in the PS script, you could have it call out to a function that builds the site based on the ID generated from the query.
Apr 12, 2016 02:01 PM|NXTwoThou|LINK
I got confirmation in another forum that it was reproducible elsewhere. They suggested creating a MS Connect bug report for it.
Apr 12, 2016 04:25 PM|bbcompent1|LINK
Ok, great. At least now we are aware of this being a bug. I'll be on the look out for a patch whenever they come out with one. Good find!
Apr 27, 2018 03:29 PM|NXTwoThou|LINK
Just for reference, it's April 2018 and got a new Server 2016 machine in. Exact same issue(I had to use IISCrypto to be able to enable insecure enough security temporarily to test). It takes me 180 seconds to find out what I could use for my next SiteID. Since I'm needing to update all the code to do a 4th web server in the mix, I'm just going to store a database entry of the last ID and lay down the law about no one adding sites manually(without updating the database after). So insanely stupid this issue exists.
All-Star
41010 Points
Apr 27, 2018 04:16 PM|PatriceSc|LINK
Hi,
You could try or to see if it makes a difference...
Edit: could also perhaps help ??? To clarify I'm not suggesting a fix but I believe it could be interesting to see if going through LDAP is involved (not sure thought what is used behind the scene). BTW I'm not sure to get why you need to get the last id before creating a site.
Apr 27, 2018 05:12 PM|NXTwoThou|LINK
Note the server versions listed in the original post, Microsoft.Web.Administration doesn't work with the older IIS. Older IIS also required SiteID to be supplied on new sites. It's also for a web farm and there was a commandment layed down a long time ago for keeping siteid's the same on all servers.
The core issue is that different versions of windows have a -tremendous- performance impact. My posting was to try and determine why and how to fix. More importantly, I was trying to pass word on to MS that there was an issue that needed fixing and giving sample code to be able to test with(I'm very sad Connect went away, not that my post there had anything besides "looking into it").
Technically, we don't have any of the W2k3 machines anymore(down to 2008R2/2012R2/2016), so I could potentially rewrite everything to use Microsoft.Web.Administration. From what I understand, I'll have a firewall nightmare to deal with(wee for random port assignments) and get to write a bunch of impersonation code(web farm, any of the 4 servers could have someone trying to create a new site on all 4). It's doable and I thank you for pointing it out, but, it doesn't solve the core issue.
All-Star
41010 Points
Apr 27, 2018 05:53 PM|PatriceSc|LINK
Sometimes I'm doing that without telling but this time I tried ;-)
This is NOT to suggest a fix. I often like to gather or check things before going in a direction or rather than trying to guess. So my goal here is to understand if it is related to going through the LDAP IIS provider. I would just for example rewrite the snippet of code you shown. Then maybe I would try to check a query about users or whatever to see how it behaves.
If it is on the LDAP side I would then try rather a Windows admin forum. Ah is the IIS 6 compatiblity feature required for this ? Could it be this extra layer that is slowing down things ?
Edit: according to it is required and it seems this is just for portability.
Apr 27, 2018 06:25 PM|NXTwoThou|LINK
I just a quicky test on what I've got now(two 2008R2, one 2012R2, one 2016, and my W10 dev box) There's quite a few more sites than there were previously.
2008R2 connecting to IIS on 2008R2, 2012R2, 2016 gets the next enumeration in DirectoryEntry Children is 0ms. Every 4th or 5th, it's 15ish ms.
2012R2, 2016, 10 connecting to IIS on 2008R2, 2012R2, 2016 gets the next in 150+ ms, every time.
What's -really- sad? On the same machine(not over the network), 2012R2/2016 take 30+ ms. I can enumerate IIS sites faster from a remote 2008R2 machine than directly on the machine.
21 replies
Last post Apr 27, 2018 06:25 PM by NXTwoThou | https://forums.asp.net/t/2092155.aspx?Compared+to+WS2003+WS2012R2+and+W10+are+extremely+slow+accessing+IIS+Am+I+missing+something+ | CC-MAIN-2018-30 | refinedweb | 3,542 | 67.35 |
JavaFX Tutorial for Beginners - Hello JavaFX
1- The requires
- In this post, I will guide you to perform the JavaFX programming on IDE Eclipse.
e(fx)eclipse
- e(fx)clipse is a set of tools and necessary libraries which helps you to perform the JavaFX programming, let's be sure that you have installed it as a Plugin for eclipse. If the e(fx)clipse is not installed , you can see guidance at:
-
JavaFX Scene Builder
- JavaFX Scene Builder is a visual design tool which allows you to create an application interface quickly by dragging and dropping. And the code is created as XML. This is an option in order to perform the JavaFX programming, you should install it.
- If not install JavaFX Scene Builder, you can see the instructions at:
-
2- Create Hello World Project
- In Eclipse select:
- File/New/Others..
- Project is created:
- The Code of the Hello World example is also created.
- First of all, let's be sure that you run the example of Hello World successfully. Right click on Main class and select:
- Run As/Java Application
- The application of Hello World JavaFX is running:
3- Explanation of Hello World Example
- In the above step, you have created and run Hello World JavaFX successfully.
- The below illustration shows the relationship between Stage, Scene, Container, Layout and Controls:
- In JavaFX, Stage is the application window, which contains the space called as Scene. Scene contains the components of the interface such as Button, Text,... or containers.
4- JavaFX Scene Builder
- In order to create a JavaFX application interface, you can write code in Java entirely. However, it takes so much time to do this, JavaFX Scene Builder is a visual tool allowing you to design the interface of Scene. The code which is generated, is XML code saved on *.fxml file.
5- Example with JavaFX Scene Builder
- This is a small example, I use Scene Builder to design application interface. The model of MVC applied to the example is illustrated as below:
- After seeing it on VIEW
- Users use CONTROLLER
- Manipulate data (Update, modify, delete, ..), the data on MODEL has been changed.
- Displaying the data of MODEL on VIEW.
- Preview the example:
- File/New/Other...
- MyScene.fxml file is created.
- You can open the fxml file with JavaFX Scene Builder.
- Note: You are sure that you have installed JavaFX Scene Builder, and integrated it into Eclipse.
- The screen of My Scene.fxml interface design:
- The components located on the Scene:
- Finding Button and dragging it into AnchorPane:
- Set ID for Button as "myButton", you can have access to the Button from Java code via its ID. Set the method will be called when the button is clicked.
- Dragging and dropping TextField into AnchorPane. Set ID for TextField which is newly dragged and dropped into AnchorPane as "myTextField", you can have access to the TextField on Java code via its ID.
- Selecting File/Save to save the changes. And selecting Preview/Show Preview in Window to preview your design.
- Closing Scene Builder windows and refreshing Project on Eclipse. You can see the code generated on the MyScene.fxml file:
- Adding the attribute fx:controller to <AnchorPane>, the Controller will be useful to the Controls lying inside AnchorPane such as myButton and myTextField.
- Note: org.o7planning.javafx.MyController class will be created later.
Controller
- MyController.java
package org.o7planning.javafx; import java.net.URL; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.TextField; public class MyController implements Initializable { @FXML private Button myButton; @FXML private TextField myTextField; @Override public void initialize(URL location, ResourceBundle resources) { // TODO (don't really need to do anything here). } // When user click on myButton // this method will be called. public void showDateTime(ActionEvent event) { System.out.println("Button Clicked!"); Date now= new Date(); DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss.SSS"); // Model Data String dateTimeString = df.format(now); // Show in VIEW myTextField.setText(dateTimeString); } }
- MyApplication.java
package org.o7planning.javafx; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; public class MyApplication extends Application { @Override public void start(Stage primaryStage) { try { // Read file fxml and draw interface. Parent root = FXMLLoader.load(getClass() .getResource("/org/o7planning/javafx/MyScene.fxml")); primaryStage.setTitle("My Application"); primaryStage.setScene(new Scene(root)); primaryStage.show(); } catch(Exception e) { e.printStackTrace(); } } public static void main(String[] args) { launch(args); } }
- Running MyApplication class: | http://o7planning.org/en/10623/javafx-tutorial-for-beginners | CC-MAIN-2017-04 | refinedweb | 763 | 52.05 |
Most discussion is on Typelevel Discord:
@Avasil bingo, thanks a lot :) Now it's giving unrelated error, which I expected :) neat
regarding
() => F[Unit] vs
F[Unit] I have have a
def task[F[_]: Concurrent](): F[Unit] = ??? that I'm currently intending to pass to the loop. Would it be better to do
loop(task()) rather than
loop(task), or am I completely missing the point
Futurebut fortunately that's not necessary with
IOimplementations
F[_]rather than
IO, cool I like that. But I ran in to an issue, mainly how to do this with a
Futurefrom an external API? I cannot seem to find any general trait having a
fromFutureor similar. How is it best to approach this?
def foo[F[_]: Sync[F]]() = ???over
def foo[F[_]]()(implicit F: Sync[F])I kind of like the flexibility by the implicit setup, but I was wondering because the tutorial use the former version. Am I doing it bad, is it taste, or?
implicit class richIODatasource[D <: DataSource, F[_]:Sync](val ids: F[D]) extends AnyVal { import cats.effect.ExitCase.{Completed, Error, Canceled} def use[T](f: Connection => F[T]): F[T] = Resource.fromAutoCloseable[F, Connection](ids.map(_.getConnection())).use(c => f(c)) def transaction[T](f:Connection => F[T]):F[T] = use{ c => Sync[F].bracketCase(Sync[F].pure(c).map{c => c.setAutoCommit(false) c })(f){ case (in, Canceled | Error(_)) =>Sync[F].delay(in.rollback()) case (in,Completed) => Sync[F].delay(in.commit()) } } }
hmm does anyone have some advice/experience/best practices with how to write better tests with effects? Currently I'm doing mixing of for comprehensions and
unsafeRunSync, but it feels kind of awkward, I just cannot see how else to do it, e.g.:
"My app" should "do bar" in { val barsF = for { foo <- foo() bars <- foo.bars() } yield bars val bars = barsF.unsafeRunSync // tests go here
I'm struggling a bit, because in a way the cleanest would be to do the tests as
F[_]s too, such that they are just a part of the for comprehension, but in a way it also feels slightly off/awkward to me
race, but it's actually unspecified right now | https://gitter.im/typelevel/cats-effect?at=5d4ef4935178a7247663c3cd | CC-MAIN-2022-05 | refinedweb | 371 | 55.84 |
Hi there,
I recently grabbed the latest version of the 10.15 beta on a new computer and I have been trying to setup some command-line software that was working on my older machines running 10.13 and 10.14. Trying to build libfreenect (an open source library to interface with an Xbox 360 Kinect) with `make` gives me this error:
$ make
[ 1%] Building C object src/CMakeFiles/freenectstatic.dir/core.c.o
/Users/billjobs/code/libfreenect/src/core.c:27:10: fatal error: 'stdio.h' file not found
#include <stdio.h>
^~~~~~~~~
1 error generated.
make[2]: *** [src/CMakeFiles/freenectstatic.dir/core.c.o] Error 1
make[1]: *** [src/CMakeFiles/freenectstatic.dir/all] Error 2
make: *** [all] Error 2
I have installed Xcode's command-line tools but after doing some research it seems like 10.15 has changed the way things normally work the paths to header files, etc. Does anyone have any insight on a fix/workaround? It doesn't make sense to me why these header files would be missing.
Retrieving data ... | https://forums.developer.apple.com/thread/119822 | CC-MAIN-2019-43 | refinedweb | 176 | 59.7 |
Experiments With JavaFX Script
By Weiqi Gao, OCI Principal Software Engineer
December 2008
Introduction. Meanwhile, technologies supporting JavaFX applications were developed by Sun. By December 2007, Scenario, a scene graph library that makes 2D programming easy in JavaFX, was made open source. At JavaOne 2008 in May, JavaFX became the central theme of multiple keynotes and JavaFX demos were headline grabbers. Also announced at JavaOne 2008 was a license deal with ON2 to support multimedia codecs on the Java platform.
The first preview release of JavaFX SDK with support for desktop applications, called the desktop profile, was released in July 31, 2008. Version 1.0 of JavaFX Desktop is scheduled for the end of 2008 while JavaFX Mobile is scheduled for Spring 2009.
For the rest of this article I will abbreviate JavaFX Script into JavaFX when doing so causes no confusion.
As I write this article in mid November 2008, my frame of reference consists of two software bundles: the JavaFX Preview SDK from the end of July, 2008, and the open source openjfx-compiler project at java.net. The former includes the GUI and video bits, and the latter contains just the compiler. Since the language has evolved a bit in recent months, I will write non-GUI examples to the latest openjfx-compiler Subversion head, and GUI examples to the JavaFX Preview SDK. Please be advised that some of the examples (the GUI examples more than the non-GUI examples) in this article may be made obsolete when JavaFX Desktop SDK 1.0 is released.
The Place of JavaFX in the Universe
Around the same time frame when JavaFX is being developed, several other technologies in roughly the same category are also being released, among them are Flex and AIR from Adobe and Silverlight from Microsoft. Both offerings are impressive and would be good technology choices where appropriate.
However, JavaFX promises to offer something unique that makes it a compelling choice:
- It runs on the JVM, which covers many platforms, from Windows, Macs and Linux PCs to Unix boxes and supercomputers to cell phones and other small devices.
- JavaFX Script is an innovative statically-typed scripting language that offers declarative construction of GUIs and data bindings.
- It can leverage the enormous number of Java libraries that are available either as open source or as commercial products.
Many Java GUI developers use Swing to build their GUIs and are therefore worried what JavaFX will do to Swing development. While it is true that JavaFX will be an alternative way to build Java GUI applications, the fact that JavaFX, at least in the desktop profile, depends on both Swing and the JVM also means that Swing will continue to be improved along with JavaFX. JavaFX is also the driving force behind the recently released Java 6 Update 10, which includes many improvements for client side Java that will be enjoyed by both Swing and JavaFX applications.
Getting The JavaFX Preview SDK
The JavaFX Preview SDK can be downloaded from the official JavaFX website. Simply click on the "Get JavaFX Preview SDK" button to go to the download page, where you can download the JavaFX Preview SDK either with or without NetBeans IDE. For this article, the one without NetBeans IDE suffices.
The JavaFX Preview SDK is supported on Windows and Mac OS X only. However, for Linux or Solaris users, if you download the zip file version for Mac OS X, most of the SDK will work. Only parts that depends on native libraries will not work.
After adding the
bin directory of the JavaFX Preview SDK to your
$PATH environment variable, you will be able to use following three commands from your command shell:
javafxc: The JavaFX compiler;
javafx: The JavaFX runtime;
javafxdoc: The JavaFX Javadoc generator.
These commands are similar to the
javac,
java and
javadoc commands in the JDK.
Getting the Openjfx-compiler
The openjfx-compiler open source project is hosted on java.net at.
This project has been active since mid-2007 and has an active mailing list, an issue tracker, and a Subversion repository.
You can grab the latest successful build artifacts from the continuous build server or build from the Subversion head.
Running "
ant all" in the
openjfx-compiler source directory builds the compiler. The result lives in a
dist subdirectory, which in turn contains the usual
bin,
doc,
lib and
man subdirectories. You will find the
javafxc,
javafx, and
javafxdoc commands in the
bin subdirectory.
Since both the JavaFX Preview SDK and the openjfx-compiler offer the same commands, you can't use both at the same time without resorting to using full paths. For the purpose of this article, it is better to write a couple of shell scripts to manipulate the
$PATH to contain either the JavaFX Preview SDK's
bin directory or
openjfx-compiler/dist's
bin directory.
Hello JavaFX World
With the JavaFX Preview SDK or the openjfx-compiler installed, we can get started with our experiments.
First, the obligatory "hello, world" example. Create a file named
hello.fx that contains the following line:
println("hello, world.")
Compile it with the command:
[weiqi@gao]$ javafxc hello.fx
Then run it with:
[weiqi@gao]$ javafx hello hello, world.
As you can see from this example, the flow of developing an JavaFX application is very similar to the flow of developing a Java application.
However, the JavaFX source is simpler than Java. In JavaFX there is no need to declare a class and write a main method to do a simple "hello, world" program. In this regard, JavaFX is similar to other scripting languages like Perl, Python, Ruby and Groovy.
In JavaFX, a
*.fx file is called a script. A script may contain any number of class definitions, function definitions, import declarations and loose statements. Our
hello.fx contains only one statement, the call to the println built-in function. Notice that there is no semicolon at the end of that statement. In JavaFX, like in Java, the semicolon is a statement terminator. However in JavaFX the semicolon is optional in many places. As a result, the JavaFX compiler appears to be more lenient towards missing semicolons.
JavaFX Compiles JavaFX Sources to Java Class Files
In this experiment, we compile the following JavaFX source file:
// func.fx function sumOfSquares(x, y) { x * x + y * y } println(sumOfSquares(3, 4));
The JavaFX compiler compiles
func.fx into two Java class files:
func.class and
func$Intf.class. The former has a JavaFX compiler generated
main method, which eventually calls into another generated method that executes the loose statements in
func.fx. The latter is never directly used when we run JavaFX Scripts, and can be considered an implementation detail.
The
javafx command is a wrapper of the
java command that prepends the JavaFX runtime jars into the bootclasspath before running the class specified on the command line.
The
func.fx script defines a simple function that calculates the sum of squares of its two arguments. The function keyword is used to define a function. Notice how in JavaFX you are not required to specify the argument types or the return type when you define a function. The compiler can determine them based on the functions body using a facility called type inference. In our case, the compiler will treat our function as if we have defined it with the following data types:
function sumOfSquares(x: Number, y: Number): Number { x * x + y * y }
Number is a JavaFX built-in type, it represents double precision floating-point numbers. In JavaFX the type specifier follows the entity it applies to and is separated from it by a colon. This makes it easy to omit the type specifier.
Boolean, Integer, Number, String, Duration
Besides
Number, JavaFX supports four other built-in types. They are:
Boolean,
Integer,
String and
Duration.
Integer represents 32-bit integer values.
Duration plays an important role in animations, which we'll see a bit later.
They are called primitive types in JavaFX. But unlike primitive types in Java, they have classes and you can call methods on them. The
Boolean,
Integer and
String types are backed by Java classes
java.lang.Boolean,
java.lang.Integer and
java.lang.String. The
Number type is backed by the Java class
java.lang.Double. The
Duration class is backed by
javafx.lang.Duration.
The
Boolean,
Integer and
Number types support Java-like literal expressions, such as
true,
false,
1024 and
3.14.
Like in other scripting languages, the JavaFX
String type supports embedded JavaFX expressions using braces. JavaFX further supports formatting of embedded JavaFX expressions in strings through the use of format specifiers. JavaFX does not support multi-line strings as some other scripting languages do. However, to ease the representation of overly long strings and multi line strings, JavaFX supports adjacent String expressions concatenation. Here are some examples:
var str1 = "Hello"; // double quotes var str2 = 'Goodbye'; // single quotes var str3 = "1 + 2 = {1 + 2}"; // => "1 + 2 = 3" var str3 = '3 + 4 = {3 + 4}'; // => "3 + 4 = 7" var str4 = "1024 in hex is {%x 1024}"; // => "1024 in hex is 400" var str5 = "Hello, " "World."; // => "Hello, World."
For the
Duration type, JavaFX supports time literals, which are self evident in form and meaning. Here are some examples:
var oneHour = 1h; var oneMinute = 1m; var oneSecond = 1s; var oneMillisecond = 1ms; println(oneHour); // => 3600000.0ms println(oneMinute + 15 * oneSecond); // => 75000.0ms println(oneMillisecond); // => 1.0ms
Constants, Variables, Classes
In the last few experiments, we have seen function definitions, variable declarations and statements in JavaFX. There are only two more kinds of major constructs that can appear at the top level of a JavaFX script: constant declarations and class definitions.
Constants are introduced by
def. Constants must be initialized when they are declared. The type specifier of the constant is optional and is usually omitted. For example:
def PI = 3.14159265; PI = 2.71828; // Error, PI is a constant
Variables are introduced by
var. Variables can be assigned after they are declared. The type specifier is optional. For example:
var name: String; name = "John";
Functions are introduced by
function. The function name is followed by the parameter list. The type specifiers for each parameter as well as the return type specifier are optional.
Classes are introduced by
class. Classes can contain constants, variables, and functions and a couple of other things which we will cover in later sections. Variables in classes are also called member variables. Functions in classes are also called member functions. Here's a simple class:
<pre style="margin-left:3em" xml:class Point { var x: Number; var y: Number; function print() { println("Point({x}, {y})"); } }</pre>
As language constructs go, these are the major ones in JavaFX. They are constants, variables, functions, classes, and statements. Strictly speaking, constant and variable declarations are also statements. And there are many other kinds of statements in JavaFX.
Types in JavaFX
JavaFX is a statically-typed language. We have seen the five primitive types. Each user-defined class defines a type. Thus the
Point class we defined earlier gives us a
Point type.
One of the differences between primitive types and user-defined types is that variables of primitive types always have a value. If you don't specify an initializer when defining a variable of a primitive type, they get the default value. Here are some examples:
var b: Boolean; var i: Integer; var n: Number; var str: String; var dur: Duration; println("b = {b}"); // => b = false println("i = {i}"); // => i = 0 println("n = {n}"); // => n = 0.0 println("str = \"{str}\""); // => str = "" println("dur = {dur}"); // => dur = 0ms
Note that the default values for primitive types are never null. The default value for
String is
"".
On the other hand, uninitialized variables of user-defined types have the value
null:
var point: Point; println(point); // => null
Aside from primitive types and class types, JavaFX supports two other kinds of types: function types and sequence types, which we experiment with in the next two sections.
Function Types
Unlike in Java, but like in other scripting languages, functions are first class entities in JavaFX. Functions have types, called function types. The
sumOfSquares function that we defined earlier would have the type
function (:Number, :Number): Number. You can declare constants and variables of function types. You can pass functions as parameters to other functions. You can return functions from functions. Here is the
addN example that is usually found in Lisp books:
function addN(n: Number): function(:Number): Number { function(x: Number): Number { x + n } } var addTen = addN(10); println(addTen(3)); // => 13.0
The function
addN takes one parameter of type
Number and returns a function of type
function(:Number): Number. The function that is returned by
addN(10) is assigned to the variable
addTen. The variable
addTen is of a function type and is called just like any other function.
Function types are a little hard to specify, especially when functions are passed in as parameters or returned. Fortunately, JavaFX's type inference engine is pretty powerful so we don't always have to explicitly specify the types. The
addN function could just as well be defined as follows:
function addN(n) { function(x) { x + n } }
In JavaFX, the last expression in the function body is the return value of the function. You can, but are not required to, use the
return keyword in this situation. You do, however, need the
return keyword if you want to return from a place other than the last expression.
Notice also how the return value of
addN is a function without a name. This is called an anonymous function expression. It evaluates to a closure, which is like a function that remembers all the variables that are in scope when the anonymous function expression is defined.
Sequence Types
Primitive types, class types and function types can also be used to form sequence types. Sequence types are formed by adding
[] to one of these types. Here are some examples:
class Point { var x: Number; var y: Number; } var nums: Number[]; // sequence of Number var strs: String[]; // sequence of String var points: Point[]; // sequence of Point var funcs: (function(:Number):Number)[] = [function(x){x}]; // sequence of function()
Only non-sequence types may be used to form sequence types. In other words, you cannot form a type that is a sequence of sequences. You will see why a little bit later. The current version of the compiler also has some limitations when it comes to sequences of functions. You must specify a non-empty sequence as an initializer for any variables of sequence of function type.
All JavaFX types have an element specifier and a cardinality. Non-sequence types consist of an explicit element specifier and an implied cardinality. Primitive types have the cardinality required, which means that a variable of primitive type contains exactly one value and cannot be null. Sequence types have the cardinality sequence, which means a variable of sequence type may contain zero or more elements. All other types (class types and function types) have the cardinality of optional, which means a variable of these types may have a value or be null.
To construct a variable of sequence type, you use an explicit sequence expression or a range expression:
var oneTwoThree = [1, 2, 3]; // => [ 1 2 3 ] var oneToTen = [1..10]; // => [ 1 2 3 4 5 6 7 8 9 10 ] var oneToNine = [1..<10]; // => [ 1 2 3 4 5 6 7 8 9 ] var odds = [1..10 step 2]; // => [ 1 3 5 7 9 ] var reversed = [5..1 step -1]; // => [ 5 4 3 2 1 ]
The first line uses an explicit sequence expression. It works for any element type. The rest use range expressions. They work only for numeric types. The thing to look out for when using range expressions is that you must specify a negative step value when constructing a decreasing sequence. Failure to do so will result in an empty sequence.
An uninitialized sequence variable has the value of an empty sequence,
[].
Object Literals
In the last few experiments, we learned the four kinds of data types in JavaFX: primitive types, class types, functions types and sequence types. We also learned ways to initialize variables of three of the four kinds of types: literals for primitive types, function definitions or anonymous function expressions for function types, and explicit sequence expressions and range expressions for sequence types.
To initialize a variable of a class type in JavaFX, we use an object literal expression. Here are a couple of
Point variables:
// Reuse the Point class define earlier var pointA = Point { x: 3, y: 4 }; var pointB = Point { x: 5 y: 12 };
An object literal starts with the class name followed by a pair of braces that contains initializers for the member variables. The member variable initializers may be separated by commas for when they are put in one line as we did for
pointA, or spaces for when they are put on separate lines as we did for
pointB. You can also use semicolons, but that is necessary only when separating member variable initializers from other constructs in the object literal.
One benefit of the JavaFX object literal syntax is that you can understand the object being constructed at the site of the object literal without looking at the class definition. You can see exactly which member variables are initialized to what values.
Another benefit is that object literals nest well. If a member variable is of class type, its initializer can be another object literal nested inside the enclosing object literal.
A third benefit is that object literals and explicit sequence expressions mix well. If a member variable is of sequence type, its initializer can be a explicit sequence expression nested inside the enclosing object literal.
Declarative GUI Construction
These conveniences of the object literal expression, when applied to GUI construction, yield a style of programming that is declarative in nature. Here's an example of a JavaFX GUI:
// hello.fx import javafx.stage.*; import javafx.scene.*; import javafx.scene.text.*; Stage { title: "Example" scene: Scene { width: 500 height: 300 content: Text { x: 100, y: 126 content: "Hello, World." font: Font { size: 48 } } } }
In this example we constructed a
javafx.stage.Stage object whose
scene member variable is initialized to a newly constructed
javafx.scene.Scene object. The
Scene object's
contents member variable is initialized to a
javafx.scene.text.Text. And finally the
Text object's
font member variable is initialized to a
javafx.scene.text.Font.
You need the JavaFX Preview SDK to run this program. The JavaFX Preview SDK includes the JavaFX GUI runtime which provides the necessary
Stage,
Scene,
Text and
Font classes.
Operators, Expressions, Statements
Like Java and other scripting languages, JavaFX supports operators, expressions and statements. All executable code in JavaFX are expressions. Many of them are similar to their Java counterparts. We'll show examples of some of them in this section. A few are quite different from their Java counterparts. And finally, some are unique to JavaFX. We will cover them in more detail in later sections.
Here is some JavaFX code that uses a few of the JavaFX language constructs:
// fib.fx import java.lang.*; function fib(n: Number): Number { if (n < 0) throw new IllegalArgumentException( "fib: parameter must be >= 0."); if (n == 0) { return 0; } else if (n == 1) { return 1; } else { var a = fib(n - 1); var b = fib(n - 2); return a + b; } }
The
import facility works as in Java.
The exceptions facility works as in Java but checked exceptions are not enforced by the JavaFX compiler. Of course you have to use JavaFX style type specification syntax in catch clauses.
The arithmetic operators (
+,
-,
*,
/,
mod), increment operators (
++ and
--, both pre and post), assignment operators (
=,
+=,
-=,
*=,
/=), relational operators (
<,
, , equality operators (
>,
>=)
==and
!=), boolean operators (
and,
or,
not) and the
instanceof operator all work as expected.
JavaFX does not use
%,
&&,
|| and
! operators as in Java. The spelled out form
mod,
and,
or and
notare used instead.
You can even use the
new operator to construct objects of Java classes.
println(new java.util.Date()) // => Fri Nov 14 08:12:47 CST 2008
Values Of Expressions
A few expressions, such as the
while loop, do not have a value and are considered to be of the
Void type. Most JavaFX expressions have a value and a type. They are called value expressions.
You can use value expressions as the right-hand side of variable declarations, member variable initializations in object literals and assignments. When a variable is declared without an explicit type specifier, its type is the type of the right hand side of the declaration.
Non-value expressions correspond to what are called statements in Java. I will use the term statement in this article although that is not standard JavaFX terminology. Standalone value expressions are also statements. The semicolon is used to separate a value expression statement from the next statement.
The block, a number of statements surrounded by a pair of braces, is an expression in JavaFX. Its value and type are those of its last statement.
var x = { var y = 10; y * y } // x is of type Integer with a value of 100
The
if construct, which is a statement in Java, does have a value. Therefore it has been turned into an expression in JavaFX, with several variants of syntax.
var b: Boolean; // initialize to true or false var x: Number; if (b) { x = 3; } else { x = 4;} // traditional form x = if (b) then 3 else 4; // expression form, like b?3:4 in Java x = if (b) 3 else 4; // 'then' is optional
The
for loop, which has two forms in Java—the traditional
for loop and the so-called for each loop—has a new face in JavaFX that resembles the Java for each loop but with a few twists. It is an expression in JavaFX whose value is most often a sequence whose elements are the values of the block introduced by the
for expression, once for each iterand. A
for expression is of
Void type if its block is of
Void type.
var input = [1, 3, 5, 7, 9]; var output = for (x in input) { x + 1 } // => [ 2, 4, 6, 8, 10 ]
Since sequences play such an central role in JavaFX, and since the
for expression works closely with JavaFX sequences, there is a lot more that the
for expression can do than is demonstrated above. We will reveal these details later when we experiment more with sequences.
Data Binding
Now that we have gone through the familiar statements and expressions, it's time to tackle the unfamiliar ones, expressions that are unique to JavaFX.
JavaFX supports data binding at the language level with the
bind construct. In its simplest form, it makes a variable change its value automatically when its binding changes its value:
var x = 10; var y = bind x; println("x = {x}, y = {y}"); // => x = 10, y = 10 x = 20; println("x = {x}, y = {y}"); // => x = 20, y = 20
You can make the binding a two way binding by adding
with inverse at the end of the binding:
var x = 10; var y = bind x with inverse; y = 20; println("x = {x}"); // => x = 20
The right-hand side of a binding can be an arbitrary expression, in which case an automatic update of the left-hand variable is triggered if any of the variables mentioned in the right-hand side expression is changed:
var x = 1; var y = 2; var z = bind x*x+y*y; // z is updated when x or y change var w = bind sumOfSquares(x, y); // w is updated when x or y change
Of course when you bind to an expression that is not a single variable it does not make sense to make it a two way binding.
When binding a variable to a function, there is a way to let the automatic update happen more often than when the function arguments change. You can make it so that the variable is updated when anything that the body of the function depends on changes. To achieve this, you define the function with the
bound modifier:
var a = 10; bound function f(n) { n + a } var x = 20; var y = bind f(x); // y is updated when x or a changes
JavaFX data binding achieves with very concise syntax what requires custom listeners and wiring code in Java.
Working With Sequences
JavaFX has an extensive set of facilities for working with sequences. We have seen some of them already. In the next few experiments we learn more about sequence manipulation.
Perhaps the most non-intuitive aspect of JavaFX sequences is that they do not nest. When you try to create a sequence whose elements are themselves sequences, JavaFX flattens the result:
println([1, [2, 3]]) // => [ 1, 2, 3 ]
You can assign a value of a non-sequence type to a variable of the corresponding sequence type. In this context, JavaFX will promote the value into a sequence of one element. Assigning null to a sequence variable will make the variable's value an empty sequence.
var numbers: Number[]; println(numbers); // => [ ] numbers = 3.1415926; println(numbers); // => [ 3.1415926 ] numbers = null; println(numbers); // => [ ]
The
sizeof operator can be used to find the size of a sequence:
println(sizeof [1, 2, 3]); // => 3
Sequences cannot hold null elements. Attempting to put a null into a sequence will be ignored:
var numbers: Number[]; numbers = [ 1, null, 3 ]; println(numbers); // => [ 1.0, 3.0 ]
Insert and
delete statements can be used to manipulate the content of sequences. There are three variants of
insert statements: insert into, insert before, and insert after.
var nums = [1, 4, 2, 8, 5, 7]; insert 10 into nums; // [ 1, 4, 2, 8, 5, 7, 10 ] insert 20 before nums[2]; // [ 1, 4, 20, 2, 8, 5, 7, 10 ] insert 30 after nums[5]; // [ 1, 4, 20, 2, 8, 5, 30, 7, 10 ] delete 8 from nums; // [ 1, 4, 20, 2, 5, 30, 7, 10 ]
You can also delete a specific element or slice from a sequence:
delete nums[3]; // [ 1, 4, 20, 5, 30, 7, 10 ] delete nums[1..4]; // [ 1, 7, 10 ]
JavaFX provides a
reverse operator to reverse sequences:
<pre style="margin-left:3em" xml:var seq = [1 2 3]; var qes = reverse seq; println(seq); // => [ 1, 2, 3 ] println(qes); // => [ 3, 2, 1 ]</pre>
Sequence Comprehension
I use the term sequence comprehension to mean syntactic constructs that build up new sequences out of existing sequences. JavaFX provides multiple sequence comprehensions.
var nums = [ 1, 4, 2, 8, 5, 7 ]; var fifth = nums[4]; // 5 var slice = nums[0..2]; // [ 1, 4, 2 ] var slice2 = nums[0..<2]; // [ 1, 4 ] var evens = nums[x|x mod 2 == 0]; // [ 4, 2, 8 ]
The last expression is supposed to mimic the mathematical notation for defining a subset with a constraint on its members:
{x ∈ N | x ≡ 0 mod 2}.
In this form of sequence comprehension, called sequence selection, the
x on the left of the vertical bar is an selection variable. And the expression on the right is an Boolean expression, called the constraint. An element is selected if and only if the constraint is true.
We can achieve the same result with a
for expression:
var evens = for (x in nums) { if (x mod 2 == 0) then x else null }
Unlike iteration variables in Java's for each loops, you can query the position of iteration variables in the original sequence with the
indexof operator:
var evenIndexed = nums[x|indexof x mod 2 == 0]; var evenIndexed2 = for (x in nums) { if (indexof x mod 2 == 0) then x else null } println(evenIndexed); // => [ 1, 2, 5 ] println(evenIndexed2); // => [ 1, 2, 5 ]
The For Loop Is A Query Language
So far in our experiments, we have used the
for expression with only one iteration variable iterating over one sequence. JavaFX allows more than one iteration variables in its
forexpressions iterating over more than one sequences. Taking a cue from SQL, these iteration specifications are called in clauses. Here is a
for expression with two in clauses:
var rs = ["A", "B"]; // rows var cs = ["1", "2"]; // columns var xs = // cross product for (r in rs, c in cs) { "{r}{c}" }; println(xs); // [ A1, A2, B1, B2 ]
Also inspired by SQL, the in clauses in a
for expression can have
where clauses that constrain the selection. The expressions in the
where clauses are Boolean expressions and can refer only to iteration variables already introduced. In other words, if the first in clause's iteration variable is
x, and the second in clause's iteration variable is
y, then the where clause attached to the first in clause may refer only to
x, not
y, while the where clause attached to the second in clause may refer to both
x and
y.
Here is a small program that finds all integral points in first quadrant that lie within the circle centered at the origin with radius 2:
class Point { var x: Integer; var y: Integer; override function toString() { "P({x},{y})" } } var xs = [0..2]; var ys = [0..2]; var ps = for (x in xs, y in ys where x*x+y*y <= 4) { Point { x: x, y: y} }; println(ps); // => [ P(0,0), P(0,1), P(0,2), P(1,0), P(1,1), P(2,0) ]
A few side notes are in order. First, the
override modifier must be used in the definition of the
toString() method because we are overriding the
toString() method of
java.lang.Object.
Second, the object literal in the body of the
for expression, with initializers that look like
x: x and
y: y seems a little unsettling. But don't worry, the object literal is perfectly fine, because the first
x refers to the member variable of
Point and the second
x refers to a variable
x in the surrounding scope, in our case the iteration variable
x.
Triggers
JavaFX variables may optionally be fitted with a trigger in the form of an
on replace clause. The on replace clause introduces a block that is executed every time the value of the variable is modified.
There are several forms of the on replace clause. Here is a simple one:
var x = 50 on replace { if (x < 0) { x = 0; } else if (x > 100) { x = 100; } }; x = -3; println(x); // => 0 x = 120; println(x); // => 100
Triggers of this form are similar to setters in Java.
For non-sequence type variables you can have access to the old value of the variable:
var x = 50 on replace oldValue { println("on replace: oldValue={oldValue}, newValue={x}"); }; // => on replace: oldValue=0, newValue=50 x = 80; // => on replace: oldValue=50, newValue=80
Notice that the initialization of the variable
x to the value 50 counts as a change to the value of the variable, a change from the default value of 0. The trigger is executed for this initialization as well as subsequent modifications to the variable.
Sequence typed variables may be modified in more complicated ways. The corresponding triggers accommodate this complexity by providing more information to the on replace clause.
var xs = [1, 4, 2, 8, 5, 7] on replace oldValue[lo..hi] = newSlice { println("on replace: oldValue={oldValue}"); println(" lo={lo}, hi={hi}"); println(" newSlice={newSlice}"); }; // => on replace: oldValue= // lo=0, hi=-1 // newSlice=142857</pre>
In the above example, the on replace trigger is fired when
xs is initialized to the six element sequence. During this change the
oldValue is the empty sequence; the
lo index of the change is 0; the
hi index is -1, one less than the
lo index, indicating an insertion; and the
newSlice is the six element sequence.
(The
oldValue and
newSlice variables do not print properly as sequences. The elements are squeezed together.)
In the next example, we replace a subsequence with new values, delete a subsequence, and insert an element into the sequence. And the output from trigger shows the effect of our actions:
xs[2..3] = [3, 9]; // => on replace: oldValue=142857 // lo=2, hi=3 // newSlice=39 delete xs[1..2]; // => on replace: oldValue=143957 // lo=1, hi=2 // newSlice= insert 2 into xs; // => on replace: oldValue=1957 // lo=4, hi=3 // newSlice=2
The syntax of the on replace clause is not the most intuitive part of JavaFX. It take some practice to get used to. The key thing to understand is that the variables you specify in the on replace clause are passed in from the JavaFX runtime.
The JavaFX runtime can supply three pieces of information: the old value of the variable, the low and high indices of the slice of the sequence that has changed, and what it has changed to, i.e., the new slice.
In the code above, I used
oldValue,
[lo..hi], and
newSlice in the on replace clause to receive these three pieces of information. But any other variable names may be used. These variables are read-only variables.
The form of the on replace clause:
var seq = [] on replace oldValue[lo..hi]=newSlice { // ... }
serves two purposes: It reminds the programmer of the role of each variable by resembling the slice modification syntax; It also allows the programmer to omit some or all of the pieces of information by not specifying the corresponding name.
Assignment to the observed variable in the on replace clause is allowed, but it will cause the trigger to be fired again if the assignment changes the value of the variable. Care must be taken to not cause the on replace trigger to be fired an infinite number of times.
JavaFX Executes On The EDT
We have gone through a lot of experiments so far. The good news is that we are almost done looking at the core features of the JavaFX Script language. We haven't covered organizational features like packages, access modifiers and class hierarchies. The only big features left are object initialization, and animations.
But before we get to them, I want to talk about the single threaded nature of JavaFX Script. By design, all user code written in JavaFX Script is executed in one thread. For desktop applications that thread is the AWT event dispatching thread, or the EDT.
Under the JavaFX Preview SDK, the following experiment will convince you that your code is being executed on the EDT:
println(java.lang.Thread.currentThread().getName()); // => AWT-EventQueue-0
If you run the above line of code with the openjfx-compiler, you will see "
Thread-0". That is because the openjfx-compiler is not hooked up to any GUI runtime.
One implication of this design choice is that you cannot write long running code in JavaFX or you risk an unresponsive GUI.
JavaFX does not offer any threading or synchronization primitives of its own. You can create threads using
java.lang.Thread. However those threads should not touch the internal states of JavaFX.
JavaFX does provide a way to asynchronously communicate with remote resources through the use of a set of classes in the
javafx.async package. I will talk more about this in a later section.
Init Blocks In Classes
Since JavaFX classes are initialized with object literal expressions, there are no constructors in JavaFX classes. Instead, two specially named blocks of code, the
init block and the
postinit block, may be declared in a JavaFX class that fulfil some of the functionalities of constructors in Java.
The
init block is run during the construction of a JavaFX object at a moment after the member variable values that are specified in the object literal expression have taken effect:
import java.lang.Math; class Point { var x: Number; var y: Number; var d: Number; init { d = Math.sqrt(x*x+y*y); } } var p = Point { x: 3, y: 4 }; println(p.d); // => 5.0
The
postinit block is executed after the object has been completely initialized. For a stand alone class, the
postinit block is run right after the
init block. The difference between
init and
postinit becomes apparent during the construction of an object of a derived class in a class hierarchy. An example will make the difference clearer:
class Base { var x: Number; init { println("Base.init"); } postinit { println("Base.postinit"); } } class Derived extends Base { var y: Number init { println("Derived.init") } postinit { println("Derived.postinit") } } var o = Derived {x: 3, y: 4}; // => Base.init // Derived.init // Base.postinit // Derived.postinit
While the
init and
postinit blocks execute in the order from base class to derived class, by the time the
postinit block of the base class is executed, the
init block of the most derived class has already been executed.
Access Modifiers And Code Organization
So far in this article, we have been writing loose code—essentially statements in a file, with the occasional class to illustrate a point or two.
JavaFX supports most of the organizational features found in Java. JavaFX programs can be organized into packages. Packages may contain subpackages, classes, and non-class JavaFX files. It is advisable to organize JavaFX source files into a directory hierarchy that reflects their package hierarchy. Just like for
javac, the
-d command line switch for
javafxc will put the compiled class files into the
directory under the correct directory hierarchy.
JavaFX supports the concept of modifiers for its classes, functions, variables, member functions and member variables. However, the set of modifiers it supports is radically different from those in Java.
First, the good news: there are no
static members in JavaFX. You can use script level variables or functions instead:
// com/ociweb/jnb/Point.fx package com.ociweb.jnb; public class Point { var x: Integer; var y: Integer; public override function toString() { "P({x}, {y})" } } public function gridPoints(n: Integer): Point[] { for (i in [0..n], j in [0..n]) { Point { x: i, y: j } } }
// main.fx import com.ociweb.jnb.Point; println(Point.gridPoints(1)); // => [ P(0, 0), P(0, 1), P(1, 0), P(1, 1) ]
There is also no
private modifier in JavaFX. You specify no modifiers instead. This gives you the default access in JavaFX, which is script private. We have been using this access level in this article all along.
The
public modifier makes entities it modifies accessible from anywhere in the application. It can be applied to entities at the script level, or to members of classes.
The
package modifier makes entities it modifies accessible from anywhere in the same package.
The
protected modifier is more complicated in JavaFX than in Java. When applied to member variables and member functions, it has the same meaning as in Java, i.e., accessible from subclasses and from the same package. When applied to script level variables and functions, it makes them accessible from the same package. It does not apply to classes.
JavaFX provides two additional access modifiers,
public-read and
public-init for member variables and script level variables. When
public-read is applied to a variable, it can be read from anywhere in the application. When
public-init is applied to a variable, it can be initialized in a object literal anywhere in the application.
The
public-read and
public-init modifiers are invented to make variables readable or initializable by the application but writable only by the implementation unit—either the script (if used alone) or the package (if used in conjunction with
package) where the variables are declared.
// com/ociweb/jnb/AdServer.fx package com.ociweb.jnb; public class AdServer { public-init var count: Integer; public-read var serverName = "My Ad Server"; def ads = ["Buy Food", "Buy Clothes", "Buy Bike", "Buy Ticket"]; public function getAds() { return ads[0..count-1]; } }
// main.fx import com.ociweb.jnb.AdServer; var adServer = AdServer { count: 2 }; println(adServer.getAds()); // => [ Buy Food, Buy Clothes ] println(adServer.serverName); // => My Ad Server println(adServer.count); // => 2
Notice that
public-init implies
public-read but
public-read does not imply
public-init. And under normal circumstances,
public-init or
public-read variables are not writable by the outside world. We will get compiler errors if we do the following in
main.fx:
adServer.count = 3; // No write access adServer.serverName = "X"; // No write access adServer = AdServer { serverName: "Y" }; // No init access
Object-Oriented Programming
The JavaFX class is the central concept of the object-oriented programming facilities in the language.
JavaFX does not support interfaces as Java does. It supports abstract classes. Abstract classes are declared with the
abstract modifier. An abstract class may contain zero or more abstract member functions, also declared with the
abstract modifier. Abstract classes cannot be instantiated.
public abstract class Shape { public abstract function show(): Void; }
JavaFX supports multiple inheritance of JavaFX classes. Subclasses can override members of superclasses. It must do so with the
override modifier. Both member functions and member variables can be overridden. The only reason you may want to override a member variable is to give it a different initializer or to augment its on replace trigger in a subclass.
public class Base { public var a: Number = 0 on replace { println("Base.a={a}"); } public function f() { println("Base.f()"); } } public class Derived extends Base { public override var a = 10 on replace { println("Derived.a={a}"); } public var b: String = "hi" on replace { println("Derived.b={b}"); } public override function f() { println("Derived.f()"); } public function g() { println("Derived.g()"); } } function run() { var base = Base { a: 20 }; // => Base.a=20.0 base.f(); // => Base.f() var derived = Derived { a: 30 b: "bye" }; // => Base.a=30.0 // Derived.a=30.0 // Derived.b=bye derived.f(); // => Derived.f() derived.g(); // => Derived.g() }
When you override a variable in a derived class, you cannot specify the variable's type. The variable will get its type from the base class. Notice also that when
derived is constructed, triggers for the overridden variable
a from both the base class and the derived class are fired.
All member functions are virtual.
The keyword
this can be used within the class definition to refer to the current object, just like in Java.
JavaFX classes can inherit from Java classes or interfaces. At most one Java class can be inherited, directly or indirectly, through at most one lineage, by a JavaFX class.
What Is A Module?
The way JavaFX code may be organized into files is more flexible (or complex, depending on your point of view) than Java because it allows variables, functions, and even loose statements at the script level.
There are two implications of this flexibility. First, in JavaFX the distinction between a library author and a library consumer is more profound. The library author, like a traditional Java developer, is mainly concerned with writing classes. The library consumer would focus on using the library classes and write mostly loose code.
Secondly, there are more ways to organize JavaFX code into script files. The traditional "one public class per file whose name matches the class name" organization is still supported, and is recommended for library authors of substantial classes. An alternative organization, in which several related smaller classes and functions are grouped into a single file, whose name does not necessarily match any of the public classes it contains, is also possible.
Such a JavaFX script file is called a module. Here is a simple example:
// com/ociweb/jnb/shapes.fx package com.ociweb.jnb; public class Point { public var x: Number; public var y: Number; } public class Circle { public var center: Point; public var radius: Number; } public class Triangle { public var a: Point; public var b: Point; public var c: Point; } public function area(circle: Circle) { var r = circle.radius; java.lang.Math.PI * r * r } public function area(triangle: Triangle) { var x1 = triangle.a.x; var y1 = triangle.a.y; var x2 = triangle.b.x; var y2 = triangle.b.y; var x3 = triangle.c.x; var y3 = triangle.c.y; (x1*y2 + x2*y3 + x3*y1 - x2*y1 - x3*y2 - x1*y3)/2 } // main.fx import com.ociweb.jnb.shapes.*; var triangle = Triangle { a: Point {x: 1, y: 0} b: Point {x: 2, y: 2} c: Point {x: 0, y: 1} }; println(area(triangle)); // => 1.5
As you can see from the above example, a module looks just like an ordinary script file. The difference lies in the fact that a module exports some or all of its members to the outside world by using a more open access modifier, usually
public, than the default script private access. Incidentally, once a script file has an exported member, be it a
public class or a
public-read script level variable, JavaFX no longer allows any loose statements in the script file. And the module class itself cannot be run with
javafx any more unless you create a function called
run() in the module file.
Notice also how the
import statement cooperates with modules. In the above example, we used the wild card character
* to import all members of the module
com.ociweb.jnb.shapes into the current scope. Alternatively, you can import each member individually:
// main2.fx import com.ociweb.jnb.shapes.Point; import com.ociweb.jnb.shapes.Triangle; import com.ociweb.jnb.shapes.area; var triangle = Triangle { a: Point {x: 1, y: 0} b: Point {x: 2, y: 2} c: Point {x: 0, y: 1} }; println(area(triangle)); // => 3.5 (but see notes below)
Or you can import the module itself, and access its members with the dot notation:
// main3.fx import com.ociweb.jnb.shapes; var triangle = shapes.Triangle { a: shapes.Point {x: 0, y: 0} b: shapes.Point {x: 1, y: 0} c: shapes.Point {x: 0, y: 1} }; println(shapes.area(shapes.triangle)); // => 0.5
(Please note that a compiler bug prevents the second example
main2.fx from compiling.)
Animations
One of the attractions of JavaFX is its animation features. It makes the GUI look pretty. However, if you think it through, an animation is nothing more than changing some GUI properties from one value to a sequence of updated values over time. For example, to animate a little box moving from the left side of a window to the right side of a window, you change its x position from 0 to the width of the window through a sequence of intermediate values over time. To achieve a fade in effect, you change the opacity of an object from 0 to 1 through a sequence of intermediate values over time.
That is why JavaFX can put its animation support in the language rather than in the GUI runtime. The animation support is achieved through a library-based approach with some syntactic help.
Let's look at a very simple example, in which we animate a numeric variable and monitor the effects of the animation through a trigger:
import javafx.animation.*; import java.lang.System; var x = 0 on replace { println("At {System.currentTimeMillis() mod 1000000}, x={x}"); }; var t = Timeline { keyFrames: [ at(5s) { x => 10 }] }; t.play();
It generated the following output on one run:
At 617610, x=0 At 618553, x=1 At 619065, x=2 At 619561, x=3 At 620061, x=4 At 620558, x=5 At 621053, x=6 At 621565, x=7 At 622061, x=8 At 622557, x=9 At 623053, x=10
The
javafx.animation.Timeline class is the controller of animations. In the example, we instantiate a
Timeline object by setting its
keyFrames member variable to a sequence of one
javafx.animation.KeyFrame object. When we call the
play() method on the
Timeline object, the animation is performed.
Can you guess what the
KeyFrame object is saying? If your guess is "at the 5 second mark, x should be 10" then you are spot on. Given this KeyFrame, the Timeline object will figure out the intermediate values using an
javafx.animation.Interpolator. Since we did not specify an interpolator, the default one, which is
Interpolator.LINEAR is used.
To specify a different interpolator, we use the following syntax:
var t = Timeline { keyFrames: [ at(5s) { x => 10 tween Interpolator.DISCRETE } ] };
The
DISCRETE interpolator is one that jumps from the start value to the end value in one step. The modified animation generated the following output on one run:
At 291118, x=0 At 296986, x=10
There is much more that the JavaFX animation framework can do to make your GUI application more alive. We have just scratched the surface of it.
Let me close this section by animating our earlier GUI application. We first declared a script level variable
x. We then bind the
x member variable of the
Text element to the script level variable
x. Finally, we animate the value of the script level variable
x.
import javafx.stage.*; import javafx.scene.*; import javafx.scene.text.*; import javafx.animation.*; var x = 50; Stage { title: "Example" scene: Scene { width: 500 height: 300 content: Text { x: bind x, y: 125 content: "Hello, World." font: Font { size: 48 } } } }; var timeline = Timeline { repeatCount: Timeline.INDEFINITE autoReverse: true keyFrames: [ at(1s) { x => 150 tween Interpolator.EASEBOTH } ] }; timeline.play();
Internationalization
JavaFX's internationalization support is based on Java's internationalization facility. However, JavaFX introduces a syntactic tool and some new rules to make internationalization easier than in Java.
To signal to the JavaFX compiler that a String is a candidate for internationalization, we prefix the String with a double hash sign
## followed optionally by a key enclosed in brackets. If no key is specified, the String itself is considered the key if it does not contain any embedded JavaFX expressions. If the String contains embedded JavaFX expressions, the key is the String with the embedded expressions converted to the
java.util.Formatter style.
// i18n.fx var i = 1024; println(##[greeting]"Hello, World."); println(##[value]"The value of i is {%d i}.");
When this program is compiled and run, the JavaFX runtime will search the
classpath for a
*.fxproperties file whose name is derived from the
*.fx file name and the locale. For our example, if we run it in the US English locale, the files being searched are:
i18n_en_US.fxproperties i18n_en.fxproperties
If a
fxproperties file is found, the property value for each key is retrieved from the
fxproperties file and used in place of the original String. If a matching
fxproperties file is not found, the original String in the source file is used. When the original String contain format specifiers, the property value for the corresponding key should also contain the appropriate format specifiers in the
java.util.Formatter style.
A localization file for the German locales might look like the following:
// i18n_de.fxproperties "greeting"="Hallo, Welt." "value"="Der Wert von i ist %1$d."
Notice how the embedded JavaFX expression "{%d i}" is converted to the
java.util.Formatter style "%1$d". The position rather than the variable name is used in the localization files to minimize the burden on the translator who may be confused on whether to translate the variable name to the local language.
Odds And Ends
With that, I believe we have covered most of the language features of JavaFX. There are a few small things that I left out. Let me just mention them briefly.
In JavaFX you can use
continue and
break in
while loops.
In JavaFX,
Void can be used as the return type for functions to indicate that the function does not return a value.
In JavaFX, casting is done with the
as operator:
var point: Point = Point3D { x: 3, y: 4, z: 5 }; var point3d = point as Point3D;
Although a constant introduced with
def cannot be assigned to later, it is legal to initialize it with a
bind expression. In that case, the constant is not a true constant. Its value will be updated when its dependencies change.
In an object literal expression, in addition to specifying member variable initializers, you can also declare variables and define functions.
To receive command line arguments, the
run() function in a JavaFX script file can be defined to take a
String[] argument:
// run.fx function run(args: String[]) { for (arg in args) { print(arg); if (indexof arg < sizeof args - 1) { print(", "); } else { println(""); } } }
$ javafxc run.fx $ javafx run 1 2 3 4 5 1, 2, 3, 4, 5
With JavaFX language features out of the way, in the remaining sections we cover a few topics from the JavaFX Preview SDK that may be of interest to you. There are many more features that I do not have space to cover in this article. You are encouraged to browse the JavaFX API documentation.
Enhanced Multimedia Support
One area where Java has been lacking is robust multimedia support. JavaFX addresses this issue with the introduction of the Java Media Components (JMC). The JMC is actually a Java-based framework that handles media playback on the Java platform. JavaFX contains a set of JMC wrappers in the
javafx.scene.media package that make media playback in JavaFX very simple.
The framework's central classes are
Media,
MediaPlayer and
MediaView.
The
Media class encapsulates multimedia resources like video files. Its member variables include
source,
duration and other information about the resource such as the width and the height of the video clip, and any other metadata that might be embedded in the resource file. You supply the
source as a URL when you construct a
Media object.
The
MediaPlayer is responsible for the actual playing of the
Media clip. It has two member functions,
play() and
pause(). It has member variables that controls the
MediaPlayer itself, like
volume,
fader,
balance and
mute. And it has member variables that control how the media is played, like
autoPlay,
repeatCount, etc. And of course it has a
media member variable that controls what it plays.
The
MediaView is a visual
Node that is responsible for the on screen presentation of the media player. It has a
mediaPlayer member variable. Its other member variables control how it may be manipulated.
A simple video player can be written in just a few lines of JavaFX code:
// player.fx import javafx.stage.*; import javafx.scene.*; import javafx.scene.media.*; function run(args: String[]) { if (sizeof args < 1) { println("Usage: javafx player <media-url>"); return 0; } var media = Media { source: args[0] }; var mediaPlayer = MediaPlayer { autoPlay: true media: media } Stage { title: "Video Player" scene: Scene { width: media.width height: media.height content: MediaView { mediaPlayer: mediaPlayer } } } }
Video support in the JavaFX Preview SDK is not complete. You can play native video formats on the supported platforms: On Windows, you can play anything that the Windows Media Player can play. On Mac OS X, you can play anything that CoreAudio and CoreVideo can play.
Cross-platform multimedia support using ON2 technologies is coming with the JavaFX Desktop 1.0 release at the end of 2008.
Communication With The Outside World
Since JavaFX code runs on the AWT event dispatch thread (EDT), a natural question developers ask is: "What about long running operations?"
JavaFX's answer to this question is a mechanism that is similar to
XMLHttpRequest in AJAX applications. Although the JavaFX wrapper classes did not make it into the JavaFX Preview SDK, the Java classes that constitute the async operations framework can be found in the
openjfx-compiler project.
Here's a possible reconstructed scenario from an earlier conversation on the
openjfx-compiler mailing list:
// remote.fx import javafx.async.*; var rtd = RemoteTextDocument { url: "" method: "GET" }; var text = bind if (rtd.done) rtd.document else "Loading...";
After construction, the
RemoteTextDocument object would start downloading the document pointed to by the
url member variable in a background thread. It would update its
done member variable to
true and its
document member variable to the content of the document when it has obtained the document.
By binding the
text variable to the if-expression, its value will be updated by the JavaFX runtime, on the EDT thread, when the document is completely downloaded.
You can monitor the
RemoteTextDocument object for progress of the download. You can also attach various callback functions to it to have more control over the handling of the downloaded document.
Look for something similar to the above in the JavaFX Desktop 1.0 release.
Rethinking Deployment
Since JavaFX compiles its source files into Java class files, JavaFX application deployment scenarios are essentially the same as Java deployment scenarios.
You can deploy your JavaFX applications as regular Java applications that are invoked on the command line, as we have done in this article.
You can package your JavaFX applications into jar files and deliver them with Java Web Start. With the JavaFX Preview SDK, you have to include the JavaFX runtime jars in your application. However, with the JavaFX Desktop 1.0 release, Sun will offer the JavaFX runtime jars as a JNLP extension at a standard URL. At that time, you can simply reference the standard JavaFX JNLP extension in the JNLP file of your JavaFX application. The hope is that the standard JavaFX runtime will be downloaded to the user's JRE cache the first time any JavaFX application is run, and subsequent JavaFX applications won't have to make another download.
The JavaFX Preview SDK supports the writing of JavaFX applets. However, Java applets haven't been a popular deployment mechanism in recent years. I don't see traditional style applets to be a popular mechanism for JavaFX application deployment.
With the new Java 6 Update 10 JRE release, however, the boundary between Java Web Start and Java applets is blurred. You can deploy your JavaFX application as a JNLP based applet that can be dragged on to the desktop to become a JNLP based application.
Look for JavaFX classes and NetBeans IDE wizards that support this deployment mechanism in the JavaFX Desktop 1.0 release.
Summary
JavaFX Script is a declarative, statically-typed, object-oriented and functional domain-specific language designed for GUI development. The JavaFX SDK provide powerful libraries that make creating media-rich and compelling GUI applications much easier.
The ubiquity of the JRE in all popular operating systems and hand-held devices gives the JavaFX developer a wide range of targets for their applications.
I would like to thank Mark Volkmann, Lance Finney and Mario Aquino for their help in reviewing this article. I would also like to thank Naoto Sato, Richard Bair and Dean Iverson for their corrections and suggestions for improvements.
References
- [1] JavaFX.com
- [2] JavaFX Technology site at java.sun.com
- [3] The openjfx-compiler project
- [4] Project Scene Graph
- [5] James Weaver's JavaFX Blog
- [6] The JavaFX Community Wiki
Software Engineering Tech Trends is a monthly publication featuring emerging trends in software engineering. | https://objectcomputing.com/resources/publications/sett/december-2008-experiments-with-javafx-script | CC-MAIN-2019-09 | refinedweb | 9,757 | 63.19 |
I’ve seen quite a few cool projects with Gameboy and Raspberry Pi, such as: this, this and this.
These are really fantastic projects and inspired me to make an attempt at my own Gameboy Color Raspberry Pi – and then attempt a full game of Player Unknowns Battlegrounds on it.
Be aware, I am still fairly amateur to working with cutting plastics and assembling things. And during this build I realised I need some better cutting tools and stuff, so please don’t judge me too harshly for the poor build quality.
- General stuffs, bit of blue tak, tools and some tie-wraps, heatsinks.
- PC with NVIDIA Graphics and Battlegrounds
So at first, my plan was to keep the battery compartment and use 2xAA batteries and voltage boost them up to 5v for the Pi to use, but it seems with a screen etc. attached this caused issues and the screen flickered, so I opted to go for a LiPoly with a PowerBoost 500c.
So I began planning where I would put the Pi, screen etc. by using an old shell I didn’t care about, before cutting up my nice red one:
And so the snipping and fitting began:
I basically had to remove tons of plastic from this to get it all to fit in in the end, the rings around the buttons went, the bottom bits of plastic, the screen, parts of the battery compartment, it was a massacre of ABS plastic. The usual setup for the PowerBoost 500c can be found in my Wrist Watch project. Solder in headers into the Pi and the Pi TFT and then hook them together (with optional heatsink on the Pi beforehand). I got a bit of veroboard for all the buttons to go to GND:
Then wired them all in, as well as the GND from the I2S DAC, with the other end of the buttons going to the following pins:
- 27 – Down
- 22 – A
- 23 – B
- 24 – Right
- 17 – Left
- 5 – Start
- 6 – Up
- 12 – Select
Then connect the veroboard to GND, these should all be available on the Pi TFT breakout.
Wire up the rest of the I2S DAC as per instructions over at Adafruit, for power in on this project I wired VCC to 3v on the Pi as the metal speaker probably won’t like much more going through it.
Ready for some button testing, I built up a Raspbian image using PiBakery:
To map the GPIO buttons to inputs I opted for Python input. Then I loaded up the Python code (also found under the code section in better format):
import RPi.GPIO as GPIO import time import: print(‘Up Button Pressed’) device.emit(uinput.REL_Y, -5) time.sleep(0.2) if input_down == False: print(‘Down Button Pressed’) device.emit(uinput.REL_Y, 5) time.sleep(0.2) if input_left == False: print(‘Left Button Pressed’) device.emit(uinput.REL_X, -5) time.sleep(0.2) if input_right == False: print(‘Right Button Pressed’) device.emit(uinput.REL_X, 5) time.sleep(0.2) if input_start == False: print(‘Start Button Pressed’) time.sleep(0.2) if input_select == False: print(‘Select Button Pressed’) time.sleep(0.2) if input_a == False: print(‘A Button Pressed’) device.emit_click(uinput.BTN_RIGHT) time.sleep(0.2) if input_b == False: print(‘B Button Pressed’)
The guide above for the I2S DAC will also guide through installing and testing the speaker, once that was confirmed working I got to some further testing and placement within the GBC case:
Once I’d cut up enough plastic to melt down and make a statue of myself I was happy with the placement of buttons and circuits – the powerboost is at the bottom right, the DAC bottom left and the metal speaker above the Powerboost; where the original speaker would have been on the original GBC – with some tape on the back to stop it shorting anything.
Also I had to snip up the start/select buttons and the D-Pad to get it to fit (warning: not pretty):
Before properly assembling it all I followed the instructions over at Adafruit for installing the Pi TFT 2.2 and then made a Python script for mouse controls; with the D-Pad moving the mouse around and the A/B keys working the mouse buttons and finally Start and Select for W/S respectively.
In order to get accelerate video through to the Pi TFT, you need to use fbcp. Follow the instructions here. Under X server, Console and Framebuffer mirroring, the only change I found I needed to make was the ‘/usr/share/X11/xorg.conf.d/99-fbdev.conf’ file:
Section "Device" Identifier "myfb" Driver "fbdev" Option "fbdev" "/dev/fb0" EndSection
This makes it write the X server to fb0 which is then copied to fb1 by fbcp, which is then written to the TFT (I think, I could be technically wrong here, but it works for me). In your /etc/rc.local file, put the below in above exit:
fbcp &
This will launch fbcp on boot the & ensures that it will run in the background.
There is also some further adjustments needed in ‘/boot/config.txt’, make sure the file is set to the below:
#=320 framebuffer_height=240 #=320 240 60 1 0 0 dtoverlay=hifiberry-dac dtoverlay=i2s-mmap # — added by adafruit-pitft-helper Mon 11 Sep 07:15:48 UTC 2017 — 22,rotate=90,speed=32000000,fps=60 # — end adafruit-pitft-helper Mon 11 Sep 07:15:48 UTC 2017 —
This will ensure that everything will run at the resolution of the Pi TFT, from here you can reboot and everything should now switch over to the TFT, making working on it interesting at this point because the VNC connection will be tiny, probably best to work from command line from here on in when possible.
There are, of course, more logical things to do at this point, such as installing RetroPie and Adafruits Retrogame to make a little emulation station, but I can’t help doing something ridiculous.
Here’s the code for my buttons (WordPress has messed with the formatting it seems), this is optimal for PUBG as Equals and F key will be used for autorun and interact respectively. I have another code with W/S configured instead for other games:
import RPi.GPIO as GPIOimport RPi.GPIO as GPIOimport timeimport, uinput.KEY_W, uinput.KEY_S, uinput.KEY_EQUAL, uinput.KEY: device.emit(uinput.REL_Y, -60) time.sleep(0.1) if input_down == False: device.emit(uinput.REL_Y, 60) time.sleep(0.1) if input_left == False: device.emit(uinput.REL_X, -60) time.sleep(0.1) if input_right == False: device.emit(uinput.REL_X, 60) time.sleep(0.1) if input_start == False: device.emit_click(uinput.KEY_EQUAL) time.sleep(0.2) if input_select == False: device.emit_click(uinput.KEY_F) time.sleep(0.2) if input_a == False: device.emit_click(uinput.BTN_RIGHT) time.sleep(0.2) if input_b == False: device.emit_click(uinput.BTN_LEFT) time.sleep(0.2) finally: GPIO.cleanup()
To get this to run at the right time to interact with the Pixel GUI I found I had to launch this using a cron command, so type in:
crontab -e
Select your editor of choice and with the python script above in your home directory named as ‘gui_buttons.py’ we can run it easily by putting this new line into cron:
Put It All Together, kind ofPut It All Together, kind of
@reboot sudo python /home/pi/gui_buttons.py &
At this point I replicated the cutting procedure onto my red GBC shell, this is the point where I realized I needed some better cutting tools other than snips and stuff, I have a Dremel but I need a better cutting head for it.
The new GBC shell takes some assembly with the screen cover itself, but this is fairly easy to figure out.
I put the on/off switch for the Powerboost up where the switch was on the GBC and then when I was happy I tie-wrapped the thing and tested the buttons. Once fully satisfied it was going to work properly, I cut a hole for where the SD Card can be inserted/removed and then Sugru’d it all up and reapplied the tie-wraps to hold it together while it set.
The shell I bought also had some stickers and things, these can be applied as needed/wanted.
The way the Pi is facing the ports are all facing up through where the game carts would go in the original GBC; so for maintenance assistance I wanted to put a Bluetooth connector for a small KB in so that it can be connected in and still look relatively authentic, so I cut up an empty cart shell and Sugru’d the nano USB in, with a USB to Micro USB connector inside.
Bit messy, but looks better when plugged in:
With it all together and working I can boot up and navigate about the Pixel GUI using the D-Pad and the A/B buttons, its quite an interesting experience.
In terms of gaming – first I installed Quake 3 by following the instructions here and breaking out one of my copies of Quake 3:
It ran pretty slowly and was hard to use just only being able to look around and run back and forth, so next up, Minecraft!
Which also was fairly impossible to play – but the real reason for this is to try PUBG, right?Moonlighting
Of course the Pi can’t actually run PUBG (until the Pi 6 or something). So we have to stream it from a computer with an Nvidia graphics card. This is where Moonlight comes in, it will work with Gamestream from GeForce experience.
Follow the instructions here to get it set up with the PC/Pi. I made a ‘stream.sh’ file on the desktop to run it:
moonlight stream -width 320 -height 240 -fps 30 -localaudio -app steam –unsupported
Then I ran:
sudo chmod +x /home/pi/Desktop/stream.sh
So that it can be run just by double clicking on the file, perfect for the control scheme I’m using for the GBC Pi – when this is run it will load up Steam in big picture mode and allow you to select Player Unknowns Battlegrounds.And away we go!
Here’s a video of me attempting a few games on the Gameboy – no audio from the game unfortunately, need to find out why moonlight wasn’t playing ball here.
I wasn’t met with much success…Things Learnt/Things to Improve
- Get better tools
- Get better at putting things together and planning
- Figure out why moonlight wasn’t playing audio from the source PC
I think I’ll attempt this again with the above in mind and do the same with a Gameboy Advance – this should allow more room within the shell and also give me 2 extra buttons to use. | https://www.hackster.io/314reactor/battlegrounds-on-game-boy-color-8ed0da | CC-MAIN-2022-27 | refinedweb | 1,816 | 66.17 |
Created on 2008-11-30 16:39 by lcatucci, last changed 2012-11-24 17:15 by python-dev. This issue is now closed.
In the enclosed patch, there are four changes
1. add support for the optional CAPA pop command, since it is needed
for starttls support discovery
2. add support for the STLS pop command
3. replace home-grown file-like methods and replace them with ssl
socket's makefile() in POP3_SSL
4. Properly shutdown sockets at close() time to avoid server-side pile-up
The needed changes to documentation if the patch gets accepted
You might split your patch into smaller patches, example:
* patch 1: implement CAPA method
* patch 2: POP3_SSL refatoring
* patch 3: stls() method
- Do you really need to keep a reference to the "raw" socket
(self._sock) for a SSL connection?
- I don't understand what is sock.shutdown(SHUT_RDWR). When is it
needed? Does it change the behaviour?
- Could you write a method to parse the capabilities because I hate
long lambda function. You may write doctest for the new method :-)
I understand the need to keep things simple, but this time the split
seemed a bit overkill. If needed, I'll redo the patch into a small
series. Thinking of it... I was unsure if it really made sense to split
out smtp/pop/imap patches instead of sending them all at forewalls or the like.
> As for the shutdown before close, it's needed to let the server know
> we are leaving, instead of waiting until socket timeout.
Extracts of an UNIX FAQ [1]:
"Generally the difference between close() and shutdown() is: close()
closes the socket id for the process but the connection is still
opened if another process shares this socket id."
"i have noticed on some (mostly non-unix) operating systems though a
close by all processes (threads) is not enough to correctly flush
data, (or threads) is not. A shutdown must be done, but on many
systems it is superfulous."
So shutdown() is useless on most OS, but it looks like it's better to
use it ;-)
> This is the reason I need to keep the reference to the wrapped
socket.
You don't need to do that. The wrapper already calls shutdown() of the
parent socket (see Lib/ssl.py).
[1]
I'm reasonably sure Victor is right about the original socket being
unneeded. How does the series look now?
"lst[1:] if len(lst)>1 else []" is useless, lst[1:] alone does the
same :-) So it can be simplify to:
def _parsecap(line):
lst = line.split()
return lst[0], lst[1:]
You might add a real example in the capa() docstring.
About poplib_02_sock_shutdown.diff: I'm not sure that poplib is the
right place to fix the issue... if there is really an issue. Why not
calling shutdown directly in socket.close()? :-)
You removed self._sock, nice.
Changed CAPA as requested: now there is a proper docstring, and the
useless if ... else ... is gone.
As for the shutdown/close comment, I think there could be cases
where you are going to close but don't want to shutdown: e.g. you might
close a dup-ed socket, but the other owner would want to continue
working with his copy of the socket.
There is a problem I forgot to state with test_anonlogin:
since I try and test both SSL and starttls, the DoS checker at cmu kicks
in and refuse the login attempt in PopSSLTest. Since I'd rather avoid
cheating, I'm leaning to try logging in as SomeUser, and expecting a
failure in both cases. Comments?
I'm enclosing the expected-failure version of test_popnet. It's much
simpler to talk and comment about something you can see!
How is going? Any hope for 2.7/3.2?
Ping...
Any hope for 2.7/3.2?
3.3 beta will be published next Sunday. Any hope?
Lorenzo, is your patch applicable to 3.3?
I've refreshed the patches to apply on 3.3, and adapted the to the
unit-test framework by giampaolo.rodola.
I've refreshed once more the patches, adding the implementation of the stls command in test_poplib.py.
IMHO, the changes as they stand now are low risk, and could as well go into 3.3.
With many thanks to Giampaolo for implementing the asynchat/asyncore pop3 server!
Lorenzo, 3.3 is in beta mode now. No new features accepted :-(.
Please, fulfill a PSF contributor agreement
Jesús,
as requested, I've scanned and sent the signed contributor agreement.
In the meanwhile, I updated once more patches 01 and 03:
01: stealed the socket shutdown check from Antoine Pitrou's r66134
03: adapt DummyPOP3_SSLHandler to use the handle_read() and
the _do_tls_handshake() methods inherited from DummyPOP3Handler
As for the "no-new-features"... I know, I know... (that's the reason why I wrote that big "in my HUMBLE opionion" ;-)
Hello,
Here are some comments about the patches:
1) poplib_01_socket_shutdown_v3.diff: looks fine to me)
3) poplib_03_starttls_v3.diff:
- same comment about PEP 8
- why did you change the signature of the _create_socket() method? it looks gratuitous
- the new method should be called starttls() as in other modules, not stls()
- starttls() should only take a context argument; no need to support separate keyfile and certfile arguments
- what is the point of catching errors like this:
+ except error_proto as _err:
+ resp = _err
Updated 02 and 03 patches (mostly) in line with Antoine's review comments:
>)
Completely right. Done.
> 3) poplib_03_starttls_v3.diff:
>
> - same comment about PEP 8
where?
> - why did you change the signature of the _create_socket()
> method? it looks gratuitous
undone
> - the new method should be called starttls() as in other modules, not > stls()
Here I'm following: at :ref:`pop3-objects` in Doc/library/poplib.rst,
All POP3 commands are represented by methods of the same name, in
lower-case; most return the response text sent by the server.
IMHO, having a single method with a name different than the underlying
POP command would just be confusing. For this reason, I'd rather avoid
adding an alias like in
starttls = stls
or the reverse...
> - starttls() should only take a context argument; no need to support > separate keyfile and certfile arguments
Right, non need to mimick pre-SSLContext method signatures!
> - what is the point of catching errors like this:
> [...]
undone
> where?
In `caps=self.capa()` (you need a space around the assignment operator).
> Here I'm following: at :ref:`pop3-objects` in Doc/library/poplib.rst,
Ah, ok. Then I agree it makes sense to call it stls(). No need for an alias, IMO.
OK, I'm uploading poplib_03_starttls_v5.diff; I only changed the
"caps=self.capa()" into "caps = self.capa()" in the "@@ -352,21 +360,42 @@ class POP3:" hunk.
Thank you for pointing at the line; I tried to run pep8.py on poplib.py, but failed to find the line, since I was overwhelmed by the reported pre-existing pep8 inconsistencies...
I'm tempted to open a pep8 issue on poplib after we finish with stls...
Thank you very much for reviewing!
Thank you Lorenzo. Your patch lacks a couple of details, such as "versionadded" and "versionchanged" tags, but I can handle this myself.
New changeset 79e33578dc05 by Antoine Pitrou in branch 'default':
Issue #4473: Ensure the socket is shutdown cleanly in POP3.close().
New changeset d30fd9834cec by Antoine Pitrou in branch 'default':
Issue #4473: Add a POP3.capa() method to query the capabilities advertised by the POP3 server.
New changeset 2329f9198d7f by Antoine Pitrou in branch 'default':
Issue #4473: Add a POP3.stls() to switch a clear-text POP3 session into an encrypted POP3 session, on supported servers.
Patches committed. Thank you very much!
New changeset 75a146a657d9 by Antoine Pitrou in branch 'default':
Fix missing import (followup to #4473). | http://bugs.python.org/issue4473 | CC-MAIN-2015-32 | refinedweb | 1,297 | 74.69 |
Teaching is an incredible learning experience. I teach XML and XSLT to developers for corporate trainings and during conferences, and I have found repeatedly that the effort I make to clarify a complex issue for my students helps to further my own understanding. I'm not only teaching the students, I teach myself as well.
Furthermore, students bring their own unique perspectives, which often force me to rethink aspects of certain issues and draw new conclusions. This article was born out of one such experience. I realized that students who have been exposed to JSP, PHP, ASP, or ColdFusion often make incorrect assumptions about XSLT; such assumptions can lead to coding mistakes. While researching how to clarify this topic, I began thinking about how XSLT processors (such as Xalan, Saxon, or MSXML) really work. This new perspective has helped me and I'm sure it will help you too.
Similarities and differences
At first glance, you can see many similarities between Web development languages, such as JSP or PHP, and XSLT. Most significantly, they all let the developer mix code in the middle of HTML tags: With JSP, the code is written in the Java language; with PHP, the code is an ad-hoc scripting language; and with XSLT, the code is XML tags in the XSLT namespace.
This similarity hides a fundamental difference. For JSP (as well as PHP, ASP, and ColdFusion), the HTML tags are treated as text. Indeed when the JSP page is compiled in a servlet, all the HTML tags are moved to write statements. In essence, the mixing of tags and code is just a convenience for the code -- which means you don't have to create a lot of write statements.
Not so with XSLT. An XSLT processor treats tags as first-class citizens. The "T" in XSLT stands for Transformation. Transformation of what? Transformation of XML documents into other XML documents (HTML is treated as a variation of XML) or, to be more precise, transformations of trees into other trees. Trees? Think W3C DOM (the org.w3c.dom package in Java technology). Although modern XSLT processors don't use DOM internally for performance reasons (an optimized library is more efficient), it helps to think of XSLT as a language that converts a DOM tree into another DOM tree.
Unlike JSP or PHP, an XSLT processor does not blindly write the tags in the output. Instead the XSLT processor does the following:
- Loads the input document as a DOM tree (internally the processor optimizes DOM, but it does not matter for this discussion)
- Performs a depth-first walk of the input tree, this is the same depth-first algorithm you learned in programming 101
-
Note that it is possible to select other algorithms besides a depth-first walk. Still, the point I'm trying to make is that the XSLT processor treats its input and its output as trees. That treatment has three important consequences:
- The processor may change the syntax. Depending on the value of the
xsl:outputstatement, the processor may write the result according to XML or HTML syntax. Web development languages cannot do so because they treat HTML tags as text and blindly copy them into the output.
- Although it may fail occasionally, the processor works hard to guarantee that the output is a well-formed XML document.
- You, the developer, have to express your problem in terms of tree manipulation.
I'll show you what that means in the next section.
In this section, I will compare two stylesheets. The first one is a typical XSLT stylesheet; the second is a rewriting that exposes the depth-first walk. While you would not want to adopt this coding style, it helps explain how the processor works.
Listing 1 is a sample XML document while Figure 1 is the corresponding DOM tree. Listing 2 is a simple stylesheet that converts Listing 1 to HTML.
Listing 1. An XML document
Listing 2. A simple stylesheet for HTML publishing
Figure 1. The XML document as the processor sees it
The goal in this section is to rewrite Listing 2 to make the depth-first walk more visible. You'll need named templates for that. If you are not familiar with named templates, they are the equivalent of method calls in XSLT: A named template is a template with a
name attribute. It accepts parameters through the
xsl:param instruction, as follows:
The
xsl:call-template instruction is used (instead of
xsl:apply-templates) to call the template, as follows:
Listing 3 is a rewrite of Listing 2 that makes the tree walking more explicit. Instead of relying on the processor to operate the walk, this stylesheet has a named template,
main, that implements the tree walking.
main is a recursive function -- it accepts a node set in the
current argument and loops over the node set. The bulk of the template is a choose instruction that attempts to find the most appropriate rules for a given node. When processing a node, the template recursively calls itself to process the children of the node.
Listing 3. A stylesheet to expose the walk
If you compare Listing 2 and Listing 3, you will find that they are structurally identical. In Listing 2, the giant choose instruction is implemented behind the scenes through templates. You don't write the choose explicitly, but this is exactly how the processor works. Compare the templates in Listing 2 with the test cases in Listing 3 and you will find a one-to-one match.
Even the last two tests in Listing 3 have direct match in Listing 2 through the default templates. Although, by virtue of being default templates, they need not be written explicitly in Listing 2, the processor has a template for text content and another "catch-all" template.
In Listing 2, the
xsl:apply-templates instruction replaces the recursive call. In many respects, you can think of
xsl:apply-templates as a recursive call into the stylesheet itself! It tells the processor to move to the children of the current node and try to find another template to apply. The loop and the test are very explicit in Listing 3, whereas in Listing 2 they are done implicitly by the processor. In Listing 2, the template takes an extra parameter current; for Listing 1, the parameter is implicit.
xsl:apply-templates automatically changes the current node.
Last but not least is the template parameter. In Listing 3, the templates takes a parameter with the nodes to process. In Listing 2, the templates don't need a parameter because the processor manages the current node. The current node always points to the node to which the templates apply. The current node works like an implicit parameter.
In practice, nobody would write a stylesheet like the one in Listing 3. It is intended for pedagogical purposes only, but it helps to illustrate how the processor works behind the scenes. As you can see if you compare Listings 2 and 3, the processor takes care of much of the basic coding (such as looping and passing parameters) to implement a depth-first search. Keep this in mind when you're working on your next stylesheet and you may find that it changes how you code.
For example, instead of writing:
as XSLT newcomers frequently do, you can write the following code, which is strictly equivalent if you factor in the work of the processor:
I hope I have clarified the inner workings of the XSLT processor. A good understanding of this is essential to improving your stylesheet coding.
- Participate in the discussion forum for Benoît Marchal's "Working XML" column.
- Find out more about XSLT and how it compares to other languages in "What kind of language is XSLT?" by Michael Kay (developerWorks, February 2001) .
- Read "Recurse, not divide, to conquer" (developerWorks, July 2001) for Benoît Marchal's discussion on how to adapt XSLT recursion to address special needs.
- Explore "Mapping files into SOAP requests, Part 2" (developerWorks, January 2004) by Benoît Marchal for another example of using recursion to transform special data with XSLT.
- Learn debugging techniques that offer insight into how a stylesheet works with Uche Ogbuji's article "Debug XSLT on the fly" (developerWorks, November 2002).
- Find hundreds more XML resources on the developerWorks XML zone, including Benoît Marchal's "Working XML" column at the column summary page.
- Get IBM WebSphere Studio Application Developer, an application development product that supports the building of a large spectrum of applications using different technologies such as XML, JSPTM, servlets, HTML, Web services, databases, and EJBs.
-. | http://www.ibm.com/developerworks/xml/library/x-xslang/index.html | crawl-003 | refinedweb | 1,435 | 61.56 |
0
I want to write a simple program to check class and inheritance in Code Blocks but i don't know how to write. I have make new project and add new class named "Car".
This is main class.
#include <iostream> #include "Car.h" using namespace std; int main() { Car c; return 0; }
and this is include\Car.h file.
#ifndef CAR_H #define CAR_H class Car { public: Car(); }; #endif // CAR_H
and this is Car.cpp file code.
#include <iostream> #include "Car.h" using namespace std; Car::Car() { cout << "Car program." <<endl; }
But when i compile and run it, it gives me errors. Please tell me how to resolve this and how to use code blocks. | https://www.daniweb.com/programming/software-development/threads/441377/code-blocks-error | CC-MAIN-2017-39 | refinedweb | 115 | 95.37 |
Question:
I have a funny problem I'd like to ask you guys ('n gals) about.
I'm importing some module A that is importing some non-existent module B. Of course this will result in an ImportError.
This is what A.py looks like
import B
Now let's import A
>>> import A Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/tmp/importtest/A.py", line 1, in <module> import B ImportError: No module named B
Alright, on to the problem. How can I know if this ImportError results from importing A or from some corrupt import inside A without looking at the error's string representation.
The difference is that either A is not there or does have incorrect import statements.
Hope you can help me out...
Cheers bb
Solution:1
There is the
imp module in the standard lib, so you could do:
>>> import imp >>> imp.find_module('collections') (<_io.TextIOWrapper name=4, 'C:\\Program Files\\Python31\\lib\\collections.py', ('.py', 'U', 1)) >>> imp.find_module('col') Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> imp.find_module('col') ImportError: No module named col
which raises
ImportError when module is not found. As it's not trying to import that module it's completely independent on whether
ImportError will be raised by that particular module.
And of course there's a
imp.load_module to actually load that module.
Solution:2
You can also look at the back-trace, which can be examined in the code.
However, why do you want to find out - either way A isn't going to work.
Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
EmoticonEmoticon | http://www.toontricks.com/2019/04/tutorial-python-importing-modules-with.html | CC-MAIN-2019-26 | refinedweb | 289 | 66.94 |
Hi Nguyen,
Good to hear from you? How is ARC doing? I was looking to download a copy the other day
but couldn't find it online anymore.
But yes, we can make those paths configurable just like the models.
If you can, open a Jira to track this? (Anyone should be able to create a new Jira account)
Sent from my iPhone
> On Oct 15, 2015, at 2:55 PM, Thien Nguyen <nguyenminhbaothien@gmail.com> wrote:
>
> Hi all,
>
> It's been awhile (some of you may remember me from ARC) but I'm working on
> embedding the latest cTAKES 3.2.2 into some tooling. I ran into an issue
> with classes in the `org.apache.ctakes.assertion.medfacts.cleartk` because
> the analysis engines there have explicit paths for the
> `ContextWordWindowExtractor`. For example:
>
> public class HistoryCleartkAnalysisEngine extends
> AssertionCleartkAnalysisEngine {
> ...
> private void initialize_history_extractor() {
>
> if(this.entityFeatureExtractors == null){
> this.entityFeatureExtractors = new ArrayList<>();
> }
> this.entityFeatureExtractors.add(*new
> ContextWordWindowExtractor("org/apache/ctakes/assertion/models/history.txt")*
> );
> this.entityFeatureExtractors.add(new
> HistoryFeaturesExtractor());
> }
> ...
>
> And this forced me to put those files into the root of my project (i.e.
> /my-project/org/apache/ctakes/assertion/models/history.txt). Since it seems
> all other resources have the paths configurable in the descriptor xml
> files, should these follow suit and be considered a bug?
>
> Thanks again for all your work on cTAKES. Fun to watch it go from
> pre-Apache days to where it's at now.
>
> Thien | http://mail-archives.apache.org/mod_mbox/ctakes-dev/201510.mbox/%3C5E9B2C73-3A39-410F-8F93-BBDCB0D74216@wiredinformatics.com%3E | CC-MAIN-2017-04 | refinedweb | 240 | 51.75 |
Redux: A Practical Tutorial
Redux: A Practical Tutorial
In this article, a seasoned web developer shows through practical, short examples how Redux works and what its main pieces are.
Join the DZone community and get the full member experience.Join For Free
Bugsnag monitors application stability, so you can make data-driven decisions on whether you should be building new features, or fixing bugs. Learn more.
TL;DR: Shows through practical, short examples how Redux works and what are its main pieces. To find the final code that we are going to create in this article, please check this GitHub repository.
What Is Redux?
Mostly used with React, Redux is a storage facility that helps JavaScript applications to manage state. Note that I started the introductory sentence with "Mostly used." What I mean is that we do not have to use Redux with React. We don't even need a browser to use Redux. We can use it to control the state of a Node.js backend application, for example.
The biggest advantage of Redux is that this facility works as the single source of truth for our data. That is, whenever we want to know the state of our application, we have to look into a single place, the Redux Store. Another advantage of Redux, as we will see in the next section, is that to manage the state, we have only to deal with simple objects and pure functions. Redux does not rely on fancy, extensive APIs. It is quite the opposite actually.
Learning Redux
To learn how to properly use Redux, we have to understand three basic concepts of this library. The first one is called store. When using Redux to manage our state, we let it keep an updated version of this state in the store. This is the main purpose of this piece of Redux. The store exists to hold (store) the current state of our data and to become the single source of truth.
The second concept is called reducer. Reducer is nothing but a pure function that gets our app's current state and generates a new state based on an action. Actions are the third concept that we are interested in. To define an action to be applied to our state, we simply create an object with a
type and any arbitrary number (
0..N) of properties.
For example, we can have as the current state a simple JavaScript object that contains a person's name. To change this state (object), we use a reducer that, based on an action, updates the person with arbitrary data. The following code snippet illustrates these concepts.
const BIRTHDAY_UPDATE = 'BIRTHDAY_UPDATE'; const initialState = {name: 'Bruno Krebs'}; function reducer(state, action) { const { birthday } = action; switch (action.type) { case BIRTHDAY_UPDATE: return { ...state, birthday }; default: return state; } } const updateAction = { type: BIRTHDAY_UPDATE, birthday: new Date(1984, 10, 20) }; const newState = reducer(initialState, updateAction); console.assert(initialState.birthday === undefined, 'Initial state must not be changed'); console.assert( newState.birthday !== undefined && newState.birthday.getTime() === new Date(1984, 10, 20).getTime(), 'New state must contain 1984/10/20 as the birthday' );
Note that the spread operator (
...state) used in the example above is a feature recently introduced to JavaScript and might not be available on all environments. For example, it is not available on Node.js prior to version
8.2.1. Therefore, we must have a Node.js newer than
8.2.1or we need to run this in a browser compatible with this feature.
In the snippet exhibited, we can see that we use the
initialState to generate a
newState. This new state is the product of calling the
reducer function with the
updateAction object and the
initialState. After passing the state and the action to the reducer, we get a new state where we can still find the name of the person, and the new
birthday property correctly applied.
Although simple, the code snippet used above shows another concept that is quite important when using Redux. The state does not change. What happens is that we have to generate a new state (or return the same) when using Redux. One pro of creating new states instead of updating the current one is that, by following this paradigm, we enable traceability in our application's state. By enabling traceability, we also enable other great features like the possibility to time travel.
After understanding these three concepts (well, four with state immutability), we are ready to start using Redux in practice. In the following sections, we are going to create a small Node.js script that uses Redux to manage state.
Using Redux
You might have noticed that we haven't used Redux in the previous section. A great characteristic of Redux is that it relies on simple concepts and structures. As we will see, introducing Redux to manage states in apps is easy. The Redux library itself is quite small, has great performance, and is really intuitive.
To keep things organized, let's create a new Node.js project, and add actions and reducers to it. In a terminal, let's issue the following commands:
# create a dir to our project mkdir redux-node # change working directory to it cd redux-node # initialize the directory as a NPM project npm init -y # create the source folder mkdir src # create files for the main app, actions, and reducers touch src/index.js src/actions.js src/reducers.js
These commands will give us a brand new project with the basic structure that we will need. To make our lives easier, and before proceeding with the next steps, let's open this project on an IDE (like WebStorm or Visual Studio Code).
Creating Redux Actions
Now, let's open the
src/actions.js file and add the following action creators and action types to it:
// action types export const ADD_EXPENSE = 'ADD_EXPENSE'; export const REMOVE_EXPENSE = 'REMOVE_EXPENSE'; // action creators export const addExpense = expense => ({ type: ADD_EXPENSE, expense }); export const removeExpense = expense => ({ type: REMOVE_EXPENSE, expense });
These action creators are quite simple. They simply return objects that contain
type, to indicate if it is a removal or an addition, and an
expense as the payload. We won't invest time creating automated tests to these action creators, as they are trivial.
Creating Redux Reducers
We are going to add the business logic of our tutorial app in the reducer that we are going to create in this section. This reducer will have a
switch statement that, based on an action, will trigger the proper function to generate the new state. Let's open the
src/reducers.js file and add the following reducer definition to it:
import {ADD_EXPENSE, REMOVE_EXPENSE} from "./actions"; export default expenses; export const initialState = { expenses: [], balance: 0 }; function expenses(state = initialState, action = {}) { switch (action.type) { case ADD_EXPENSE: return addExpense(state, action.expense); case REMOVE_EXPENSE: return removeExpense(state, action.expense); default: return state; } } function addExpense(state, expense) { return { ...state, expenses: [...state.expenses, expense], balance: state.balance + expense.amount } } function removeExpense(state, expense) { const persistedExpense = state.expenses.find(item => item.id === expense.id); return { ...state, expenses: state.expenses.filter(item => item.id !== expense.id), balance: state.balance - persistedExpense.amount } }
To decide exactly what function to call (
addExpense or
removeExpense), the reducer created by this file (
expenses) compares the
action.type with both
ADD_EXPENSE and
REMOVE_EXPENSE constants. After identifying the correct type, it triggers the proper function passing the current
state of the application and the
expense in question.
Testing Redux Reducers With Jest
It is easy to create an automated test to validate the behavior of this reducer. As reducers are pure functions, we don't need to mock anything. We just need to generate some samples of expenses and actions, trigger our reducer with them, and check the generated output. Let's install the test runner to help us testing the reducer.
npm i -D jest babel-jest babel-preset-es2015
Also, let's update the
scripts property in the
package.json file so we can easily run
jest:
{ // ... "scripts": { "test": "jest", "test:watch": "npm test -- --watch" } // ... }
With these scripts in place, we can create the test suite that will validate the
expenses reducer. Let's create a file called
reducers.test.js alongside with
reducers.js and define two tests in a new test suite, as follows:
import {addExpense, removeExpense} from './actions'; import expenses, {initialState} from './reducers'; describe('reducers', () => { it('should be able to add expenses', () => { const stateStep1 = expenses(initialState, addExpense({ id: 1, amount: 20 })); expect(stateStep1.expenses.length).toEqual(1); expect(stateStep1.balance).toEqual(20); const stateStep2 = expenses(stateStep1, addExpense({ id: 2, amount: 10 })); expect(stateStep2.expenses.length).toEqual(2); expect(stateStep2.balance).toEqual(30); }); it('should be able to remove expenses', () => { const stateStep1 = expenses(initialState, addExpense({ id: 1, amount: 55 })); expect(stateStep1.expenses.length).toEqual(1); expect(stateStep1.balance).toEqual(55); const stateStep2 = expenses(stateStep1, addExpense({ id: 2, amount: 36 })); expect(stateStep2.expenses.length).toEqual(2); expect(stateStep2.balance).toEqual(91); const stateStep3 = expenses(stateStep2, removeExpense({ id: 1 })); expect(stateStep3.expenses.length).toEqual(1); expect(stateStep3.balance).toEqual(36); }); it('should return the default state', () => { expect(expenses()).toEqual(initialState); }); });
The test suite and its tests are a little bit verbose, but they are easy to understand. We start by importing the
addExpense and
removeExpense action creators. After that, we import the
expenses reducer from its source alongside with the
initialState. Lastly, we use the
describe function to define the test suite and the
it function to create three tests.
The first two tests are pretty similar. Therefore, let's analyze the first one to understand how they work. The first step executed by this test calls the
expenses reducer passing to it the
initialState and the
addExpense action creator. As the parameter of this action creator, we pass an expense with
id = 1 and
amount = 20. We then check if the result of the
expenses execution, the
stateStep1, contains a single expense and if the
balance is equal 20. After that, we execute a similar process that validates if the
expenses reducer accepts a new expense and updates the
balance accordingly. The difference in the second test is that, after adding two expenses, we use the reducer to remove an expense.
Let's run the
npm test command to verify our implementation. If we followed the steps above correctly, we should get an output similar this:
> redux-node@1.0.0 test /Users/brunokrebs/git/tmp/redux-node > jest PASS src/reducers.test.js reducers ✓ should be able to add expenses (3ms) ✓ should be able to remove expenses (1ms) ✓ should return the default state Test Suites: 1 passed, 1 total Tests: 3 passed, 3 total Snapshots: 0 total Time: 0.834s, estimated 1s Ran all test suites.
Defining a Redux Store
So far, we haven't used the central piece of Redux, the Redux Store. We have only defined two functions to create Redux Actions and a Redux Reducer. Now it's time to create a Redux Store and put our reducer and our action creators to work.
As we want to use modern JavaScript code, let's install
babel-cli and a plugin:
npm i -D babel-cli babel-plugin-transform-object-rest-spread
The plugin simply guarantees that we can use the spread operator with Babel. After installing both dependencies, let's open the
index.js file and add the following code:
import {createStore} from 'redux'; import {addExpense, removeExpense} from './actions'; import expenses from './reducers'; const store = createStore(expenses); store.dispatch(addExpense({ id: 1, amount: 45 })); store.dispatch(addExpense({ id: 2, amount: 20 })); store.dispatch(addExpense({ id: 3, amount: 30 })); store.dispatch(removeExpense({ id: 2 })); console.assert(store.getState().balance === 75); console.assert(store.getState().expenses.length === 2);
Pretty simple, right? To create a Redux Store, all we had to do was to import the
createStore function from Redux and call it passing our reducer. Interacting with the store was not hard either. After importing the action creators, we simply called the
dispatch function of the store, passing to it actions created by our action creators (
addExpense and
removeExpense).
In the end, to verify that the store ended up in the correct state, we added two
console.assert calls. The first one showed that the
balance is indeed 75, and the second one guaranteed that we finished with two expenses in the last state.
To run our code, we need to use the command provided by Babel. To easily run this command, let's edit the
package.json file and add the following record to the
script property:
{ // ... "scripts": { "start": "babel-node src/", // ... }, // ... }
After that, we can simply issue
npm start and we will see Babel run our code and assert that we get the expected state.
Aside: Auth0 Authentication With JavaScript
Auth0 offers a free tier to get started with modern authentication. Check it out!
Centralized Login Page
It's as easy as installing the and node modules like so:
npm install jwt-decode auth0-js --save);
Get the full example using this code.
Go ahead and check out our quickstarts to learn how to implement authentication using different languages and frameworks in your apps.
Conclusion
As we can see, Redux is an easy technology to reason about. Although not hard, correctly understanding its three main pieces (the store, reducers, and actions) is important before we move to other topics, like integrating with front-end frameworks. However, once we learn Redux's concepts, we can integrate it with, for example, React to get a great foundation for modern Single Page Apps.
By the way, in our blog, we have an article that shows how to properly secure React and Redux Apps with JWTs. Take a look at it if you are going to use these technologies in your next project.
Monitor application stability with Bugsnag to decide if your engineering team should be building new features on your roadmap or fixing bugs to stabilize your application.Try it free.
Published at DZone with permission of Bruno Krebs , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/redux-a-practical-tutorial | CC-MAIN-2018-43 | refinedweb | 2,353 | 57.27 |
My form class
from django import forms class Form(forms.Form): your_name = forms.CharField(label='Your name ', max_length=100)
My app file
__init__.py
from django import forms from my_app.forms import Form from captcha.fields import ReCaptchaField def register(form): form.captcha=CaptchaField() register(Form)
Code in
__init__.py add an attribute captcha but it is not on the page.
I tried so
My form class
from django import forms class Form(forms.Form): your_name = forms.CharField(label='Your name ', max_length=100) captcha=CaptchaField()
It works, but I have a different! I want to add a сaptcha many forms. I want to add the captcha without changing the form classes. I want to change the form classes during initialization. How to do it???
You need to assign the field to
form.fields, not just
form.
However this is not really the way to do this. Instead, you should make all your forms inherit from a shared parent class, which defines the
captcha field. | https://databasefaq.com/index.php/answer/3018/python-django-forms-django-forms-django-add-an-attribute-class-form-in-init-py | CC-MAIN-2019-51 | refinedweb | 164 | 80.78 |
Analysis and implementation of chessboard coverage
1, What is a chessboard overlay?
In a chessboard composed of 2^k * 2^k squares, if exactly one square is different from other squares, the square is called a special square, and the chessboard is called a special chessboard. Obviously, there are 4^k situations where special squares appear on the chessboard, that is, k > = 0, and there are 4^k different special chessboards.
Chessboard covering: cover all squares except the special square on a given special chessboard (i.e. the position of the special square has been determined) with four different forms of L-shaped dominoes, and any two L-shaped dominoes shall not be covered repeatedly. According to the rules, it is easy to know that the number of L-shaped bone discs used in the 2^k*2^k chessboard coverage is exactly (4^k-1)/3, that is (number of all squares - number of special squares) / 3.
The following figure shows a special chessboard (three small squares of the same color form an L-shaped dominoes) and four different forms of L-shaped dominoes when k=2. The blue one is a special square:
A special chessboard when k=2 4 different types of L-shaped dominoes
2, Ideas and methods of realizing chessboard coverage
The basic method of chessboard coverage is divide and conquer. It is a simple algorithm for designing chessboard coverage. What is divide and conquer?
The basic idea of divide and conquer method: decompose a problem with scale n into k smaller subproblems, which are independent of each other and the same as the original problem. Solve these subproblems recursively, and then combine the solutions of each subproblem to obtain the solution of the original problem. In short, decompose the problem with scale n from top to bottom until the subproblem is decomposed to a small enough size to accommodate When it is easy to solve, it is merged from bottom to top to obtain the original solution.
Analysis idea: when k > 0, divide the 2^k*2^k chessboard into four 2^(k-1)*2^(k-1) sub chessboards, as shown in the figure:
The special checkerboard must be located in the four small checkerboards, and the other three sub checkerboards do not have special checkerboards. In order to convert the three sub checkerboards without special checkerboards into special checkerboards, we can cover the junction of the three smaller checkerboards with an L-shaped bone plate, as shown in the figure:
As can be seen from the figure, the squares covered by L-shaped dominoes on the three sub chessboards become the special squares on the chessboard, so the problem is decomposed into four small-scale chessboard coverage problems. This segmentation method is used recursively until the chessboard is simplified to 1 * 1 chessboard, and the recursion ends.
Analysis to realize this algorithm: judge the four small blocks after segmentation each time to judge whether the special square is inside. The judgment method here is to record the row and column coordinates of the square in the upper left corner of the whole large block each time, and then compare with the coordinates of the special square to know whether the special square is in the block. If the special square is inside, it is directly If not, mark the squares in the lower right corner, lower left corner, upper right corner or upper left corner as special squares according to the different positions of the divided four squares, and then continue the recursion. In the recursion function, there is also a variable s to record the number of squares on the edge. Each time the other block is divided, the number of squares on the edge will be halved. This variable is for square Then determine the position of the special grid.
3, Chessboard coverage of the specific implementation code
#include <stdio.h> 2 #include <stdlib.h> 3 4 int num = 0; 5 int Matrix[100][100]; 6 void chessBoard(int tr, int tc, int dr, int dc, int size); 7 int main() 8 { 9 int size,r,c,row,col; 10 printf("Please enter the row and column number of the chessboard"); 11 scanf("%d",&size); 12 printf("Please enter the row and column number of the special grid"); 13 scanf("%d %d",&row,&col); 14 chessBoard(0,0,row,col,size); 15 16 for (r = 0; r < size; r++) 17 { 18 for (c = 0; c < size; c++) 19 { 20 printf("%2d ",Matrix[r][c]); 21 } 22 printf("\n"); 23 } 24 25 return 0; 26 } 27 28 void chessBoard(int tr, int tc, int dr, int dc, int size) 29 { 30 31 int s,t; 32 if (size==1) return; 33 s = size/2; //Split chessboard 34 t = ++num; //L-shaped dominoes 35 if (dr < tr + s && dc < tc +s) //Cover the upper left corner of the checkerboard 36 { 37 //Special squares in this chessboard 38 chessBoard(tr,tc,dr,dc,s); 39 } 40 else //There are no special squares in this chessboard 41 { 42 //Cover the lower right corner with t-shaped L-shaped dominoes 43 Matrix[tr+s-1][tc+s-1] = t; 44 //Cover the remaining squares 45 chessBoard(tr,tc,tr+s-1,tc+s-1,s); 46 } 47 //Cover the upper right corner of the checkerboard 48 if (dr < tr + s && dc >= tc + s ) // 49 { 50 //Special squares in this chessboard 51 chessBoard(tr,tc+s,dr,dc,s); 52 } 53 else //There are no special squares in this chessboard 54 { 55 //Cover the lower left corner with a t-shaped L-shaped dominoes 56 Matrix[tr+s-1][tc+s] = t; 57 //Cover the remaining squares 58 chessBoard(tr,tc+s,tr+s-1,tc+s,s); 59 } 60 //Cover the lower left checkerboard 61 if (dr >= tr + s && dc < tc + s) 62 { 63 //Special squares in this chessboard 64 chessBoard(tr+s,tc,dr,dc,s); 65 } 66 else 67 { 68 //Cover the upper right corner with t-shaped L-shaped dominoes 69 Matrix[tr+s][tc+s-1] = t; 70 //Cover the remaining squares 71 chessBoard(tr+s,tc,tr+s,tc+s-1,s); 72 } 73 //Cover the lower right checkerboard 74 if (dr >= tr + s && dc >= tc + s) 75 { 76 //Special squares in this chessboard 77 chessBoard(tr+s,tc+s,dr,dc,s); 78 } 79 else 80 { 81 //Cover the upper left corner with t-shaped L-shaped dominoes 82 Matrix[tr+s][tc+s] = t; 83 //Cover the remaining squares 84 chessBoard(tr+s,tc+s,tr+s,tc+s,s); 85 } 86 87 }
The operation results are as follows:
Reference:
1,
2. Computer algorithm design and analysis Wang Xiaodong fifth edition. (if you need the answers to the exercises after class, you can leave a message in the comment area, and I will send a link) | https://programmer.help/blogs/algorithm-detailed-explanation-of-chessboard-coverage-basic-tutorial.html | CC-MAIN-2021-49 | refinedweb | 1,147 | 50.84 |
ReadMe Language | 中文版 | English |
ASRT Project Home Page | Released Download | View this project's wiki document (Chinese) | Experience Demo | Donate
If you have any questions in your works with this project, welcome to put up issues in this repo and I will response as soon as possible.
You can check the FAQ Page (Chinese) first before asking questions to avoid repeating questions.
A post about ASRT's introduction
About how to use ASRT to train and deploy:
For questions about the principles of the statistical language model that are often asked, see:
For questions about CTC, see:
For more infomation please refer to author's blog website: AILemon Blog (Chinese)
This project uses Keras, TensorFlow based on deep convolutional neural network and long-short memory neural network, attention mechanism and CTC to implement.
First, clone the project to your computer through Git, and then download the data sets needed for the training of this project. For the download links, please refer to End of Document
$ git clone
Or you can use the "Fork" button to copy a copy of the project and then clone it locally with your own SSH key.
After cloning the repository via git, go to the project root directory; create a subdirectory
dataset/ (you can use a soft link instead), and then extract the downloaded datasets directly into it.
Note that in the current version, both the Thchs30 and ST-CMDS data sets must be downloaded and used, and using other data sets need to modify the sourece codes.
$ cd ASRT_SpeechRecognition $ mkdir dataset $ tar zxf <dataset zip files name> -C dataset/
Then, you need to copy all the files in the 'datalist' directory to the dataset directory, that is, put them together with the data set.
$ cp -rf datalist/* dataset/
Currently available models are 24, 25 and 251
Before running this project, please install the necessary Python3 version dependent library
To start training this project, please execute:
$ python3 train_mspeech.py
To start the test of this project, please execute:
$ python3 test_mspeech.py
Before testing, make sure the model file path filled in the code files exists.
ASRT API Server startup please execute:
$ python3 asrserver.py
Please note that after opening the API server, you need to use the client software corresponding to this ASRT project for voice recognition. For details, see the Wiki documentation ASRT Client Demo.
If you want to train and use Model 251, make changes in the corresponding position of the
import SpeechModel in the code files.
If there is any problem during the execution of the program or during use, it can be promptly put forward in the issue, and I will reply as soon as possible.
CNN + LSTM/GRU + CTC
The maximum length of the input audio is 16 seconds, and the output is the corresponding Chinese pinyin sequence.
The complete source program that includes trained model weights can be obtained from the archives of the various versions of the software released in the releases page of Github.
The released finished software can be downloaded here: ASRT download page
Maximum Entropy Hidden Markov Model Based on Probability Graph.
The input is a Chinese pinyin sequence, and the output is the corresponding Chinese character text.
At present, the best model can basically reach 80% of Pinyin correct rate on the test set.
However, as the current international and domestic teams can achieve 98%, the accuracy rate still needs to be further improved.
Dependent Environment Details
Some free Chinese speech datasets (Chinese)
Tsinghua University THCHS30 Chinese voice data set
data_thchs30.tgz Download
Free ST Chinese Mandarin Corpus
ST-CMDS-20170001_1-OS.tar.gz Download
AIShell-1 Open Source Dataset
data_aishell.tgz Download
Note:unzip this dataset
$ tar xzf data_aishell.tgz $ cd data_aishell/wav $ for tar in *.tar.gz; do tar xvf $tar; done
Primewords Chinese Corpus Set 1
primewords_md_2018_set1.tar.gz Download
aidatatang_200zh
aidatatang_200zh.tgz Download
MagicData
train_set.tar.gz Download
Special thanks! Thanks to the predecessors' public voice data set.
If the provided dataset link cannot be opened and downloaded, click this link OpenSLR
GPL v3.0 © nl8590687 Author: ailemon
@zw76859420 @madeirak @ZJUGuoShuai @williamchenwl
@nl8590687 (repo owner)
Activity
Community
Health
Trend
Influence
:Code submit frequency
:React/respond to issue & PR etc.
:Well-balanced team members and collaboration
:Recent popularity of project
:Star counts, download counts etc. | https://gitee.com/ailemon/ASRT_SpeechRecognition | CC-MAIN-2021-04 | refinedweb | 714 | 60.04 |
08-06-2019
11:10 AM
IoT Hub message routing now supports routing messages to Azure Data Lake Store (ADLS) Gen2 in public preview.
ADLS Gen 2 is designed specifically for enterprises to run large scale analytics workloads in the cloud. You can utilize the existing route to storage (through CLI/PowerShell/Portal/ARM) to send messages to ADLS Gen2 accounts, which are hierarchical namespace-enabled storage accounts built on top of Blob storage. This also brings Azure IoT Hub a step closer to supporting Common Data Model (CDM) - an effort we are working towards to aid Microsoft’s Open Data Initiative.
This was achieved through collaboration with Azure storage team, who enabled the Blob APIs to integrate with ADLS Gen2 for accessing data, announced through this blog. This capability is available for new ADLS Gen2 storage accounts in regions - West US 2 and West Central US. Support for existing storage accounts will roll out by next month and we aim to enable all regions and GA by early next year. | https://techcommunity.microsoft.com/t5/azure-iot/you-can-now-route-iot-devices-messages-to-azure-data-lake-gen-2/m-p/790674 | CC-MAIN-2020-16 | refinedweb | 171 | 56.29 |
Next: Shift and Reset, Up: Prompts [Contents][Index]
Guile’s primitive delimited control operators are
call-with-prompt and
abort-to-prompt.
Set up a prompt, and call thunk within that prompt.
During the dynamic extent of the call to thunk, a prompt named tag
will be present in the dynamic context, such that if a user calls
abort-to-prompt (see below) with that tag, control rewinds back to the
prompt, and the handler is run.
handler must be a procedure. The first argument to handler will be
the state of the computation begun when thunk was called, and ending with
the call to
abort-to-prompt. The remaining arguments to handler are
those passed to
abort-to-prompt.
Make a new prompt tag. Currently prompt tags are generated symbols. This may change in some future Guile version.
Return the default prompt tag. Having a distinguished default prompt tag allows some useful prompt and abort idioms, discussed in the next section.
Unwind the dynamic and control context to the nearest prompt named tag, also passing the given values.
C programmers may recognize
call-with-prompt and
abort-to-prompt
as a fancy kind of
setjmp and
longjmp, respectively. Prompts are
indeed quite useful as non-local escape mechanisms. Guile’s
catch and
throw are implemented in terms of prompts. Prompts are more convenient
than
longjmp, in that one has the opportunity to pass multiple values to
the jump target.
Also unlike
longjmp, the prompt handler is given the full state of the
process that was aborted, as the first argument to the prompt’s handler. That
state is the continuation of the computation wrapped by the prompt. It is
a delimited continuation, because it is not the whole continuation of the
program; rather, just the computation initiated by the call to
call-with-prompt.
The continuation is a procedure, and may be reinstated simply by invoking it, with any number of values. Here’s where things get interesting, and complicated as well. Besides being described as delimited, continuations reified by prompts are also composable, because invoking a prompt-saved continuation composes that continuation with the current one.
Imagine you have saved a continuation via call-with-prompt:
(define cont (call-with-prompt ;; tag 'foo ;; thunk (lambda () (+ 34 (abort-to-prompt 'foo))) ;; handler (lambda (k) k)))
The resulting continuation is the addition of 34. It’s as if you had written:
(define cont (lambda (x) (+ 34 x)))
So, if we call
cont with one numeric value, we get that number,
incremented by 34:
(cont 8) ⇒ 42 (* 2 (cont 8)) ⇒ 84
The last example illustrates what we mean when we say, "composes with the
current continuation". We mean that there is a current continuation – some
remaining things to compute, like
(lambda (x) (* x 2)) – and that
calling the saved continuation doesn’t wipe out the current continuation, it
composes the saved continuation with the current one.
We’re belaboring the point here because traditional Scheme continuations, as discussed in the next section, aren’t composable, and are actually less expressive than continuations captured by prompts. But there’s a place for them both.
Before moving on, we should mention that if the handler of a prompt is a
lambda expression, and the first argument isn’t referenced, an abort to
that prompt will not cause a continuation to be reified. This can be an
important efficiency consideration to keep in mind.
One example where this optimization matters is escape continuations. Escape continuations are delimited continuations whose only use is to make a non-local exit—i.e., to escape from the current continuation. Such continuations are invoked only once, and for this reason they are sometimes called one-shot continuations. A common use of escape continuations is when throwing an exception (see Exceptions).
The constructs below are syntactic sugar atop prompts to simplify the use of escape continuations.
Call proc with an escape continuation.
In the example below, the return continuation is used to escape
the continuation of the call to
fold.
(use-modules (ice-9 control) (srfi srfi-1)) (define (prefix x lst) ;; Return all the elements before the first occurrence ;; of X in LST. (call/ec (lambda (return) (fold (lambda (element prefix) (if (equal? element x) (return (reverse prefix)) ; escape `fold' (cons element prefix))) '() lst)))) (prefix 'a '(0 1 2 a 3 4 5)) ⇒ (0 1 2)
Bind k within body to an escape continuation.
This is equivalent to
(call/ec (lambda (k) body …)).
Next: Shift and Reset, Up: Prompts [Contents][Index] | http://www.gnu.org/software/guile/manual/html_node/Prompt-Primitives.html | CC-MAIN-2014-15 | refinedweb | 753 | 54.32 |
I'm just learning Java, so please bear with my ignorance. I have a feeling (hope) that this question has a very simple answer, just one that is evading me at the moment.
For our assignment, we have to write a boolean function that will take a given elephant, "e" (the program we're writing is used to store data about elephants) and return true if this elephant is e's mother, and e isn't null.
We have also previously written a getMother() function that will return the elephant's mother.
As such, I need to ensure e isn't null, and verify that e.getMother() returns the name of the elephant calling the function. Sounded easy enough, but several, several hours later I'm no closer to figuring out how to do that.
For example:
Elephant mom = new Elephant("Mom", 1990, 2, 'f'); Elephant dad = new Elephant("Dad", 1990, 10, 'm'); Elephant kid = new Elephant ("Joey", 1995, 7, 'M', 5, mom, dad); mom.isMotherOf(kid); //Needs to return true
e.getMother will return the name of e's mother, but I don't know how to compare that to whatever elephant is calling the function
boolean isMotherOf(Elephant e) { return ( e != null && e.getMother() == /* ?????? */) }
Fot context, a copy of the assignemnt can be found here.
If anyone could point me in the right direction, it would greatly be appreciated. I've already spent more time on his than I did every project up to this point. Let me know if I need to clarify anything, or provide any of my previous code. | https://www.daniweb.com/programming/software-development/threads/413825/need-help-with-a-probably-very-simple-java-assignment | CC-MAIN-2020-05 | refinedweb | 264 | 70.53 |
Single Line Nested For Loops
Wrote this function in python that transposes a matrix:
def transpose(m): height = len(m) width = len(m[0]) return [ [ m[i][j] for i in range(0, height) ] for j in range(0, width) ]
In the process I realized I don't fully understand how single line nested for loops execute. Please help me understand by answering the following questions:
- What is the order in which this for loop executes?
- If I had a triple nested for loop, what order would it execute?
- What would be equal the equal unnested for loop?
Given,
[ function(i,j) for i,j in object ]
- What type must object be in order to use this for loop structure?
- What is the order in which i and j are assigned to elements in object?
- Can it be simulated by a different for loop structure?
- Can this for loop be nested with a similar or different structure for loop? And how would it look?
Additional information is appreciated as well.
The best source of information is the official Python tutorial on list comprehensions. List comprehensions are nearly the same as for loops (certainly any list comprehension can be written as a for-loop) but they are often faster than using a for loop.
Look at this longer list comprehension from the tutorial (the
if part filters the comprehension, only parts that pass the if statement are passed into the final part of the list comprehension (here
(x,y)):
>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
It's exactly the same as this nested for loop (and, as the tutorial says, note how the order of for and if are the same).
>>> combs = [] >>> for x in [1,2,3]: ... for y in [3,1,4]: ... if x != y: ... combs.append((x, y)) ... >>> combs [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
The major difference between a list comprehension and a for loop is that the final part of the for loop (where you do something) comes at the beginning rather than at the end.
On to your q:
What type must object be in order to use this for loop structure?
An iterable. Any object that can generate a (finite) set of elements. These include any container, lists, sets, generators, etc.
What is the order in which i and j are assigned to elements in object?
They are assigned in exactly the same order as they are generated from each list, as if they were in a nested for loop (for your first comprehension you'd get 1 element for i, then every value from j, 2nd element into i, then every value from j, etc.)
Can it be simulated by a different for loop structure?
Yes, already shown above.
Can this for loop be nested with a similar or different structure for loop? And how would it look?
Sure, but it's not a great idea. Here, for example, gives you a list of lists of characters:
[[ch for ch in word] for word in ("apple", "banana", "pear", "the", "hello")]
From: stackoverflow.com/q/17006641 | https://python-decompiler.com/article/2013-06/single-line-nested-for-loops | CC-MAIN-2020-10 | refinedweb | 545 | 69.72 |
DNS is most commonly associated with the Internet. However, private networks use DNS extensively to resolve computer names and to locate computers within their local networks and the Internet. DNS provides the following benefits: (called a subdomain). Consequently, a domain's name identifies its position in the hierarchy. For example, in Figure 5.1, the domain name sales.microsoft.com identifies the sales domain as a subdomain of the microsoft.com domain and microsoft as a subdomain of the com domain.
The hierarchical structure of the domain namespace consists of a root domain, top-level domains, second-level domains, and host names.
The root domain is at the top of the hierarchy and is represented as a period (.). The Internet root domain is managed by several organizations, including Network Solutions, Inc.
Top-level domains are two- or three-character name codes. Top-level domains are grouped by organization type or geographic location. Table 5.1 provides some examples of top-level domain names.
Table 5.1??Top-Level Domains
Top-level domains can contain second-level domains and host names.
Organizations such as Network Solutions, Inc., assign and register second-level domains to individuals and organizations for the Internet. A second-level name has two name parts: a top-level name and a unique second-level name. Table 5.2 provides some examples of second-level domains.
Table 5.2??Second-Level Domains
Host names refer to specific computers on the Internet or a private network. For example, in Figure 5.1, Computer1 is a host name. A host name is the leftmost portion of a fully qualified domain name (FQDN), which describes the exact position of a host within the domain hierarchy. In Figure 5.1, Computer1.sales.microsoft.com. (including the end period, which represents the root domain) is an FQDN.
DNS uses a host's FQDN to resolve a name to an IP address.
When you create a domain namespace, consider the following domain guidelines and standard naming conventions:
A zone represents a discrete portion of the domain namespace. Zones provide a way to partition the domain namespace into manageable sections and they provide the following functions:
The name-to-IP address mappings for a zone are stored in the zone database file. Each zone is anchored to a specific domain, referred to as the zone's root domain. The zone database file does not necessarily contain information for all subdomains of the zone's root domain, only those subdomains within the zone.
In Figure 5.2, the root domain for Zone1 is microsoft.com, and its zone file contains the name-to-IP address mappings for the microsoft and sales domains. The root domain for Zone2 is development, and its zone file contains the name-to-IP address mappings only for the development domain. The zone file for Zone1 does not contain the name-to-IP address mappings for the development domain, although development is a subdomain of the microsoft domain..
Multiple name servers act as a backup to the name server containing the primary zone database file. Multiple name servers provide the following advantages:." | https://etutorials.org/Microsoft+Products/microsoft+windows+xp+professional+training+kit/Chapter+5+-+Using+the+DNS+Service+and+Active+Directory+Service/Lesson+1nbspUnderstanding+DNS/ | CC-MAIN-2022-21 | refinedweb | 519 | 50.02 |
Introduction
In our Python file handling Tutorial, we learned how to manipulate files from within Python. In this tutorial, we’ll learn how to delete files in Python.
We know how to read from and write to a file in Python. Let’s learn the delete operation in Python today.
Suppose after successfully creating a file, we perform some operations on it like reading and writing. As soon as we are done using the file for analyzing different sets of data, maybe in some cases, we don’t need it in the future. At this point how do we delete the file? In this tutorial, we are going to learn that.
Methods to Delete Files in Python
Let us take a look at the different methods using which we can delete files in Python.
1. Using the os module
The
os module in Python provides some easy to use methods using which we can delete or remove a file as well as an empty directory. Look at the below-given code carefully:
import os if os.path.isfile('/Users/test/new_file.txt'): os.remove('/Users/test/new_file.txt') print("success") else: print("File doesn't exists!")
Here we have used an if-else statement to avoid the exception that may arise if the file directory doesn’t exist. The method
isfile() checks the existence of the file with filename- ‘new_file.txt’.
Again, the
os module provides us with another method,
rmdir(), which can be used to delete or remove an empty directory. For example:
import os os.rmdir('directory')
Note: The directory must be an empty one. If it contains any content, the method we return an OSerror.
2. Using the shutil module
The shutil is yet another method to delete files in Python that makes it easy for a user to delete a file or its complete directory(including all its contents).
rmtree() is a method under the shutil module which removes a directory and its contents in a recursive manner. Let us see how to use it:
import shutil shutil.rmtree('/test/')
For the above-mentioned code, the directory ‘/test/’ is removed. And most importantly, all the contents inside the directory are also deleted.
3. Using the pathlib module
pathlib is a built-in python module available for Python 3.4+. We can remove a file or an empty directory using this pre-defined module.
Let’s go for an example:
import pathlib file=pathlib.path("test/new_file.txt") file.unlink()
In the above example, the
path() method is used to retrieve the file path whereas, the
unlink() method is used to unlink or remove the file for the specified path.
The unlink() method works for files. If a directory is specified, an OSError is raised. To remove a directory, we can resort to one of the previously discussed methods. | https://www.askpython.com/python/delete-files-in-python | CC-MAIN-2020-16 | refinedweb | 472 | 65.22 |
Been trying to upgrade a python script of mine to use the new Arc 10 syntax what I have is a For loop that I'm trying to recode, and I'm having issues trying to get the name of the raster in each iteration. Anybody got a direction to point me in?
Thanks,
Wade
import arcpy # inDIR = arcpy.getparameterastext(0) # outDIR = arcpy.getparameterastext(1) # clipFC = arcpy.getparameterastext(2) arcpy.env.workspace = "C:/Temp/imagery/" outDIR = "C:/Temp/imagery/clipped/" clipFC = "C:/Temp/clip_shapefile.shp" # raster = rasters.Next() rasters = arcpy.ListRasters() for raster in rasters: # count = 0 name = rasList.next() # while name != None: outname = name.split(".")[0] + "_clip.tif" arcpy.compression= "LZW" arcpy.Clip_management(name, "#", os.path.join(outDIR, outname), clipFC, "#", "ClippingGeometry") # count = count + 1 # name = rasList.next()
Thanks,
Wade
Note these are are all case-sensitive in 10.0. | https://community.esri.com/thread/33831-upgrading-python-code | CC-MAIN-2018-43 | refinedweb | 140 | 55.3 |
May 2012 Report
Xerces-J
There were several students who expressed an interest in GSoC this year and we were fortunate again to have a student with a project proposal that was accepted. For GSoC, Shakya Wijerama will be working on a solution to allow for validation against multiple XML schemas with the same namespace.
With XML Schema 1.1 becoming a W3C Recommendation there appears to be more interest from users in what we've done in Xerces-J. We still need to figure out what remaining work needs to be done to move the support from its beta state into the main release stream.
We are aware that the Apache Lucene project had been distributing its own patched version of Xerces to resolve a problem they were having. The Xerces JIRA issue reported for the problem continues to remain open today because we have been waiting for a consumable test case to be provided. The initial reporter's test was 20 GBs, too large for many to download and analyze. Apparently Lucene has since implemented a workaround and stopped distributing their own Xerces version. We certainly welcome the Lucene developers engagement if they're still interested in a resolution. With more direct communication on the mailing lists this issue might have already been resolved a long time ago.
Mailing list traffic has been moderate (and increasingly lately in part due to GSoC); about 140+ posts on the j-dev and j-users lists since the beginning of March.
No new releases this quarter.
Xerces-C
Moderate development activity during the reporting period: 4 bugs have been filed, 8 have been resolved.
Mailing list traffic has been moderate; about 50+ posts on the c-dev and c-users lists since the beginning of March.
No new releases this quarter.
Xerces-P
Nothing in particular to report. There was no development activity over the reporting period.
XML Commons
The migration from the XML project is finally complete. Thanks to Gareth the website and SVN location have now been moved over to the Xerces domain.
No development activity to report.
Apache Project Branding Requirements
The "TM" symbol has been added to the first main occurrences of "Apache Xerces" on each TLP website page. There's still some work left to do on the TLP website, including adding "TM" to the project logo. | https://wiki.apache.org/xerces/May2012?action=diff | CC-MAIN-2017-43 | refinedweb | 391 | 63.29 |
Java HashMap vs Hashtable0 Comments
The Java collection framework provides several collection implementations to store and operate on objects. Some groups of implementations are similar in the operations they perform, and it is common for novice programmers to use them interchangeably.
ArrayList and
LinkedList are two such implementations that are often confused and incorrectly applied in applications. I have written a post on
ArrayList vs
LinkedList that explains the nuances of them.
In this post, I’ll take up two other implementations that although appears identical, but are inherently different. They are
HashMap and
Hashtable.
HashMap and Hashtable
Both
HashMap and
HashTable implements the
Map interface, a sub interface of the
Collection interface. A
Map stores key-value pairs where duplicate keys are not allowed.
HashMap extends the
AbstractMap class and implements the
Map interface. On the other hand,
Hashtable inherits the
Dictionary class and also implements the
Map interface.
As both
Hashtable and
HashMap implements
Map, they are similar as both stores key-value pairs where the keys are unique and stored as hash values. To store an element in a
Hashtable or
HashMap, you need to specify a key object and its associated value. The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table.
HashMap vs Hashtable
The primary difference between
HashMap and
Hashtable is that
HashMap is not thread-safe, and therefore cannot be shared between multiple threads without external synchronization. On the other hand,
Hashtable is thread safe, and therefore can be shared between multiple threads.
Some other key differences are:
- Because of synchronization and thread safety,
Hashtableis much slower than
HashMapif used in single threaded environment.
HashMapallows one
nullkey and multiple
nullvalues whereas
Hashtabledoesn’t allow
nullvalues.
HashMapis traversed by
Iteratorwhile
Hashtablecan be traversed by both
Iteratorand the legacy
Enumeration.
Iteratorin
HashMapis a fail-fast iterator. It throws
ConcurrentModificationExceptionif any thread other than the iterator’s
remove()method tries to modify the map structurally. Thus, in the face of concurrent modification, the iterator fails fast and cleanly, rather than risking undesirable behaviour. However, The
Enumerationreturned by
Hashtabledoesn’t have this behaviour.
In addition to these differences, one commonly asked question is Why
HashMap stores one null key but
Hashtable does not?
HashMap, allows storing one
null key and multiple
null values. The reason for allowing only one
null key is because keys in a
HashMap has to be unique. On the other hand
Hashtable does not allow
null keys. This is because the objects used as keys in a
Hashtable implements the
hashCode() and
equals() methods for their storage and retrieval. Since
null is not an object it cannot implement the methods. If you try hashing a
null key, it will throw a
NullPointerException.
Testing Operations on HashMap and Hastable
Let us perform some operations on
HashMap and
Hashtable. We will start with an
Item POJO that we will store in both the implementations.
The
Item POJO class is this.
Item.java
package springframework.guru.hashmapvshashtable.model; public class Item { private String item; private int price; public Item() { } public Item(String item, int price) { this.item = item; this.price = price; } public String getItem() { return item; } public void setItem(String item) { this.item = item; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } @Override public String toString() { return "Item{" + "item='" + item + '\'' + ", price=" + price + '}'; } @Override public int hashCode() { int hashcode = 0; hashcode = price * 20; hashcode += item.hashCode(); return hashcode; } @Override public boolean equals(Object obj) { if(obj instanceof Item) { Item i = (Item)obj; return (i.item.equals(this.item) && i.price == this.price); }else { return false; } } }
The preceding code example created an
Item POJO. The class overrides the
hashCode() method. The hash code implementation generates unique hash code for each object based on their state. This means if you have objects with the same state, you will get the same hash code. If you are overriding
hashCode() you need to override the
equals() method also, as present in the preceding code.
I will use JUnit to test operations on both the
HashMap and
Hashtable implementations. If you are new to JUnit, I suggest going through my series on JUnit.
The
ItemTest JUnit test class where I will keep adding test cases is this.
ItemTest.java
package springframework.guru.hashmapvshashtable.model; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.*; import static junit.framework.TestCase.*; public class ItemTest { private Item item, item1,item2,item3; @Before public void setUp() { item = new Item("Water bottle", 20); item1 = new Item("Plate",30); item2 = new Item("Spoon",10); item3 = new Item("Glass", 15); } @After public void tearDown() { item = item1 = item2 = item3 = null; } @Test public void ItemWithHashMapTest() { HashMap<Item, Integer> hashMap = new HashMap<Item, Integer>(); hashMap.put(item, 10); hashMap.put(item1, 5); hashMap.put(item2, 10); hashMap.put(item3, 3); System.out.println("Size of HashMap "+ hashMap.size()); assertEquals(4,hashMap.size()); for(Map.Entry entry: hashMap.entrySet()) { System.out.println(entry.getKey().toString() + "-" + entry.getValue()); } Item newItemAsKeyInHashMap = new Item("Water bottle", 20); assertTrue(hashMap.containsKey(newItemAsKeyInHashMap)); assertTrue(hashMap.containsValue(hashMap.get(newItemAsKeyInHashMap))); } }
The test case in the preceding code creates a
HashMap<Item, Integer> object and initializes it with
Item objects. The
assertEquals() method tests the number of elements in the
HashMap. The code iterates through the
HashMap to print the key value pairs of the
Hashmap. Both the
AssertTrue() methods checks for the presence of an Item key and its value.
The output on running the tests in IntelliJ is this.
Next, let’s write a test case to test the same operations on a
Hashtable.
@Test public void ItemWithHashtableTest() { Hashtable<Item, Integer> hashtable = new Hashtable<Item, Integer>(); hashtable.put(item, 10); hashtable.put(item1, 5); hashtable.put(item2, 10); hashtable.put(item3, 3); /*Will not be allowed being duplicate*/ hashtable.put(item1,16); assertEquals(4, hashtable.size()); System.out.println("Size of Hashtable "+ hashtable.size()); for(Map.Entry entry: hashtable.entrySet()) { System.out.println(entry.getKey().toString() + "-" + entry.getValue()); } Item itemAsKeyInHashtable = new Item("Water bottle", 20); assertTrue(hashtable.containsKey(itemAsKeyInHashtable)); assertTrue(hashtable.containsValue(hashtable.get(itemAsKeyInHashtable))); }
The output on running the tests in IntelliJ is this.
Testing Concurrent Modifications
A common exception encountered when working with Java collection classes is
ConcurrentModificationException. This exception is thrown while iterating through a collection if any thread other than the
Iterator tries to modify the collection.
The following test attempts to remove an element while looping through the elements of a
HashMap using a
for loop.
@Test(expected = ConcurrentModificationException.class) public void ConcurrentModificationExceptionTest() { HashMap<Item, Integer> hashMap = new HashMap<Item, Integer>(); hashMap.put(item, 10); hashMap.put(item1, 5); hashMap.put(item2, 10); for(Map.Entry<Item, Integer> entry: hashMap.entrySet()) { Integer value = entry.getValue(); if(value == 5) { hashMap.remove(entry.getKey()); } } }
The preceding test case throws an exception of type
ConcurrentModificationException. The test case passes because it is expecting an exception of type
ConcurrentModificationException
To remove an element while iterating through a
Hashmap, ensure you use the
remove() method of
Iterator.
The following test attempts to remove an element while iterating through a
HashMap using an
Iterator.
@Test public void ConcurrentModificationHashMapIterationTest() { HashMap<Item, Integer> hashMap = new HashMap<Item, Integer>(); hashMap.put(item, 10); hashMap.put(item1, 5); hashMap.put(item2, 10); assertEquals(3,hashMap.size()); for(Iterator<Map.Entry<Item, Integer>> it = hashMap.entrySet().iterator(); it.hasNext();) { Map.Entry<Item, Integer> entry = it.next(); Integer value = entry.getValue(); if(value == 5) { it.remove(); System.out.println("Item with value 5 safely removed from HashMap"); } } assertEquals(2,hashMap.size()); }
The test case passes and the output is this.
The following test expects a
ConcurrentModificationException while trying to remove an element from a
Hashtable while looping through its elements.
@Test(expected=ConcurrentModificationException.class) public void ExceptionWithHashtableTest() { Hashtable<Item, Integer> hashtable = new Hashtable<Item, Integer>(); hashtable.put(item, 10); hashtable.put(item1, 5); hashtable.put(item2, 10); for (Map.Entry<Item, Integer> entry : hashtable.entrySet()) { Integer value = entry.getValue(); if (value == 5) { hashtable.remove(entry.getKey()); } } }
Hashtable supports both
Enumeration and
Iterator. As an
Enumeration unlike
Iterator is not fail-fast, you can use it to enumerate over the elements of a
Hashtable and modify it.
The following test code removes an element while enumerating over a
Hashtable.
public void ConcurrentModificationWithHashtableEnumerationTest() { Hashtable<Item, Integer> hashtable = new Hashtable<Item, Integer>(); hashtable.put(item, 5); hashtable.put(item1, 10); hashtable.put(item2, 15); assertEquals(3,hashtable.size()); Enumeration<Item> en = hashtable.keys(); while(en.hasMoreElements()) { Item key = en.nextElement(); Integer value = hashtable.get(key); System.out.println(key + "-" + value); if(key.getItem().equals("Plate")) { hashtable.remove(key); System.out.println("Item "+key+" safely removed from Hashtable"); } } assertEquals(2,hashtable.size()); }
The output on running the test is this.
Testing for Null Values
HashMap allows only one
null key but multiple
null values.
The code to test a
HashMap for
null values is this.
@Test public void NullCheckInHashMapTest() { HashMap<Item, Integer> hashMap = new HashMap<Item, Integer>(); hashMap.put(item, 10); hashMap.put(item1, null); hashMap.put(null, 15); hashMap.put(null, null); for(Map.Entry entry: hashMap.entrySet()) { System.out.println(entry.getKey() + "-" + entry.getValue()); } assertEquals(3, hashMap.size()); assertNull(null,hashMap.get(null)); System.out.println("Null key :"+ hashMap.get(null)); }
In this code, the
assertEquals() method asserts that the
HashMap contains three elements. Note that the code tries adding four elements out of which two elements have
null keys.
The
assertNull assertion asserts that the last added element with a
null key is retained by the
Hashtable.
The output on running the test is this.
Hashtable on the other hand does not allow
null keys.
The test code is this.
@Test(expected = NullPointerException.class) public void NullCheckInHashtableTest() { Hashtable<Item, Integer> hashtable = new Hashtable<Item, Integer>(); hashtable.put(item, 10); hashtable.put(item1, 5); hashtable.put(null, null); System.out.println("Hashtable Null key "+ hashtable.get(null)); }
The preceding test passes as it expects a
NullPointerException to be thrown in Line * that attempts to add an element with a
null key.
Summary
While still supported,
Hashtable is considered obsolete and
HashMap is the most direct replacement of it.
One difference that could impact your decision on selecting one between the two is that all relevant methods of
Hashtable are synchronized while they are not in a
HashMap. However the synchronization concern of
HashMap is addressed by
ConcurrenthashMap. But
ConcurrenthashMap, unlike
HashMap does not allow
null to be used as a key or value.
In your application, you should not use
Hashtable in new development. However, you will find lots of legacy code bases with
Hashtable implementations and sooner or later, you would need working with them. | https://springframework.guru/java-hashmap-vs-hashtable/ | CC-MAIN-2019-47 | refinedweb | 1,773 | 52.76 |
import "barista.run/modules/shell"
Package shell provides modules to display the output of shell commands. It supports both long-running commands, where the output is the last line, e.g. dmesg or tail -f /var/log/some.log, and repeatedly running commands, e.g. whoami, date +%s.
Module represents a shell module that updates on a timer or on demand.
New constructs a new shell module.
Every sets the refresh interval for the module. The command will be executed repeatedly at the given interval, and the output updated. A zero interval stops automatic repeats (but Refresh will still work).
Output sets the output format. The format func will be passed the entire trimmed output from the command once it's done executing. To process output by lines, see Tail().
Refresh executes the command and updates the output.
Stream starts the module.
TailModule represents a bar.Module that displays the last line of output from a shell command in the bar.
func Tail(cmd string, args ...string) *TailModule
Tail constructs a module that displays the last line of output from a long running command.
func (m *TailModule) Output(format func(string) bar.Output) *TailModule
Output sets the output format for each line of output.
func (m *TailModule) Stream(s bar.Sink)
Stream starts the module.
Package shell imports 10 packages (graph). Updated 2018-11-25. Refresh now. Tools for package owners. | https://godoc.org/barista.run/modules/shell | CC-MAIN-2020-40 | refinedweb | 231 | 71.31 |
find......
Upgrading from RPG3 to RPG400
how to upgrade rpg 3 to rpg400
Are CAL’s Needed for Lotus Domino Access??
i have power down my v4r5 server, and checked all the connections,also i have restarted my router and every thing. but now server performance is slow, i dont konow why? please help me.......
ASP data to be sent to mail
daily basis i want to receive the iseries systems ASP percentage to be sent to my mail
can we do debugging a dsp file in rpg? if its so how is possible? plz give me the steps?
Publishing Ms Exchange 2003 FE through TMG 2010 Server
We have two Ms Exchange Servers both 2003 and configured as: FE (front end) and Back End (for meilboxes) - currently the FE is published through Ms ISA 2006 and working just fine. Plans to migrate to TMG 2010 publishing of the FE named above have hit a snag by some very strange issue of -- inbound...
Router....
Controlling spam in Exchange 2007
Dear All i have lot of spam mails in my exch server users.pls guide me how i can block these mails in exch server.
How to come up with storage statistics on iSeries 820
Sir: As per requirement again from our 3rd party vendor in assessing our prod iseries 820 for system performance fine-tuning: "System storage information – Size and percentage allotted to SIBS and other system, usage, backup in the prod server." The main concern of the 3rd...
i hv written this prog in netbeans n i m new to java so not getting error public class Main { /** Creates a new instance of Main */ public Main() { } /** * @param args the command line arguments */ public static void...
I set up ofline sync from the laptop and now found that the user on the server under users is missing although i see the user from the laptop as a share i can access the data.
Speed of a V5R4 processor
how to find the processor speed of an V5R4 system
Remote Access Client Access
I have used client access for years. I had a linksys router to a westell modem model 6100. THEN Frontier came in and swapped the westell modem for a westell model 7500 which is a modem/router combo. It has been configured for port forwarding. However, it won't let me in from home. What changed...
We are implementing Agile SDLC in our company. Has anybody identified Agile SDLC controls that are tested as part of their SOX complinance program? Would appreciate any examples of controls that you can offer
Disappearing appointments in Blackberry synced Outlook
How do I keep appointments disappearing from the calendar in outlook 2010? I am using a Blackberry to Sync with Outlook. | http://itknowledgeexchange.techtarget.com/itanswers/page/495/?src=5057680&asrc=EM_UGT_17849919&uid=14764242 | CC-MAIN-2013-48 | refinedweb | 459 | 69.21 |
A pipe connects an input stream and an output stream.
A piped I/O is based on the producer-consumer pattern, where the producer produces data and the consumer consumes the data.
In a piped I/O, we create two streams representing two ends of the pipe. A PipedOutputStream object represents one end and a PipedInputStream object represents the other end. We connect the two ends using the connect() method on the either object.
We can also connect them by passing one object to the constructor when we create another object.
The following code shows two ways of creating and connecting the two ends of a pipe:
The first method creates a piped input and output streams and connect them.
It connects the two streams using
connect method.
PipedInputStream pis = new PipedInputStream(); PipedOutputStream pos = new PipedOutputStream(); pis.connect(pos); /* Connect the two ends */
The second method creates piped input and output streams and connect them. It connects the two streams by passing the input piped stream to the output stream constructor.
PipedInputStream pis = new PipedInputStream(); PipedOutputStream pos = new PipedOutputStream(pis);
We can produce and consume data after we connect the two ends of the pipe.
We produce data by using one of the write() methods of the PipedOutputStream object. Whatever we write to the piped output stream automatically becomes available to the piped input stream object for reading.
We use the read() method of PipedInputStream to read data from the pipe. The piped input stream is blocked if data is not available when it attempts to read from the pipe.
A piped stream has a buffer with a fixed capacity to store data between the time it is written to and read from the pipe.
We can set the pipe capacity when we create it. If a pipe's buffer is full, an attempt to write on the pipe will block.
The following code creates piped input and output streams with the buffer capacity of 2048 bytes.
PipedOutputStream pos = new PipedOutputStream(); PipedInputStream pis = new PipedInputStream(pos, 2048);
A pipe is used to transfer data from one thread to another. The synchronization between two threads is taken care of by the blocking read and write.
The following code demonstrates how to use a piped I/O.
import java.io.PipedInputStream; import java.io.PipedOutputStream; //w w w. j av a 2 s.c o m public class Main { public static void main(String[] args) throws Exception { PipedInputStream pis = new PipedInputStream(); PipedOutputStream pos = new PipedOutputStream(); pos.connect(pis); Runnable producer = () -> produceData(pos); Runnable consumer = () -> consumeData(pis); new Thread(producer).start(); new Thread(consumer).start(); } public static void produceData(PipedOutputStream pos) { try { for (int i = 1; i <= 50; i++) { pos.write((byte) i); pos.flush(); System.out.println("Writing: " + i); Thread.sleep(500); } pos.close(); } catch (Exception e) { e.printStackTrace(); } } public static void consumeData(PipedInputStream pis) { try { int num = -1; while ((num = pis.read()) != -1) { System.out.println("Reading: " + num); } pis.close(); } catch (Exception e) { e.printStackTrace(); } } }
The code above generates the following result. | http://www.java2s.com/Tutorials/Java/Java_io/0300__Java_io_Pipe.htm | CC-MAIN-2017-09 | refinedweb | 501 | 58.89 |
Possible Duplicate:
Static vs global
Global variables (not
static) are there when you create the
.o file available to the linker for use in other files. Therefore, if you have two files like this, you get name collision on
a:
a.c:
#include <stdio.h> int a; int compute(void); int main() { a = 1; printf("%d %d\n", a, compute()); return 0; }
b.c:
int a; int compute(void) { a = 0; return a; }
because the linker doesn't know which of the global
as to use.
However, when you define static globals, you are telling the compiler to keep the variable only for that file and don't let the linker know about it. So if you add
static (in the definition of
a) to the two sample codes I wrote, you won't get name collisions simply because the linker doesn't even know there is an
a in either of the files:
a.c:
#include <stdio.h> static int a; int compute(void); int main() { a = 1; printf("%d %d\n", a, compute()); return 0; }
b.c:
static int a; int compute(void) { a = 0; return a; }
This means that each file works with its own
a without knowing about the other ones.
As a side note, it's ok to have one of them
static and the other not as long as they are in different files. If two declarations are in the same file (read translation unit), one
static and one
extern, see this answer. | https://codedump.io/share/UFmHtbluFe4f/1/cc-global-vs-static-global | CC-MAIN-2017-09 | refinedweb | 249 | 78.89 |
Searching is the process of finding a particular element from a long list of multiple elements. If you are a programmer and working with data stored in Linear data structures like arrays, I bet you must have come across needing a search operation. In this article let's take a look at the two of the most used searching algorithms.
- Linear Search
- Binary Search
Linear Search
Consider that you want to eat your favourite food, but that food is present in an only restaurant among multiple restaurants present in a food fest. What you will do is go one by one to restaurants and search for your favourite food.
The above method is simply called Linear Search. When there are multiple elements present in the array, the best and the easiest way of searching is going one by one and checking the elements by comparing them.
Below is a simple explanation of Linear Search Implementation in Python.
def linearSearch(array, n, target): for i in range(0, n): if (array[i] == target): return i return -1 array = [10, 20, 30, 40, 50] x = 30 n = len(array) result = linearSearch(array, n, x) if(result == -1): print("Element not found") else: print("Element found at index: ", result) # Outputs 2
Time Complexity:- In the best case, if the element you want to search is present at the first index, the time complexity is O(n). But time complexities are measured based on worst cases since it is considered the best parameter to measure the time consumed by the algorithm. So over here we can see a case where the element could be present at the end of the array. So the time complexity is the no of elements in the array which is O(n)
Space Complexity:- Since we are not using any external data structure, the space complexity remains constant at O(1).
Advantages:-
- Easy to understand.
- Works in all cases (both sorted and non sorted).
- Space efficient.
Disadvantages:-
- Not so time-efficient when compared to binary search on sorted elements.
Binary Search
Imagine when the elements you operating on is sorted in some way (either ascending or descending). So now you have a slight understanding of where your search element must be present. This approach is called Binary Search.
In this approach, there will be three-pointers (start, end and middle). At first, the start will be at zero indexes and the end will be at last. Consider an example in which the array is ascending sorted, in the first iteration of binary search we will find the middle pointer by float dividing (start + end) by 2. If the element is found we return the mid pointer, else if the current mid element is greater than the target we decrease the end element by (mid - 1) else if the current mid element is lesser than the target we increase the start element. This process continues until we find the target.
Below is a simple explanation of Binary Search Implementation in Python.
def binarySearch(arr, target, low, high): while low <= high: mid = low + (high - low) // 2 if arr[mid]==target: return mid elif arr[mid] < target: low = mid + 1 else: high = mid - 1 return -1 arr = [10, 20, 30, 40, 50, 60, 70] x = 30 result = binarySearch(arr, x, 0, len(arr)-1) if result != -1: print("Element is present at index " + str(result)) else: print("Not found") # Outputs 2
Time Complexity:- Binary Search is an example of a divide and conquer algorithm. In each iteration of the binary search, we are reducing our no if inputs. For example in the above input when comparing the start and the end ranges of the code we have 7 inputs but since it didn't fit our condition we break it into 3 elements and then one. So here is no of the elements is decreasing so our time complexity is the worst case also could be O(logn), which is more efficient than linear search when compared.
Space Complexity:- Since we are not using any external data structure, the space complexity remains constant at O(1).
Advantages:-
- Time efficient when using sorted elements.
- Space efficient.
Disadvantages:-
- Works only in sorted cases. If the element is not sorted, we have to first sort the elements and then search using Binary search which is not efficient when compared to Linear search on non-sorted elements since it remains the same for both cases.
Conclusion
Searching is one of the important operations in the linear data structure. If you find yourselves in a situation where the array is sorted and want to search use Binary Search, else stick with Linear Search.
Thank you. | https://blog.quasarcommunity.org/introduction-to-searching-algorithms-in-a-linear-data-structure | CC-MAIN-2022-40 | refinedweb | 778 | 58.21 |
DrawMultipleHUDText issue
Hello PluginCafe! :)
I'm using Draw() method if TagData plugin for displaying multiple text values but I can't figure out, how the DrawMultipleHUDText works.
Let's assume I have a list of strings
abc = [ "Hello", "World", ]
And a list of vectors (Usually I'm importing c4d.Vector as v)
xyz = [v(0,100,0), v(0,200,0)]
How should I pass them into DrawMultipleHUDText?
I tried this method and it does not work.
def Draw(self, tag, op, bd, bh): abc = ["Hello", "World"] xyz = [v(0, 100, 0), v(0, 200, 0)] values = {'_txt': abc, "_position": xyz} bd.DrawMultipleHUDText(values) return c4d.DRAWRESULT_OK
I want to display these values on top of other viewport elements.
Seems like I figured this out but it's kinda complicated.
def Draw(self, tag, op, bd, bh): values0 = [{'_txt': "Hello", "_position": v(100,100,0)},{'_txt': "World", "_position": v(200,200,0)}] bd.DrawMultipleHUDText(values0) return c4d.DRAWRESULT_OK
The method above causes shading problems which can be solved by enabling depth option.
bd.SetDepth(True)
But it's still displayed on the background. Is it possible to bring it to the front?
- m_magalhaes last edited by
hello,
I can resume your question to "Drawing something in front of everything"
It's possible in a SCENEHOOK (witch is not supported in python).
did you try to change the BaseDraw matrix ?
I can point you to this thread the "solution" is to set the matrix of the BaseDraw so the drawing is done really near the camera. Be aware you can have issue with the clipping functions.
hope this help.
Cheers
Manuel
- m_magalhaes last edited by m_magalhaes
hello,
setting the matrix to screen seems to work.
""" Draw multiple text From Tag """ import c4d from c4d import plugins, utils, bitmaps, gui # Be sure to use a unique ID obtained from PLUGIN_ID = 1052927 class TDRAW_EXAMPLE(c4d.plugins.TagData): def Draw(self, tag, op, bd, bh): # Returns if object is not a polygon object if not op.IsInstanceOf(c4d.Opolygon): return c4d.DRAWRESULT_OK # Retrieves the Object Matrix opMg = op.GetMg() # Retrieves All Points points = op.GetAllPoints() # Retrieves Global Coordinates points = [opMg * p for p in points] # From world to screen Coordinates (in another array) screenPoints = [ bd.WS(p) for p in points ] # Prepares the dictionary for the draw multipleHUDText Draw Point Coordinates (world space) at screenPoint Position. value = [ { "_txt" : "point " + str(i) + " " + str(pos[0]) , "_position" : pos[1] } for i, pos in enumerate(zip(points, screenPoints)) ] # Sets the matrix to screen space bd.SetMatrix_Screen() # Enables depth buffer. bd.SetDepth(True) # Draws points indices at point coordinates bd.DrawMultipleHUDText(value) return c4d.DRAWRESULT_OK def Execute(self, tag, doc, op, bt, priority, flags): return c4d.EXECUTIONRESULT_OK if __name__ == "__main__": # Register the tag c4d.plugins.RegisterTagPlugin(id=PLUGIN_ID, str="Tag that draw on viewport", info=c4d.TAG_EXPRESSION | c4d.TAG_VISIBLE, g=TDRAW_EXAMPLE, description="tdrawexample", icon=None)
tdrawexample.h
#ifndef __TDRAWEXAMPLE_H__ #define __TDRAWEXAMPLE_H__ enum { }; #endif // __pc11519_H__
tdrawexample.res
CONTAINER tdrawexample { NAME tdrawexample; INCLUDE Obase; GROUP ID_OBJECTPROPERTIES { } }
tdrawexample.str
STRINGTABLE tdrawexample { tdrawexample "Draw on viewport from tag"; }
c4d_symbol.h
enum { // End of symbol definition _DUMMY_ELEMENT_ };
Cheers
Manuel
OMG! You just wrote the entire plugin for my silly question.
Thank You!!!
I have only one question.
Why did you use
Draw(self, op, drawpass, bd, bh)
instead of
Draw(self, tag, op, bd, bh)
will not
drawpassbe treated as op and
opas a
tag?
- m_magalhaes last edited by m_magalhaes
well,
@merkvilson cause i started from an old ObjectData project and i didn't changed the signature xD
And exact, the name changed but not the object of course.
so, now you don't even need to retrieve the object from the tag :) I've updated the code.
(always refresh your mind before starting another project ^^)
cheers
Manuel
OK. Now I get it.
Thank you very much! I really appreciate what you've done.
Have a good day!
-Merk | https://plugincafe.maxon.net/topic/11589/drawmultiplehudtext-issue | CC-MAIN-2020-50 | refinedweb | 646 | 59.7 |
#include "ltwia.h"
L_LTWIA_API L_INT EXT_FUNCTION L_WiaSetProperties(hSession, pItem, pProperties, pfnCallBack, pUserData)
Sets a list of all properties available through the LWIAPROPERTIES structure into the WIA device's item passed through the pItem parameter.
This feature is available in version 16 or higher.
The function can set the values of the properties to the values specified in the LWIAPROPERTIES structure into the WIA device's item passed through the pItem parameter.
So if the user wants to keep his changed properties then he should not set this flag to suppress the manufacturer's image acquisition dialog and acquire directly from the specified source item.
Required DLLs and Libraries
Platforms
LEADTOOLS WIA supports both 32-bit and 64-bit image acquisition for both WIA 1.0 (XP and earlier) and WIA 2.0 (VISTA and later).
For an example, refer to L_WiaGetRootItem. | https://www.leadtools.com/help/leadtools/v19m/wia/api/l-wiasetproperties.html | CC-MAIN-2017-43 | refinedweb | 141 | 54.73 |
0
I created a text file using following method:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace FajlliTekstual { class Program { static void Main(string[] args) { FileStream fileStream = new FileStream("shenime.txt", FileMode.Create, FileAccess.Write); TextWriter writer = new StreamWriter(fileStream); Console.WriteLine("Someone Else"); writer.WriteLine("Bla Bla"); writer.WriteLine("Bla Bla"); writer.WriteLine("Unkown Person"); writer.Close(); fileStream.Close(); Console.ReadLine(); } } }
**/Now the text file holds the first and last name of someone.
My goal is to read this text file and to show the results in a console application sorted name like those that begin with A or B or other letter.
This first name latter should be given by the user and then the list must be shown.
Thank you in advance for your reply.
Cheers./
** | https://www.daniweb.com/programming/software-development/threads/439255/help-needed-to-sort-lines-in-a-text-file | CC-MAIN-2017-39 | refinedweb | 137 | 63.15 |
Hi there everyone, I have a quick question: is it possible to embed a web browser and override it's drag&drop functionality? I mean, we have a intranet application, written in PHP, Python, JavaScript and what not and it basically provides a means for tracking our files on the servers. What it does is it serves UNC paths to the users and apps via its web UI. So I thought, can I embed the entire page and have it serve these UNC strings to my app via IronPython or general .NET? Thank you in advance, best,: > I am a little bit confused about Silverlight, .NET and IronPython > versions. > > Here is a list what I think is valid, please correct me if I am wrong: > > * IronPython 2.6.1 supports Silverlight 3 + .NET 2 SP1 > * IronPython 2.6.1 does not support Silverlight 4 + .NET 2 SP1 or > Silverlight 4 + .NET 4 > * IronPython 2.7 will support Silverlight 4 + .NET 4 > > > What will IronPython 2.6.2 support? > > -- > -- Lukas > > > On 27.7.2010 17:31, Dave Fugate wrote: >> >> I’d actually suggest doing this with 2.7 Alpha 1 sources... >> >> >> >> *Building* 2./6.1/ requires a Silverlight /3./x installation as there >> were changes to System.Core (e.g., System.Func) between Silverlight >> 3.x and Silverlight 4.x. As you’ve discovered, we implemented some of >> this missing System.Core functionality ourselves in 2.6.1 which is >> confusing the compiler when there’s references to both (4.x) >> System.Core and MS.Scripting.Utils. If you can’t get your hands on a >> Silverlight 3.x installation to fix this, the next easiest route IMO >> would be to use 2.7A1 instead. >> >> >> >> *From:* users-bounces at lists.ironpython.com >> [mailto:users-bounces at lists.ironpython.com] *On Behalf Of *Lukas Cenovsky >> *Sent:* Tuesday, July 27, 2010 8:09 AM >> *To:* Discussion of IronPython >> *Subject:* Re: [IronPython] Building IronPython from sources >> >> >> >> Thanks. Copying my current Silverlight version 4.0.50524.0 to >> 3.0.50106.0 helped and Microsoft.Scripting.dll compiles fine. Now I >> get many following errors for Microsoft.Dynamic.dll: >> >> Error 1 'Func' is an ambiguous reference between >> 'System.Func<T0,T1,T2,T3,T4,TRet>' and >> 'Microsoft.Scripting.Utils.Func<T0,T1,T2,T3,T4,TRet>' >> C:\IronPython-2.6.1\Src\Runtime\Microsoft.Dynamic\Interpreter\Instructions\CallInstruction.Generated.cs >> 278 70 Microsoft.Dynamic >> >> How can I tell Visual Studio to use reference from >> Microsoft.Scripting.Utils? Thanks. >> >> -- >> -- Lukas >> >> >> On 26.7.2010 18:21, Dave Fugate wrote: >> >> Hi Lukas, the error message below is because you don’t have the >> version of Silverlight installed which was used to build IronPython >> 2.6.1. For this particular release, I believe it was something like >> “%ProgramFiles%\Microsoft Silverlight\3.0.40624.0”. You can find out >> for sure by examining the “<Silverlight3Path>” element in >> Src\IronPython\IronPython.csproj. Any ways, there are two workarounds: >> >> Replace all instances of “3.0.40624.0” throughout all C# project files >> with the version of Silverlight you have installed locally >> >> Copy and rename the version of Silverlight you have installed to >> whatever is expected by the C# project files >> >> >> >> Hope that helps, >> >> >> >> Dave >> >> >> >> *From:* users-bounces at lists.ironpython.com >> <mailto:users-bounces at lists.ironpython.com> >> [mailto:users-bounces at lists.ironpython.com] *On Behalf Of *Lukas Cenovsky >> *Sent:* Friday, July 23, 2010 12:37 PM >> *To:* Discussion of IronPython >> *Subject:* [IronPython] Building IronPython from sources >> >> >> >> Hi all, >> I have one wish for the next release of IronPython 2.6.2 (hope it is >> not too late...) - please make sure it is possible to build IronPython >> binaries from sources. I have downloaded >> IronPython-2.6.1-Src-Net20SP1.zip >> <> >> and I there is no way for me to build Silverlight binaries from it... >> >> I have opened the solution in VS 2010, solution file was converted to >> the new version, I selected 'Silverlight Debug' as a solution >> configuration and I received meny errors as below when building >> Microsoft.Scripting.dll: >> >> Error 11 The type 'System.SerializableAttribute' exists in both >> 'c:\IronPython-2.6.1\Bin\Silverlight >> Debug\Microsoft.Scripting.Core.dll' and >> 'c:\Windows\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll' >> C:\IronPython-2.6.1\Src\Runtime\Microsoft.Scripting\ArgumentTypeException.cs >> 20 6 Microsoft.Scripting >> Error 12 The type or namespace name 'Serializable' could not be >> found (are you missing a using directive or an assembly reference?) >> C:\IronPython-2.6.1\Src\Runtime\Microsoft.Scripting\ArgumentTypeException.cs >> 20 6 Microsoft.Scripting >> >> My goal was to build debug-able Microsoft.Scripting.Silverlight.dll >> because I'm receiving AddReference error which I'd like to inspect. >> >> -- >> -- Lukas >> >> >> _______________________________________________ >> Users mailing list >> Users at lists.ironpython.com <mailto:Users at lists.ironpython.com> >> >> >> >> >> >> _______________________________________________ >> Users mailing list >> Users at lists.ironpython.com >> > > > ------------------------------------------------------------------------ > > _______________________________________________ > Users mailing list > Users at lists.ironpython.com > | http://mail.python.org/pipermail/ironpython-users/2010-July/013405.html | CC-MAIN-2013-20 | refinedweb | 811 | 61.63 |
In case it was missed, Pydev is now on Git :)
I'm finding it the hard way that unfortunately its eclipse integration is still not ready for prime time -- it's missing some basic things such as a synchronize view, and I've had some bugs for it to mark the changed files in the package explorer (so, I'm waiting until it matures a bit to give it another try).
In the meanwhile, I'm using the command line (with the msysgit bash).
The thing I missed most was the synchronize view. A part of my modus operandi is making a review of all the changes before doing a commit -- and editing some things there, so, based on this link, I've created a script -- which I called gitdd -- that will create a directory structure with the HEAD and links to the changed files so that one can change those files in a diff viewer (in this case, WinMerge).
The script is below if anyone wants to use it (note that it must be run in the msysgit bash -- although it should probably work on Linux too, with another diff viewer)
#!/bin/sh -e
# usage: gitdd <path>
# Compares the current differences in winmerge with links to original files.
# Note that it must be executed at the root of the git repository.
SUBDIRECTORY_OK=1
O=".git-winmerge-tmp-$$"
V=HEAD
list="$O/list"
list_exist="$O/list_exist"
trap "rm -rf $O" 0
mkdir $O
mkdir $O/b
git diff $V --name-only -z $1 > $list
/d/bin/Python261/python.exe /c/Program\ Files/Git/bin/gitddpy.py $list $O/b/
cat $list | xargs -0 git archive --prefix=a/ $V | /d/bin/bin-1.0/tar.exe xf - -C $O
/d/bin/WinMerge/WinMergeU.exe //r //u //wr //dl WorkingCopy $O/b $O/a
[Update]
I wanted to create links to the files (so that I could edit them on WinMerge and have the original changed), so, I ended up creating a gitddpy.py to create the link (not sure why git prompt was crashing when using the shell for that -- so, this was the solution that worked for me).
The gitddpy.py contents are:
import sys
print sys.argv
f = file(sys.argv[1])
contents = f.read()
import subprocess
import os.path
for line in contents.split('\0'):
if os.path.exists(line):
subprocess.call(['cp', line, '--parents', '-l',
'--target-directory='+sys.argv[2]], shell=True)
f.close()
[Update]
Configuring Git with the following:
git config format.pretty "%h %ct %ad %Cgreen%aN%Creset %s"
git config log.date short
The commands I use most (using the msysgit Bash) are:
git status
git commit -a -m "Message"
git push origin master
git checkout <path>
git log -n 6 --format="%ct %Cgreen%aN%Creset %s"
git commit --amend (change last commit message)
And some of the commands I had to discover how to use in the msysgit bash are:
Alt+Space+E+K: mark contents for copy
Insert: paste contents
Alt+Back: erase until whitespace
The last thing worth mentioning is that the Pydev releases don't have such a nice unique id as the one that was available with subversion anymore, and it now contains the commit time (%ct in the log format). It's a bit annoying that it's such a big number, but I believe that the other choices were worse (the hash would seem totally random for someone seeing it, and basing it on the number of commits wouldn't work with history rewriting).
To sum things up: yes, I know that not being able to do everything in Eclipse sucks a bit, but hopefully the Git tools for Eclipse will catch up soon -- I'm hoping that having the history offline and not having to worry about renames, as well as the whole idea of decentralized versioning systems pays for this nuisance for now (and I'm certain that when the Eclipse plugin for Git catches up it'll be much better).
4 comments:
Great news!
I agree that egit is not quite ready, but i've found it pretty usefull to view current tree state, just for information.
Another one: it is much more simplier to use git on Linux, just give it a try.
I use git from commandline and Meld for merging in case of conflicts.
Keep up the good work!
How is using git commandline on linux simpler than using git commandline on windows? The commands are exactly the same, so your claim makes no sense at all.
I have to agree that on windows some things just don't work as expected...
The fact is that when someone wants to do some things that are a bit more complex, not having the linux shell makes a difference.
And I've had a few cases where it just crashed on me when using the shell from msysgit -- which I worked around invoking a python shell and doing things from there (although I think most things are working properly for the basic operations)
Many thanks for your scripts! Here is a version of the shell script that doesn't require python.
#####################
#!
ln $(pwd)/$i $(pwd)/$O/WORKINGCOPY/ | http://pydev.blogspot.com/2009/09/git-and-folder-compare-with-git-with.html?showComment=1257208171673 | CC-MAIN-2016-18 | refinedweb | 864 | 67.69 |
Package: libqt0-ruby1.8 Version: 4:3.3.2-1 Severity: important A mistake in the use of include means that Qt methods were being added to "Module" badly poluting its namespace. This bug also breaks the rubyscript2exe program. The good news is that this problem has been fixed upstream but since it is a pretty serious problem I am hoping that the fix gets into sarge. Here is a discussion regarding the bug from: Erik Veenstra wrote: >>. > This "hack" caused a problem in RubyScript2Exe when trying to > "compile" a Ruby application which uses Qt. I've tested the > combination RubyScript2Exe and Qt with a little HelloWorld > program. It works! Richard Dale replied: Yes, my mistake was to think of 'include Qt' being just like a 'using namespace' statement in a static language like C++. But it isn't like that at all, and in this case was having quite major unexpected effects. I'd known there was something 'not quite right' in the namespace handling of QtRuby for a while, but couldn't work out what it was. That was I was so pleased when you found the problem. -- System Information: Debian Release: 3.1 APT prefers testing APT policy: (500, 'testing') Architecture: i386 (i686) Kernel: Linux 2.4.27-1-686 Locale: LANG=C, LC_CTYPE=C (charmap=ANSI_X3.4-1968) Versions of packages libqt0-ruby1.8 depends on: ii libaudio2 1.7-2 The Network Audio System (NAS). (s ii libc6 2.3.2.ds1-20 GNU C Library: Shared libraries an ii libfontconfig1 2.3.1-2 generic font configuration librarypng12-0 1.2.8rel-1 PNG library - runtime ii libqt3c102-mt 3:3.3.3-8 Qt GUI Library (Threaded runtime v ii libruby1.8 1.8.2-3 Libraries necessary to run Ruby 1. ii libsm6 4.3.0.dfsg.1-10 X Window System Session Management ii libsmokeqt1 4:3.3.2-1 SMOKE Binding Library to Qt ii libstdc++5 1:3.3.5-8 The GNU Standard C++ Library v3 ii libx11-6 4.3.0.dfsg.1-10 X Window System protocol client li ii libxcursor1 1.1.3-1 X cursor management library ii libxext6 4.3.0.dfsg.1-10 X Window System miscellaneous exte ii libxft2 2.1.2-6 FreeType-based font drawing librar ii libxrandr2 4.3.0.dfsg.1-10 X Window System Resize, Rotate and ii libxrender1 0.8.3-7 X Rendering Extension client libra ii libxt6 4.3.0.dfsg.1-10 X Toolkit Intrinsics ii ruby1.8 1.8.2-3 Interpreter of object-oriented scr ii xlibmesa-gl [libgl1] 4.3.0.dfsg.1-10 Mesa 3D graphics library [XFree86] ii xlibmesa-glu [libglu1] 4.3.0.dfsg.1-10 Mesa OpenGL utility library [XFree ii xlibs 4.3.0.dfsg.1-10 X Keyboard Extension (XKB) configu ii zlib1g 1:1.2.2-3 compression library - runtime -- no debconf information | https://lists.debian.org/debian-qt-kde/2005/04/msg00091.html | CC-MAIN-2016-07 | refinedweb | 491 | 61.73 |
Always the same problem of file upload flash !!!!
There is a solution to all this !!!
I have made various posts, tried usb2.0 / 3.0 ...
When I upload the serial firmware, this always happens to me.
Reading file status Failed to read project status, uploading all files Creating dir lib Creating dir www Creating dir www/bootstrap Creating dir www/bootstrap/css Creating dir www/bootstrap/fonts Creating dir www/bootstrap/js Creating dir www/js [1/19] Writing file SI7006A20.py [2/19] Writing file boot.py [3/19] Writing file hal.py [4/19] Writing file lib/mqttserver.pub.pem [5/19] Writing file main.py [6/19] Writing file mqtt.py [7/19] Writing file simple.py [8/19] Writing file umqtt.py [9/19] Writing file www/bootstrap/css/bootstrap.min.css Failed to write file, trying again... Failed to write file, trying again... Filecheck failed [10/19] Writing file www/bootstrap/js/bootstrap.min.js Failed to write file, trying again... Failed to write file, trying again... Failed to write file: inco [11/19] Writing file www/index.html Failed to write file, trying again... Failed to write file, trying again... Failed to write file: incorrec [12/19] Writing file www/js/angular.min.js Failed to write file, trying again... Failed to write file, trying again... Failed to write file: incor [13/19] Writing file www/js/app.js Failed to write file, trying again... Failed to write file, trying again... Failed to write file: no module named 'xConfigureFile [14/19] Writing file www/js/jquery-1.11.1.js Failed to write file, trying again... Failed to write file, trying again... Upload failed.: Failed to write file: no module named 'xConfigureFile Please reboot your device manually. Traceback (most recent call last): File "main.py", line 4, in <module> ImportError: no module named 'xConfigureFile' Pycom MicroPython 1.18.1.r1 [v1.8.6-849-b0520f1] on 2018-08-29; LoPy with ESP32 Type "help()" for more information.
I thought it was a power problem, but nothing ..
L01/8mb flash, various firmware version
Help me!!!!
regards
James
Hi, I tried via ftp and it works perfectly.
Regards
@dan Hi, the files are not big, besides the errors the upload gives them in some pycom libraries. I have tried ubuntu 18 and 16, Atom and pymakr 1.4.2 and the last 1.4.4.
Anyway the program works correctly even with errors in the upload, but it is annoying.
I will try via ftp.
Regards,
@nespressif for me, I had the same issue with the bootstrap css as the original post, but when I decreased its size, I was able to upload it. If you upload larger files, FTP seems to work better.
@dan Hi, I'm uploading my project: boot.py, main.py and the lib directory with my own libraries and the pysense libraries. I always get an error when uploading the pycoproc.py library, but after the program works.
I have uninstalled and reinstalled Pymakr in Atom and now I show the size of each file during uploading.
I'll try via FTP and also from another computer with ubuntu 16.04 and I'll tell you.
@nespressif Hi, what files are you trying to upload? Also, could you try using FTP?
Hello, everybody,
I have the same problem, with pysense + sipy, updated to the last stable firmware, I have uninstalled and reinstalled pymakr in Atom and I always fail the flash of the same file of the project (pycoproc).
In my case it seems that these problems have come after upgrading to Ubuntu 18.04 lts.
I will try to flash with another computer that I have with ubuntu 16.04 and the latest version of pymakr.
Would I also like to know why this happens?
Regards
@robert-hh fine...
@cmisztur Put aside pymakr and give a clean ftp client a try, to sort out the problem. If possible, use linux or mac command line ftp. Check beforehand, that teher is sufficient free space in the file system of your device. You can do so with
import uos;uos.getfree("/flash")
So what is the solution?
Seems like changes to my files are actually uploaded, but still end up with the error message.
Uploading project (main folder)... Safe booting device... (see settings for more info) Reading file status [1/1] Writing file lib/sx1509.py Failed to write file, trying again... Failed to write file, trying again... Filecheck failed Upload done, resetting board...
It is not always possible to transmit files via FTP, so if there were real transfer problems in the serial mode it would be a serious problem, and more serious than any other answer after the umpteenth post, at least in understanding what could be.
regards
James
@james said in Always the same problem of file upload flash !!!!:
Another thought is that they are css and js files and that some character in the file in serial transfer can give some problems, even if it should be a binary trafficking.
That's what i would suspect. Serial transfer might not be transparent. That's one of the reasons why I use ftp. It is reliable and well tested over decades.
@robert-hh ,
Let's talk about the "L01", I do not know why this thing but until some time ago even those of the pycom updater saw the whole flash.
However, the problem of uploading files is driving me crazy, someone hypothesized some problems with the FTDI chip, but I think only with regard to the flash of micropython, also because the other files are uploaded safely.
Another thought is that they are css and js files and that some character in the file in serial transfer can give some problems, even if it should be a binary trafficking.
regards
James
@james OK. I just tested a image loaded with the Pycom updater, and that indeed uses the full flash. Only the images generated from the github repository seem to be generated with a smaller file system. I'm curious why.
@robert-hh , @dan
in ftp is ok.
file is correctly
regards
with the version
Type "help()" for more information. >>> import os >>> os.uname() (sysname='LoPy', nodename='LoPy', release='1.17.3.b1', version='v1.8.6-849-83e2f7f on 2018-03-19', machine='LoPy with ESP32', lorawan='1.0.2') >>> os.listdir() ['main.py', 'sys', 'lib', 'cert', 'boot.py', 'www', 'SI7006A20.py', 'project.pymakr', 'hal.py', 'mqtt.py', 'simple.py', 'umqtt.py', 'xApp.py', 'xConfigureFile.py', 'xHTTPConfigure.py', 'xWebServer.py', 'xWebSocket.py'] >>> os.chdir('www') >>> os.listdir() ['bootstrap', 'js', 'index.html'] >>> os.chdir('bootstrap') >>> os.listdir() ['css', 'fonts', 'js'] >>> os.chdir('css') >>> os.listdir() ['bootstrap.min.css'] >>>
the file is actually there but it's failing, it always reloads with an error,
could it be a problem related to the ram ????
with the last error error error
@robert-hh
It seems strange,
when I started with this project I took the OEM L01 and I was assured that the flash was handled throughout
>>> os.getfree('/flash') 3680
also because there was a moment in which I managed to do it.
the total firmware including the small web and 804kb
@dan I have not tried in ftp, I could try even if I need to transfer files via serial; I use the wifi both as an ap client and as ap for the configuration.
I need to understand the problem, I made a post even a while ago but nothing.
excuse for my easy english
regards
James
@james It could problem of the accumulated file sizes. The flash file system has a size of 508k. The total flash size used is 3680k for all devices. The extra flash space on 8 MByte devices is not used, which is sad.
www/bootstrap/js/bootstrap.min.js 119K file size | https://forum.pycom.io/topic/3740/always-the-same-problem-of-file-upload-flash | CC-MAIN-2019-30 | refinedweb | 1,310 | 77.03 |
0
A very small problem I am having. Here is an example:
A class representing a book
public class Book { private String title, author; //Constructor for book public Book (String name, String writer) { title = name; author = writer; }
Another class called Bookshelf representing a collection of books
public class Bookshelf { private Book[] shelf; int number; //Constructor for Bookshelf public Bookshelf () { shelf = new Book[10]; number = 0; }
Main method:
public class Bookstore { public static void main (String[] args) { Bookshelf cases = new Bookshelf (); //<-how to retrieve the array inside bookshelf System.out.println ("This is: " + Bookstore.somemethod (REALPARAM); //<-- } //Static method public static void somemethod (PARAMETER) //<--Array in bookshelf class as PARAMETER { //some code } }
So as you can see above, I have a static method called somemethod that is designed to accept the array present inside the Bookshelf class (Bookshelf constructor) as its parameter. How should I do this?? What should I put in the field PARAMETER as well as REALPARAM so that I can accomplish this??
Any form of help is greatly appreciated. I have researched online the whole day yesterday and also today. Thanks a lot.
Edited by Limiter: n/a | https://www.daniweb.com/programming/software-development/threads/357299/an-array-inside-a-constructor | CC-MAIN-2017-09 | refinedweb | 189 | 61.26 |
BeagleBone/I2CLCDDemo
Contents
I2C LCD Demo with Onewire Temperature Sensor
Introduction
I created this tutorial to show how to use inexpensive components (commonly used arduino components) with the BeagleBone Black. The cost of this project can easily be under $20 USD shipping and all.
If you have come from tinkering with Arduino boards you need to understand that the BBB is much more sensitive than what you are used to. It can't handle the voltages or amounts of current. For this demo we'll be using a logic converter to allow the BBB to communicate with a 5V device over I2C.
For the software side I'm using python.
Hardware
- 8 Channel Logic Converter $4.95 each and free shipping.
- IIC I2C LCD Module $3.20 each and cheap shipping.
- Sturdy 4 Line LCD $6.90 each and cheap shipping.
- (Optional) Waterproof Temperature Sensor $2 and free shipping. Also uses a 4.7k resistor (there is some wiggle room here).
Logic Converter Wiring
For the logic converter you need to
- Run a wire from a 3.3v pin to the VCC on the low side of the logic converter.
- Run a wire from a 5v pin to the VCC on the high side of the logic converter.
- Run a wire from a ground pin to the ground of one side and a jump a wire from the ground of one side to the ground on the other side.
I2C LCD wiring
For the LCD module you need to
- Wire the I2C module into 5V and Ground with the high side of the logic converter
- Plug SCL and SDA from the I2C module into the first two pins on the logic converter on the high side (for example H0 and H1)
- On the other side of the logic converter run wires to the BBB to pins 19(SCL) and 20(SDA)
Temp sensor wiring
For the temperature sensor you need to
- Run a jumper wire from the 3.3v from the VCC low side of the logic converter to the sensor's VCC wire
- Run a jumper wire from ground to the sensor ground wire
- Put a 4.7k resistor from the 3.3V VCC to the data wire
- From the data wire, run a wire to the BBB at P9_22
Software
For the 1-Wire temperature sensor, you can follow this tutorial to get the device recognized by the system. For the purposes of this tutorial the address I will be using is "/sys/bus/w1/devices/28-000004d43557/w1_slave" yours will be different. To get your 1-wire device address you should be able to
ls /sys/bus/w1/devices/.
You can setup python for working with I2C by following the guide from Adafruit. The main priority is having smbus working. You need to have i2c tools installed to figure out what address the I2C LCD module is at. Mine is on bus 1, at address 0x20.
The particular I2C module I listed in the hardware section had a peculiar wiring that didn't easily work with any I2C LCD libraries. For one the backlight pin toggles the opposite of the PyLCD library. I was able to find the pinout by digging through tons of sites, and finally found a comment on dx.com for a different module which mostly worked, and then found an unpopular Arduino sketch that worked with it, and got it all sorted out from there.
Below is the actual code to make this app run. You'll have to at the very least modify the w1 device address. The first "os path exists" checks to see if the device is loaded, and if not, loads it up and give enough time before continuing. To run the application run "python weather.py".
weather.py
import pylcd import smbus from time import * import os.path #if 1-wire sensor isn't ready if os.path.exists("/sys/bus/w1/devices/28-000004d43557/w1_slave") is False: slots = open("/sys/devices/bone_capemgr.9/slots", "w") slots.write("BB-W1:00A0") slots.close() print "Added 1-Wire Device" sleep(2) #This is basically the same as "echo BB-W1:00A0 > /sys/devices/bone_capemgr.9/slots" class temp: def __init__(self): a = 1 #celcius def temp_c(self): w1="/sys/bus/w1/devices/28-000004d43557/w1_slave" raw = open(w1, "r").read() return str(float(raw.split("t=")[-1])/1000) #farenheit def temp_f(self): ctemp = self.temp_c() ftemp = 9.0/5.0 * float(ctemp) + 32.0 return ftemp while True: tempnow = temp() ctemp = tempnow.temp_c() ftemp = tempnow.temp_f() lcd = pylcd.lcd(0x20, 1) lcd.lcd_puts("BeagleWeather", 1) lcd.lcd_puts("Celsius: "+str(ctemp), 2) lcd.lcd_puts("Farenheit: "+str(ftemp), 3) lcd.lcd_puts(strftime("%m-%d-%Y %H:%M",localtime()), 4) #update every 10 seconds sleep(10)
Here is the library. Besides the modified pins from the original source at github, I added
if now < today7am or now > today11pm: to turn the backlight off during sleeping hours. It was the easiest place to hack it in, as I didn't want to spend a lot of time on that.
pylcd.py
''' Copyright (C) 2012 Matthew Skol smbus from time import * import datetime # (Use for "LCD2004" board) 2: top 4 bits of expander are commands bits AND P0-6 P1-5 P2-4 3: "LCD2004" board where lower 4 are commands, but backlight is pin 3 ''' def __init__(self, addr, port, reverse=0, backlight_pin=7, en_pin=4, rw_pin=5, rs_pin=6, d4_pin=0, d5_pin=1, d6_pin=2, d7_pin=3): self.reverse = reverse self.lcd_device = i2c_device(addr, port) self.pins=[i for i in range(8)] # Initialize the list #self.backlight=1<<7 # Initialize with backlight as on (Change self.backlight to 0 to turn off backlight pin) now = datetime.datetime.now() today7am = now.replace(hour=7, minute=0, second=0, microsecond=0) today11pm = now.replace(hour=23, minute=0, second=0, microsecond=0) if now < today7am or now > today11pm: self.backlight=1<<7 else: backlight_pin=7 self.backlight=0 if d7_pin != -1: # Manually set pins, in case we have a different backpack pinout self.pins[0]=d4_pin self.pins[1]=d5_pin self.pins[2]=d6_pin self.pins[3]=d7_pin self.pins[4]=rs_pin self.pins[5]=rw_pin self.pins[6]=en_pin self.pins[7]=backlight_pin elif self.reverse==1: # 1: top 4 bits of expander are commands bits AND P0-4 P1-5 P2-6 (Use for "LCD2004" board) elif self.reverse==2: # 2: top 4 bits of expander are commands bits AND P0-6 P1-5 P2-4 else: # self.pins is already initialized to this, but broken out here for clarity self.pins[0]=0 # D4 Pin self.pins[1]=1 # D5 Pin self.pins[2]=2 # D6 Pin self.pins[3]=3 # D7 Pin self.pins[4]=4 # RS Pin self.pins[5]=5 # RW Pin self.pins[6]=6 # EN Pin self.pins[7]=7 # Backlight Pin # This begins the actual initialization sequence self.lcd_device_write(0x03) # Prepare to switch to 4 bit mode self.lcd_strobe() sleep(0.0005) self.lcd_strobe() sleep(0.0005) self.lcd_strobe() sleep(0.0005) self.lcd_device_write(0x02) # Set 4 bit mode self.lcd_strobe() sleep(0.0005) # Initialize self.lcd_write(0x28) # Set 4 bit, 2 line mode (Multi-line) self.lcd_write(0x08) # Hide cursor, don't blink self.lcd_write(0x01) # Clear display, move cursor home self.lcd_write(0x06) # Move cursor right self.lcd_write(0x0C) # Turn on display # self.lcd_write(0x0F) # clocks EN to latch command def lcd_strobe(self): self.lcd_device_write(self.lastcomm | (1<<6), 1) # 1<<6 is the enable pin self.lcd_device_write(self.lastcomm,1) # Technically not needed, but included so we can read from the display # write a command to lcd def lcd_write(self, cmd): self.lcd_device_write((cmd >> 4)) # Write the first 4 bits (nibble) of the command self.lcd_strobe() self.lcd_device_write((cmd & 0x0F)) # Write the second nibble of the command self.lcd_strobe() self.lcd_device_write(0x0) # Technically not needed # write a character to lcd (or character rom) def lcd_write_char(self, charvalue): self.lcd_device_write(((1<<4) | (charvalue >> 4))) # Originally this was 0x40 self.lcd_strobe() self.lcd_device_write(((1<<4) | (charvalue & 0x0F))) # Originally this was 0x40 self.lcd_strobe() self.lcd_device_write(0x0) # put char function def lcd_putc(self, char): self.lcd_write_char(ord(char)) # Do clunky bitshifting to account for strangely wired boards # I guarantee there is an easier way of doing this. def lcd_device_write(self, commvalue, isstrobe=0): tempcomm=commvalue | self.backlight outcomm=[0 for i in range(8)] for a in range(0,8): outcomm[self.pins[a]]=(tempcomm & 1) tempcomm=tempcomm>>1 tempcomm=0 a=7 while (a >= 0): tempcomm=(tempcomm<<1)|outcomm[a] a=a-1; self.lcd_device.write(tempcomm) sleep(0.0005) # May be unnecessary, but including to guarantee we don't push data out too fast # Since we can't trust what we read from the display, we store the last # executed command in a property inside the object. This way strobe # can add the enable bit & resend it if isstrobe==0: # self.lastcomm=commvalue #) sleep(0.005) # This command takes awhile. self.lcd_write(0x2) sleep(0.005) # This command takes awhile. # add custom characters (0 - 7) def lcd_load_custon_chars(self, fontdata): self.lcd_device.bus.write(0x40); for char in fontdata: for line in char: self.lcd_write_char(line)
Notes
It looks like LCDd can be modified to work with this module by taking a glimpse of the source at. | http://elinux.org/BeagleBone/I2CLCDDemo | CC-MAIN-2016-07 | refinedweb | 1,554 | 68.47 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.