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 |
|---|---|---|---|---|---|
Continuous Deployment Automation on Alibaba Cloud: CI/CD Automation on Container Service .
4. Setup Container Service
Before creating a container cluster, there are some services that need to be activated for the first-time users. If the Cloud resources are not activated, it need to be activated before you can proceed to create the Kubernetes cluster.
4.1 Create a Kubernetes Cluster
Navigate to the Container Service console, select Kubernetes, and click the Create Kubernetes Cluster button.
There are four different editions of Kubernetes cluster that you can create on Alibaba Cloud.
- Kubernetes — This edition is the standard Kubernetes cluster that provides full control on the underlying infrastructure. You can manage the master and worker nodes directly.
- Managed Kubernetes — This is the managed Kubernetes where the master nodes are managed by Alibaba Cloud, you do not need to worry about the health, scalability of the master nodes. All you need to focus is control the worker nodes.
- Multi-AZ Kubernetes — This is the cluster that span across different availability zones. Choose this option for better fault tolerant on physical data center availability
- Serverless Kubernetes (beta) — At this point of writing, this edition is currently on beta. This edition provides the highest level of abstraction of underlying infrastructure resources. Developers only need to focus on application deployment and leave the management of the infrastructure to the Cloud Service Provider..
5. Setup Container Registry
5.1 Create GitHub Account (Optional)
If you do not have a GitHub account, go to and sign up for a new account. Fill in the username, email and password. Then, after verification, choose the Free account.
After registration is completed, it shall bring you the main landing page.. Authrization page, click on “Authroize Aliyun Developer”
Once it is authorized, you should receive a notification email. Go back to the Container Registry page. Click on the Account Bound button.
By now, it should show “Bound” on the GitHub code source section.
5.4 Namespace
Go back to the Namespace page. On the defaut
The following figure shows the list of namespaces. In this lab, we would be using the existing namespace devops-workshop..
5.6 Push the Docker Image to the Container Registry
On the terminal, on the root level, navigate to the application source code directory.
$ cd java-webapp-docker
List the available docker images:
$.
5.7 Configure Automatic Image Build
Go to the build section, enable the Automatically build image option.
For details about how to download the image in other environments, see the repository guide.
6. Deploy Application to Container Service
6.1 Initial Application Deployment to Kubernetes Cluster.
6.2 Create Service.
6.3 Create Trigger.
7. Continuous Integration and Deployment on Container Service
7.1 Install Git
$yum install -y git
7.2 Clone the Source Codes to Local Computer
Next, you would need to clone the codes to the local computer. To do that open a terminal or command prompt. Type
$git clone
After the codes are successfully cloned.
7.3 Create a New Tag
To create a new tag, type
$git tag release-v1.0
7.4 Create a New Branch
To create a new branch from the tag,
$git branch release-v1.0-branch release-v1.0
7.5 Checkout the Codes from the Branch
$git checkout release-v1.0-branch
7.6 Change the Existing Source Code
Go to the home directory of the project source code — java-webapp-docker. Change the directory to src/main/webapp. Open the index.jsp with an editor such as vi or vim. Change the header
to “Welcome to Alibaba Cloud DevOps v1.0”.
<html>
<body>
<h1>Welcome to Alibaba Cloud DevOps v1.0</h1>
</body>
</html>
7.7 Commit Changes and Create New TagUsername for '': <USERNAME>
Password for '': <PASSWORD>
7.8 Automatic Build.
Reference: | https://alibaba-cloud.medium.com/continuous-deployment-automation-on-alibaba-cloud-ci-cd-automation-on-container-service-2-ee30f2803a52 | CC-MAIN-2021-10 | refinedweb | 632 | 59.5 |
SSAS has many of the same communication object models that you have become familiar with in Flash?NetConnection, Stream (also known as NetStream), and SharedObject?with two additional objects?Application and Client. Flash ActionScript uses these objects to connect, stream, and share data with the server. The server can also use the objects to connect, stream, and share data with other Flash Communication Servers or application servers connected to databases. Flash Communication Server ships with two additional libraries?Components (components.asc) and NetServices (netservices.asc)?that add a number of other objects to SSAS. When loaded, these extra objects become available to handle the Flash UI components and Flash Remoting MX. Let's review each object individually.
There exists no relationship between the server-side NetConnection object and the client-side NetConnection object. A client connection with a Communication Server accesses the Application object to handle connection events. NetConnection (on the server) is used to connect to servers. These servers can include other Application instances on a local server or an Application instance on a remote server.
Much like the client-side NetConnection, this object has all the same methods, properties, and events. These features allow you to connect and call methods on other communication or application servers and handle any status changes just like a Flash client would. In essence, when you use the NetConnection on the server, your server becomes a client.
Connecting with other Application instances on the same Flash Communication Server or servers that are remote is just as simple as connecting the Flash player with the server. When you use NetConnection, the receiving server (or Application instance) handles the server as another client, using the events in the Application object on the called server.
This exercise will have your Flash movie call the instance myInstanceName from the SSASTests application. A value will be passed invoking the server to call another instance of the same application using the NetConnection object in SSAS.
The exercise will show how you can connect to another Application instance from SSAS, but the same technique can also be used to connect with a remote Flash Communication Server:
Create a new folder called SSASTests in the FlashCom applications folder.
Open a new file in Flash MX.
Open the ActionScript panel (F9).
Enter the following script on Layer 1, Frame 1:
nc = new NetConnection(); nc.onStatus = function(info) { trace("LEVEL: "+info.level+" CODE: "+info.code);}; nc.connect("rtmp:/SSASTests/myInstance", "kevin", "bird");
Save your Flash movie.
When the username "kevin" is passed through the .connect method, it triggers the server to connect again to a different instance name, myServerInstance. This time, a different username is used so the server won't enter into an infinite loop. If you pass the same username, the server will continue to connect to itself and you will probably bring down the server. (This is said out of experience.)
Follow these steps to create the SSAS connection when the username, "kevin," is received:
Create the main.asc file in the SSASTests folder.
Add the following script to main.asc:
application.onConnect = function(clientObject, username) { // ** ACCEPT THE CONNECTION ** application.acceptConnection(clientObject); // ** CONNECT TO A NEW INSTANCE IF USERNAME == "kevin" if (username == "kevin") { trace("the Server is connecting"); nc = new NetConnection(); nc.onStatus = function(info) { trace("LEVEL: "+info.level+" CODE: "+info.code); if (info.code == "NetConnection.Connect.Success") { trace("you Connected - Great! Go get your self something nice"); } }; nc.connect("rtmp:/SSASTests/myServerInstance", "notKevin"); } else { trace("the Server is NOT connecting"); } };
Save the main.asc file.
As you can see, there is an IF statement embedded within the .onConnect event that monitors the username value for "kevin." If the value matches, a new NetConnection is invoked with a trace informing you that it is connecting. Follow these steps to test your application:
In Flash MX, open the Communication App Inspector (in the Window menu).
Test your movie (Ctrl+Enter).
When these scripts are tested with Flash MX, a review of the App Inspector will show two instances of the same application running (see Figure 11.2).
Now, monitor the trace activity as it happens in the Live Log:
Close your test movie in Flash MX. (Leave the FLA file open; you will be testing it again.)
Select the myInstance instance in the App Inspector and click View Detail. Because myInstance is acting as a client, trace actions are output to its Live Log.
Test your Flash movie (Ctrl+Enter) again while monitoring the Live Log window.
You will see the trace information including the onStatus trace in the Live Log window. Figure 11.3 demonstrates the output created by this application's instance. If you do the same with the other instance, you will not see the onStatus output, because a NetConnection is not being established from that instance.
Although this may seem an impractical exercise, it demonstrates the ease of connecting with another server. Where the IP address (192.168.0.1) is mentioned, replace that with a proper URI of a remote Flash Communication Server.
The Application object contains methods, properties, and events that give you control over a connection invoked by a Flash client and also provides information about the Application instance. Application instances, as you read earlier in this chapter, are loaded when called by a client or through the App Inspector. Each method, property, and event is specific only to the instance, and has no relationship to other instances running on the server.
The Application class is one that you will use most often. Application events handle NetConnection commands from a Flash client or another connected Flash Communication Server. The Application methods offer control over the maintenance of your application, such as cleaning up SharedObjects or streams that weren't closed properly. There are also methods to manage class registration or proxy a remote NetConnection.
When the NetConnection.connect method is called by a Flash client or another server, there are two events that could be triggered. If the Application instance hasn't been loaded, the event Application.onAppStart is called before any other function. After the instance is loaded, every client connecting triggers the Application.onConnect method. This is a function primarily used to assemble any authentication scripts or prepare unique objects, such as streams or SharedObjects. The most important aspect of the onConnect is to accept or reject a connection request. Like all ActionScript events, you are required to overwrite both the onAppStart and onConnect events.
You can create any additional properties or methods within the application scope. These methods and properties are available to each client that connects to manage the details of the Application instance.
A common use of the onConnect method is accepting or rejecting a connection. You have seen this event at work in earlier chapters when you scripted a connection to the Communication Server. This exercise will manually populate an array of usernames and passwords when the application starts. Flash Communication Server uses this array to challenge a login and password sent from the Flash player and decides to accept or reject the connection. To authenticate a user, follow these steps:
Create a new folder in the Flashcom Applications folder called mySecureApp.
Create an empty main.asc file within the mySecureApp folder.
Add the following script to the main.asc file:
application.onAppStart = function() { // define the array of users that will be authenticated to use this application user_array = []; user_array.push({uname:"kevin", password:"bird"}); user_array.push({uname:"colin", password:"tank"}); user_array.push({uname:"sharon", password:"craft"}); user_array.push({uname:"sandy", password:"car"}); };
You have just overwritten the onAppStart method for this application. This script runs only once when the application is instantiated. For those of you who might be wondering, "This is a strange way to declare an array," this array is known as an associative array or an array of objects. You might also notice that instead of using new Array when declaring the array, a double square bracket is used to declare an empty array ([]). The array of objects operates very similar to a database record set, which is a little foreshadowing to Chapter 13. This associative array is used as a data store by the onConnect method to ensure each person accessing the application has a valid login and password.
For a Flash client to connect to the application, the connection must be "accepted." You can accept connections using the methods Application.acceptConnection or Application.rejectConnection. Combining these methods with the onConnect event is the most common use.
The NetConnection call from a Flash client sends the login and password as custom parameters of the .connect method. They are handled by the onConnect method. You use those values to match against the data in the array. These next steps will construct the authentication script inside the onConnect handler:
Below the onAppStart function, add the following script to overwrite the onConnect method:
application.onConnect= function(clientObject, username, password) { // Loop through the array to challenge the username and password passed through the connect
Declare a variable called isAuthenticated to false. You use this to store a successful match in the array loop:
var isAuthenticated = false;
Create an array loop that steps through the array trying to match the username and password combination. If the challenge is true, isAuthenticated will be true, and the loop will break out:
for (uname in user_array) { trace("testing" + uname); var thisUSR = user_array[uname].uname; var thisPWD = user_array[uname].password; var challenge = (username == thisUSR) && (password == thisPWD); if (challenge) { var isAuthenticated = true; break; } }
When the loop has finished, a second challenge of the isAuthenticated variable accepts or rejects the connection. This is the end of the onConnect function, so make sure the closing bracket is included:
// Accept/Reject the Connection if (isAuthenticated) { application.acceptConnection(clientObject); } else { application.rejectConnection(clientObject); } };
This may look a little complicated, but it really isn't. You can immediately see that this method is set up to receive three parameters:
clientObject
username
You can have as many parameters in this method as you need; however, you must always pass the clientObject to assign this client to the application. The bulk of the work is done by the looping through the array of objects. The username and password are transferred into temporary variables on each loop. A challenge looks for a matching username/password combination. Each loop sets the challenge variable to false until a correct match is found. The loop breaks out with a correct match, setting the isAuthenticated variable to true. After the loop, the isAuthenticated variable is challenged, and if it is true, the application accepts the connection. This changes the status of the connection and triggers the NetConnection.onStatus function on the Flash client (not shown here).
The Flash player does not have an interface for this exercise. Instead, you hardcode the username and password values. The values are passed to the.connect method as extra parameters. Let's script the call that the Flash player will make:
Open a new Flash movie within Flash MX.
Add the following script to Layer 1, Frame 1:
nc = new NetConnection(); nc.onStatus = function(info) {trace("LEVEL: "+info.level+" CODE: "+info.code);}; nc.connect("rtmp:/mySecureApp/myInstance", "kevin", "bird");
Save the Flash movie.
This script makes a connection call to the myInstance instance of the mySecureApp application. Because there is no Flash interface used in this exercise, you must monitor the trace activity of both the Flash movie and the server. You need the App Inspector window and the Flash MX output window. Follow these steps to manually load the application in the App Inspector:
Open the App Inspector window in Flash MX.
Load the instance manually using the App/Inst text input box on the main screen of the App Inspector. Enter mySecureApp/myInstance in the field, and click Load.
Click the new active instance and select View Detail.
Click the Reload App button to monitor the trace actions while the Application instance reloads.
Test your Flash movie (Ctrl+Enter).
If everything is correct, your Flash MX output window should display a connect.success status message. Now, try a wrong username and password and test again to receive the connect.rejected status message.
The Application object also has application.onDisconnect and application.onAppStop events. When a user closes the browser, or disconnects the application, the onDisconnect method is triggered. When the server shuts down, or the instance is reloaded, the onAppStop method triggers. Try these out by placing the following functions at the bottom of your main.asc file, and then reload your application:
application.onDisconnect = function() { trace("Was it something I said?"); } application.onAppStop = function() { trace("Thanks for all the Fish!"); }
If you know you will have multiple instances running within a single application, you could use the application.name property as a challenge to grant additional privileges to the user. The best place for this test is within the onConnect event:
application.onConnect = function(myClientObj) { if (application.name == "SSASTests/underwear"){ trace("welcome to the underworld!"); } }
To get the most out of what the Application object can offer, review the Quick Reference guides in the appendices.
By now, you have a good understanding of object-oriented programming (OOP) concepts. A key to understanding OOP is realizing that objects can be instanced (or instantiated). The concept of a prototype can be daunting at first; however, it is very straightforward. Each of the objects you have reviewed so far are prototypes. A prototype is like a stencil. In OOP, you prototype methods, properties, and events. Each object used is actually a prototype.
How does this relate to the Client object? Macromedia has taken the concept of OOP and related it to everything, as you saw with the Application object. When a client (Flash player) successfully connects to an Application instance, that client becomes an instance of the Client object on the server. The properties, methods, and events that are built into the Client class are instanced and now only relate to that Client instance. There is no connection to other instances. A quick example of this is the property Client.ip. This property exposes the IP address of the connected client to the server.
This IP address is unique for each client that is connected to the Flash Communication Server. Similar properties are available to return the Flash player version and operating system for each client.
The Client prototype (or class or object) can be used to set permissions to access streams or SharedObjects, or set the limits on bandwidth.
You can create custom methods and properties within the Client instance. When you do this, the Flash client can access server-side methods and properties. Using the NetConnection.call method in Flash MX, you can invoke methods that have been defined in that Client's instance. There are some tricks to this, however. First, you can only create Client methods and properties after the client's connection has been accepted, using the Application.acceptConnection. This is because there has been no instance of the client until it has connected. After the connection has been accepted, you can then set new functions that can be called by the Flash client. The following example shows a custom function, called hello, that can be accessed by the client after the connection has been accepted:
ClientObj.hello = function(name){ return "hello from the server, "+ name; }
This function must be declared after the connection has been accepted. To access this function in Flash, use the NetConnection.call method. This function takes one parameter.
nc.call("hello", new eventHandler, "Kevin Towes");
Remember that this function is not available until the server has accepted the connection and created the Client object. To test this, place the client-side code within a nc.onStatus handler.
This exercise will step you through Flash ActionScript that will call and handle a function defined on the server. To make things more interesting, the server will also call and handle a function defined in Flash ActionScript. So, there will be a function on the server called sayHelloServer and a function on the client called sayHelloClient. Each of these functions will have a trace function that will show up in the respective trace output windows.
This is a brain teaser, so let's walk through it. When the Flash client calls the server function, the App Inspector's Live Log will display a message that was set on the server. When the server calls the Client function, the Flash MX output window will display a trace in its output window. Let's go one level deeper and send an object from the server to the client. We'll start on the server in SSAS, and then move to Flash MX to script the client:
Create a new folder in the Flashcom/Application folder called myHello.
Create a new main.asc file.
Add the following onConnect handler to the main.asc file. This script automatically accepts all incoming connection requests and instantiates the Client instance:
application.onConnect = function(clientObject, username) { application.acceptConnection(clientObject);
After the Client object has been instanced by the Application.acceptConnection, you can now start declaring new functions the client can access.
Create a new function called sayHelloServer in the Client instance clientObject. Place a trace action and a return object (in this case, just a string):
// Define a function for the Client to Call - send him an object clientObject.sayHelloServer = function() { trace("The client says How Ya Doin, Bucko.. Got Somthin' for ya!"); return ("FlashCom Server Rocks!"); };
Call the function sayHelloClient that you will script in Flash MX:
// invoke the function on the Client clientObject.call("sayHelloClient"); };
That's it! As you can see by this example, you must declare custom Client functions after the client has connected. As your functions get more complex, you may find it easier to move them outside the onConnect event and into another function. Now, on to Flash:
Open a new Flash movie in Flash MX.
Open the Actions panel on Label 1, Frame 1.
Create a new NetConnection object:
nc = new NetConnection();
Create the onStatus function for the NetConnection, and place a challenge on the returned status .code. If the connection is successful, call the server function sayHelloServer. Remember, server functions are casE SensItivE:
nc.onStatus = function(info) { trace("LEVEL: "+info.level+" CODE: "+info.code); if (info.code == "NetConnection.Connect.Success") { // Call the Server nc.call("sayHelloServer", new server_ret()); } };
In the nc.call, there is a new object instantiated called server_ret. A function that is called over a NetConnection may not return its results immediately. To compensate for this, an object to receive and handle the result or error must be created for each server function you call. This is called the result object, and it can contain two functions. The onStatus function is invoked if there was an error with the function. The onResult function handles successful function calls. Here is the script to handle a successfully returned function; add this code below the nc.OnStatus function:
// handle any objects returned from Flash's call to the server server_ret = function () { this.onResult = function(value_ret) { trace("Message From the Server: "+value_ret); }; };
The server returns an object that contains a string value. The returned value is captured in our variable value_ret. This can be any variable name you want. We are only going to use the value to trace it to the output window.
Declaring a function that the server can invoke is simple. You define it as a NetConnection method. The server cannot call a function that is not declared in the NetConnection instance. The following traces output to the Flash MX output panel when it is invoked:
Add this line of code to the bottom of your ActionScript panel to define the function sayHelloClient within the context of the NetConnection:
// define a function on the NetConnection that will be called by the server nc.sayHelloClient = function() { trace("The Server says.. Yo, Dude!"); };
Connect the NetConnection to the Communication Server to start the show:
nc.connect("rtmp://192.168.0.1/myHello/myInstance");
Save the Flash file.
Now, you are ready to play. To watch the action, you must have the output window in Flash MX open (F2) and the App Inspector ready. If you want, manually load the Application instance in the App Inspector, or you can wait until your Flash test movie creates the instance. Test your movie using Ctrl+Enter. Your output windows should look something like Figure 11.4.
What if you want to create a function on the server that all clients can have access to? You can do this by adding a method or property to the Client object prototype. This is called extending the class.
This example will extend the Client class with a new method called setConnectTime. It will first check to see if the property connectTime is defined, which it won't be, and then it will set it to the current date and time. You try this code using the previous exercise. Place it at the bottom of your SSAS in main.asc:
Client.prototype.setConnectTime = function() { if(this.connectTime == undefined) { this.connectTime = new Date(); } return this.connectTime }
This is now a global method to the entire Client class, just like the Client methods. To use this method, place the call in the onConnect event. This example uses the instance name clientObject, so you could place it in the previous example:
clientObject.setConnectTime();
A new property called connectTime is set. When accessed, it returns the date and time the client connected. As you have already seen, all Client methods within the Client class can be accessed by the Flash client, including this new prototype. You can try it by adding the following line to the onStatus function in the previous exercise:
nc.call("setConnectTimes", new server_ret());
This traces the server time you connected in your Flash MX output window.
One last technique to note is the capability to assign read and write permission to streams and SharedObjects. There are two properties used for this: Client.writeAccess and Client.readAccess. These properties both work on the principle of file access. By default, when a client connects, it is given read and write access to the entire instance. This means it can publish and subscribe to streams, or read and write any SharedObject accessible to the Application instance. You can handle security by setting up different access levels to your SharedObjects and streams. This will be covered in the next two sections; however, this is a good introduction. Let's say you create a SharedObject that you only want the server to write to, but everyone can access it and "listen" to changes made to it. You would set up the SharedObject on the server like this:
server_so = SharedObject.get("mySecureFolder/mySharedObject",true);
Notice the use of a folder here. This actually translates on the server as a folder name, but more importantly, it is an access level. Streams are the same; for example:
myStream = Stream.get("mySecureStreams/myStream");
Now you have two access levels you must lock out: mySharedObject and myStream. To achieve this, you simply set the Client properties when they connect. The following script would allow all clients to read and listen to all resources available; however, the client could only create resources (SharedObjects and streams) in the /pub folder:
application.onConnect = function(clientObject, username){ clientObject.writeAccess = "/pub"; clientObject.readAccess = "/"; application.acceptConnection(clientObject); }
You can create a list of folders by separating them with a semicolon (;). In the preceding script, a client can only publish a SharedObject in the /pub folder (or access level). The ActionScript on the client would like this:
flash_so = SharedObject.get("pub/mySharedObject",true);
As you can see, the Client object is a great tool to communicate between client and server. Understanding the concept of the instance is the key to the entire Flash Communication Server. Next, you will review the Stream object. Keep in mind that you will instance the Stream class each time you want to use it.
The Stream object is a powerful object that can be used to manage streams coming in and going out from the server. As you have already seen with the client-side NetStream object, a Flash Communication Server stream is a one-way feed of video, audio, or a combination. Communication Server clients can connect multiple streams to a single connection; however, each stream must either publish content to the server or subscribe to content from the server. Streams are collected on the server within an Application instance. They can be prerecorded or live.
Obviously, you cannot watch or listen to a stream on a server, because there is no interface! So what can you do with SSAS and streams? The server can do a number of unique operations that cannot be done on the client. Because of its position in the network, the server maintains priority control over all streams.
This means that it can cancel or overwrite any stream. Some roles that SSAS can take with the Stream object include chaining servers together, acting as a video switcher between live and/or recorded video sources, streaming a play list, or recording a play list or live stream that wasn't set to be recorded by the publisher.
A key difference between the server-side Stream object and the client-side NetStream object is the play() function. The play() method on the server is similar to the publish() method on the client. The play() function publishes content to a stream. You might ask, "If the server does not have a video or sound device, how can it publish?" The play() function takes its video sources from one of two places: prerecorded Flash video (FLV) or live streams being published by a client.
Consider the play() function as a play list that can control what a stream is sending. Let's say you have three prerecorded Flash videos that you want to sequence together. video1.flv would play for 10 seconds, then video2.flv would play for 10 seconds, and then video3.flv for 10 seconds. Using multiple play() functions in SSAS makes it easy to build this sequence. Here is some sample script that would achieve that:
startStream = function(){ // Create the stream var my_stream = Stream.get("serverStream"); // Start the playList my_stream.play("video1",0,10); my_stream.play("video2",0,10); my_stream.play("video3",0,10); }
When the function startStream is called, the stream serverStream is created, and the play list begins. This play list starts immediately, even if no client is connected. The stream is running in real time. If a client subscribes to the stream 15 seconds after the function was called, the client would start in the middle of video2.flv.
You could also do this with a live stream. Let's say you want to play video1, then video2, and then switch to a live stream. The script would look very similar, except video3 would be replaced with the name of the live stream being published to the server by a client. Take a look:
startStream = function(){ // Create the stream var my_stream = Stream.get("serverStream"); // Start the playList my_stream.play("video1",0,10); my_stream.play("video2",0,10); my_stream.play("someClientStream",0,-2); }
The play() function has similar parameters to the client side. The first parameter is the stream name. This can be the name of a live stream being published by a remote client or server. startTime is the next parameter. With a recorded stream (FLV file), this references the start time in seconds to begin the stream. If you are referencing a stream that is being published by a client, there are two values you can use. If startTime is set to a value of -1, Flash Communication Server tries to connect to a live stream published remotely. If the stream does not exist, it waits until the stream is created by the publisher. If you set the value to -2, Communication Server attempts to look for a prerecorded FLV video on the server with the same name. If there is no live stream and no recorded file, Communication Server creates a stream and waits for someone to publish to it.
The ?2 option is great if you are preparing a live broadcast and need to have some filler while the stream is being set up. The reset parameter follows the startTime and expects a Boolean value. It clears the stream if it is set to true. The last option allows the play function to source a stream from a NetConnection to another server. This is a key element for chaining servers together. Let's look at some scenarios of how you can use the Stream object, including chaining servers to increase user and bandwidth capacity.
As you saw, the Flash Communication Server can switch between live and recorded streams using a preset play list. This is a great technique, but you may find you want some additional control over what subscribers are seeing. At this point, you will have to create some sort of Switching interface in Flash MX.
Figure 11.5 represents a scenario of four live streams being published to Flash Communication Server by four separate Flash clients. The Flash clients that are on the receiving end are only receiving one stream. Using SSAS, you could automatically cycle the source of the outbound stream from any of the four inbound streams similar to the previous example. This would be great with a security-camera application that required you to cycle between a number of video sources. However, you want more control over when the streams are switched.
A better solution would be to build a Flash application that could control the SSAS and allow you to manually "switch" between video sources. Figure 11.6 isn't real, but it demonstrates how you could build a Flash-based video switcher to control what the live stream is.
In this example, there are four live streams and one prerecorded advertising stream. The operator of this interface can control what is being sent to the server stream.
Chaining servers is a great technique for distributing the load on your server. If your Flash Communication Server license only allows 10 users and you need 15, you can use this redistribution technique. The Flash Communication Server is a point-to-point network. This translates into the server reserving enough bandwidth for each user subscribing to a stream. This is different from a satellite TV approach, which uses a point-to-multipoint connection. With satellite TV, the broadcaster sends out its signal and, it doesn't matter how many people are watching it, there is no additional load on the satellite if one person is watching or one million people are watching.
When you chain servers together, you can increase the number of users that can watch your stream, and you increase the bandwidth available. In Figure 11.7 there are three servers chained together. Each server has a 10-user license. This would allow a total of 24 Flash players to connect to the live stream. Each server would reserve one publish stream (outbound) for another server. Each server would use another stream as its subscription (or inbound) stream.
A fictitious Flash video switcher application will control the play list on the server.
You can achieve this very easily. First, you need to connect the server to another server, and then you simply connect the play function to a remote server stream. Let's use the same script from the earlier example, but this time, video 3 will be sourced from another Flash Communication Server stream:
startStream = function(){ // establish a NetConnection to a remote application instance that // is streaming. nc = new NetConnection(); nc.connect("rtmp://[remote server]/[remote app]/[remote instance]"); // Create the stream var my_stream = Stream.get("serverStream"); // Start the playList my_stream.play("video1",0,10); my_stream.play("video2",0,10); // receive the 3rd video from a remote server my_stream.play("someOtherServerStream",0,-1, false, nc); }
As you can see, the syntax is not that complex. Sourcing streams is another great feature of Flash Communication Server.
There is one more thing you can do with the Stream object: record. You can assemble a series of streams into a single recorded stream that can be played back without a play list. The record() method records the play list into a single FLV file, named with the stream name. In the following code sample, a file called serverStream will be created in the folder /myApp/streams/myInstance/ serverStream.flv:
startStream = function(){ // Create the stream var my_stream = Stream.get("serverStream"); // Start the playList my_stream.record(); my_stream.play("video1",0,10); my_stream.play("video2",0,10); // receive the 3rd video from a live source my_stream.play("someClientStream",0,-1); }
Like the client-side NetStream, you can also invoke functions through the stream using the .send method. You can monitor buffer time and set the buffer time, just like on the client. Buffer time is the amount of memory allocated to preload a stream before it is played. You can also use the length function to determine the length of a prerecorded FLV file.
Stream is an integral part of the Flash Communication Server. It is very powerful and extremely scalable. Security is achieved as with SharedObjects through access levels, or folders. For more details on security, review SharedObject security in the next section.
The SharedObject programming model is clearly the most exciting and most powerful feature of the Communication Server. Some might consider the capability to stream video as the best part, but after you understand the power of SharedObjects, your imagination will work overtime with the possibilities. The server-side SharedObject is like the client-side SharedObject, with a few additional features.
A SharedObject stores two things: objects and methods. They can be accessed by any connected Flash or server client. These clients are completely synchronized with each other. Any client or server with appropriate permissions can change, add, or remove data. These activities invoke Flash Communication Server to announce the change to all connected clients. These clients respond to the announcement appropriately by refreshing their local memory cache of the SharedObject. Client-side functions can be invoked through broadcast messages over the SharedObject.
SharedObjects can be persistent or temporary. They can be created by the server or by a client connected to the server. SharedObjects can be locally owned or owned by another instance. This means that you can share data across instances and applications. If that isn't enough, you can also access SharedObjects owned by an instance on a different server somewhere else in the world! This is a technique called proxied SharedObjects.
These next few sections will introduce you to some advanced concepts of the SharedObject as it is accessed using server-side ActionScript.
Data is stored in a concept called slots. Slots are name and value properties contained as attributes of the SharedObject.data property. This may be a little confusing at first, but when you get used to the idea, it makes a lot of sense. Consider the data property of a SharedObject like the _root of a directory. Within the root, you can create folders that contain files. Folders can also contain subfolders, and so on. Visualizing this tree will help you understand the concept. A slot can be any valid ActionScript object. This includes arrays, objects, recordsets, or even simple variables. The exercise in Chapter 8, "STEP 8: Collaboration with SharedObject()," clearly demonstrated simple name and value variables as independent slots of the data property. The user access array you created earlier in this chapter could be completely stored in a persistent SharedObject, if you wanted. Let's take a look at how you would do that.
This was the array you created earlier:
user_array = []; user_array.push({uname:"kevin", password:"bird"}); user_array.push({uname:"colin", password:"tank"}); user_array.push({uname:"sharon", password:"craft"}); user_array.push({uname:"sandy", password:"car"});
Placing this array into a SharedObject slot is simple.
Note
Unlike the client-side method, in server-side ActionScript, you must use a setProperty method to add or edit slots. Here is some sample SSAS to add/edit a slot called user_array in the SharedObject secureData/systemObject:
MySystemObject_so = SharedObject.get("secureData/mySystemObject", true); MySystemObject_so.setProperty("userData", user_array);
Reading SharedObject data also requires a unique method, getProperty. Here is an example of transferring the entire array from the SharedObject to a local server variable:
var myServerVar = MySystemObject_so.getProperty("userData");
This all happens in real time through a powerful process of synchronization messaging. The Flash Communication Server sends messaging "objects" to each connected client and server. This object is an ActionScript array of objects called information objects. This is a similar concept you see with NetConnection or Stream. When data changes in the SharedObject, everything that is connected is informed of the data change by the Flash Communication Server. Data can be simultaneously changed, added, or removed by the server with SSAS, or by any number of connected clients using ActionScript or SSAS.
At first glance, it might seem very complicated, primarily because of the array of objects. The information object is handled on each client and the server by the onSync event. The process was demonstrated in Chapter 8 where there were multiple clients changing data at the same time.
The array can contain a batch of change events. It does not contain data. You are responsible for building a handler on the client and the server for the data change notifications. This might include transferring a SharedObject slot value to a local variable, or affecting an object appropriately. The array is useful (on the client) if it becomes disconnected and has to reconnect. Upon reconnect, the array may have a number of messages inside that it must handle.
The following onSync handler script template demonstrates how you can handle the information object both on the client and on the server. You must loop through the array and challenge and handle the code property on each loop. This template will handle the four possible cases of the code property:
this.so.onSync = function(info) { trace("Synchronizing Data"); // // Use this structure as a prototype for your onSync Handlers. // Loop through the Array of Objects using the IN operator // for (name in info) { trace("[sync] Reading Array Object #"+name+" code("+info[name].code+","+info[name].name+")"); // // ::: The following switch handles code values returned by the object // Place Code Here // switch (info[name].code) { case "change" : trace("::Handle a change of data by another client"); // Place Code Here break; case "success" : trace("::Handle successful change of data from this server"); // };
The whole synchronization process is explained in detail in Chapter 8.
You can control the security of SharedObjects using the Client properties Client.writeAccess and Client.readAccess. Review the Client object section earlier in this chapter for some example script. SharedObjects, like the Stream object, can be filed into access levels, or folders. This can only be done when they are first created.
For maximum security, creating a SharedObject on the server is the best practice. If you can, create the SharedObject on the application.onAppStart. Create a strategy for storing SharedObjects. For example, use a common folder for all sensitive SharedObjects and a public folder for all non-sensitive objects. Remember, you can have as many SharedObjects as you need. Don't try to place sensitive data in slots of one big general SharedObject. It just cannot be secured that way.
SharedObjects can also exist within other Application instances, or even on different servers altogether. Connecting to a remote SharedObject from the server is a process called proxied SharedObject. The concept isn't that difficult to grasp. When an Application instance connects to a SharedObject within another instance or application local or remote, it makes that SharedObject available to all of its connected clients.
The process is similar to an Internet service provider, or your network router. When you dial up your computer to your provider, you have access to everything your provider is sharing. If you then have a router in your home or office, you redistribute that feed to workstations in your network. This can be called a proxy server. To connect, you must route your request through the proxy server. The Flash Communication Server Application instance is no different. When the SharedObject is connected, it is available to all of its connected clients, unless you have placed it within an access level (or folder). Connecting is simple.
First, you make a connection to a remote server, or Application instance, using the SSAS NetConnection object. This can be done in the application.onAppStart function. It is not recommended to have it within the onConnect, because each time a client connects, the server will reconnect. You could write some script that challenges the NetConnection.isConnect property. The following script uses this technique:
application.onAppStart = function() { nc = new NetConnection(); }; application.onConnect = function() { if (not nc.isConnected) { nc.connect("rtmp://[remote server]/[remote app]/[remote instance]"); // - or - nc.connect("rtmp:/[local app]/local instance]"); } };
When your server is connected, you then attach the SharedObject to the NetConnection instance. The following script is the exact script you saw in the preceding; however, it is not stored within its Application instance:
mySystemObject_pso = SharedObject.get("secureData/mySystemObject", true, nc); mySystemObject_pso.setProperty("userData", user_array);
The suffix _pso was added to the SharedObject to signify proxy SharedObject. It is not required, but it helps you keep things straight.
If you weren't impressed enough already by the SharedObject model, this might just add the cherry to the top. You can create ActionScript functions and assign them to a SharedObject. Think about that for a moment. If you can create a function and assign it to a SharedObject, that means a Flash player can invoke a function on another Flash player! SharedObject functions are primarily used for messaging. You cannot "call" a SharedObject function like you can a remote Flash function. You use the SharedObject's send method to invoke the function. You cannot create a SharedObject function using server-side ActionScript. It can only be created by the client, and the server doesn't receive any response from the client on success or failure of the send method; therefore, it is asynchronous.
To execute a SharedObject method on the Flash client using the send method, use the following code:
var my_so = SharedObject.get("SharedObjectFileName", true); my_so.send("client-so-method");
Creating SharedObject functions will be covered in the next chapter; however, here's a sneak peak to create a SharedObject function on the Flash client:
so=SharedObject.getRemote("myObject", nc.uri, true); so.connect(nc); so.data.myMethod = function() { trace("Hi There from your Friendly SharedObject."); };
SharedObjects can be temporarily "locked" only by the server. Locking a SharedObject allows the server to perform operations on the SharedObject without triggering the onSync events for each player. Locking also allows you to ensure that there are no SharedObject write actions while the server does what you want it to do. During the lock, each change that is made is batched. Unlocking the SharedObject engages the batch to announce the changes to the connected clients.
There are two methods associated with locking: so.lock() and so.unlock(). Wrap your SSAS operations in these functions and you will execute a lock and release.
Because the server-side version has direct access to the SharedObject, you can perform a few additional methods to the data such as some clean up methods like .clear, .purge, and .flush.
.clear deletes all properties (slots) of any a object. It doesn't take any arguments. This method is useful if you create a temporary SharedObject and want to clear all traces of it from the server. Here is the .clear method:
var my_so = SharedObject.get("SharedObjectFileName", true); my_so.clear();
.purge is useful to clean up any empty properties or properties that are older than the current version (more on versions shortly). The flush function transfers the memory-version of the object to a file. You can only do this with persistent SharedObjects. The file is located in a SharedObjects folder within the Application folder. Like the Streams folder, this folder contains subfolders referencing any instance names of the application.
.flush forces Flash Communication Server to dump the memory version of a persistent SharedObject to the file version. It's like hitting the Save button when you are writing a book. This is a good habit to get into if the synchronized data you are storing is extremely important and a sudden server halt (such as a power failure or someone clicking that Halt button in the Administration Console) would kill the data. You can do it using the setInterval tag,or after a major operation such as a database query.
Flash Communication Server installs with two additional objects that are used with Flash Remoting MX. These two objects are NetServices and RecordSet. They are discussed in detail in Chapter 13, but we will make a brief mention of them here to keep everything together.
Using the Communication Server, you can expose databases and other services to the Flash player. This is achieved through technology called Flash Remoting MX. Flash Remoting MX operates on the standard HTTP or secure HTTPS protocols using a binary format called Action Message Format (AMF).
The NetServices class contains the methods required to call services on remote application servers. Remote application servers can provide database access and access to other server-level resources such as email or LDAP.
Making a Flash Remoting MX call requires a server that is compatible with Flash Remoting MX. These servers are discussed in Chapter 13. NetServices gives you the tools to connect and call remote service methods that can return any ActionScript object including the new RecordSet object.
The RecordSet object is a series of 17 unique methods that give you familiar tools to interact with a database query result set. Using the concept of columns and rows, you can sort, get column names, and even search through the RecordSet easily.
RecordSet objects can be transferred into SharedObjects for distribution to connected clients. A complete breakdown of the RecordSet methods are included in the Quick Reference appendixes. Example applications using the RecordSet object can be seen in Chapter 13 and Appendix E,"Useful ActionScript Templates Quick Reference."
ActionScript intervals were introduced in Flash MX to allow Flash developers to schedule the call of functions at specific timed intervals. The functionality is also available within SSAS. Intervals on the server can be used fully to let you call functions that may clean up the SharedObjects with a purge() method, or flush() them periodically to the hard disk. You could also develop an interval to capture a still image of an incoming stream to create a time-lapse photography effect. Intervals are easy to set up. This example calls the captureMyCamera function every two seconds:
intervalID_itv = setInterval("captureMyCamera", 2000);
It is important to use a variable to run this setInterval function because setInterval will return an ID value that you need if you want to shut it off. When you are finished with the interval, you can clear it using the clearInterval function, referencing the intervalID used in the previous example:
clearInterval(intervalID_itv); | http://etutorials.org/Macromedia/Macromedia+Flash+Communication+Server+MX/Part+II+Implementing+Macromedia+Flash+Communication+Server/Chapter+11.+Server-Side+ActionScript+SSAS/Server-Side+Objects/ | crawl-001 | refinedweb | 7,863 | 57.67 |
Thx - JMP
/* Week 2 Individual Assignment PRG420 Java Programming I Due: Wednesday, January 16, 2008 File Name: Week2Poulsen.java */ /* Write a Java program without a graphical user interface that calculates and displays the mortgage payment amount given the amount of the mortgage, the term of the mortgage, and the interest rate of the mortgage. In this program, hard code the amount = $200,000, the term = 30 years, and the interest rate = 5.75%. Insert comments in the program to document the program. Post your programs in your Learning Team forum for peer evaluation. */ public class Week2Poulsen.java { public static void main() { | http://www.dreamincode.net/forums/topic/40889-homework-help/ | CC-MAIN-2016-30 | refinedweb | 101 | 65.83 |
#include <playerclient.h>
Inherits ClientProxy.
List of all members.
Position2DProxy
[inline]
Constructor. Leave the access field empty to start unconnected.
Send a motor command for velocity control mode. Specify the forward, sideways, and angular speeds in m/sec, m/sec, and radians/sec, respectively. Returns: 0 if everything's ok, -1 otherwise.
Same as the previous SetSpeed(), but doesn't take the yspeed, yaw). Note that x and y are in m and yaw is in radians. Returns: 0 if OK, -1 else
x
y
yaw
Only supported by the reb_position driver.
Only supported by the reb_position driver. spd rad/s, acc rad/s/s
Only supported by the segwayrmp driver.
Accessor method.
[virtual]
All proxies must provide this method. It is used internally to parse new data when it is received.
Reimplemented from ClientProxy.
Print current position device state. | http://playerstage.sourceforge.net/doc/Player-1.6.5/player-html/classPosition2DProxy.php | CC-MAIN-2015-32 | refinedweb | 140 | 54.69 |
MFCC means Mel-frequency cepstral coefficients. It’s a powerful feature representation for sound. Although there is a lot of implementations in different programming language for MFCC, they give sheerly different results for the same audio input.
To solve this problem, I got an open-source implementation of C++ for MFCC and built a Python module for it. By using SWIG, this work became less painful.
The function has
sample_rate and a one-dimension-array as input, a two-dimensions-array as output. So the header file of C++ looks like:
void mfcc(int sample_rate, short* in_array, int size_in, double** out_array, int* dim1, int* dim2 );
We also need to use
numpy, so the interface file for SWIG is:
%module mfcc %{ #define SWIG_FILE_WITH_INIT #include "mfcc.hpp" %} %include "numpy.i" %init %{ import_array(); %} %apply (short* IN_ARRAY1, int DIM1) {(short* in_array, int size_in)} %apply (double** ARGOUTVIEW_ARRAY2, int* DIM1, int* DIM2) {(double** out_array, int* dim1, int* dim2)} %rename (mfcc) my_mfcc; %inline %{ void my_mfcc(int sample_rate, short* in_array, int size_in, double** out_array, int* dim1, int* dim2) { mfcc(sample_rate, in_array, size_in, out_array, dim1, dim2); } %}
To use this module, here is an example Python code:
import mfcc import numpy as np from scipy.io import wavfile sr, audio = wavfile.read("mono.wav") output = mfcc.mfcc(sr, audio) print(output.shape, output)
All the code is in my repository. | http://donghao.org/tag/swig/ | CC-MAIN-2020-40 | refinedweb | 220 | 55.84 |
Hi,
Ive a ListView with ViewCell which contains a Label and a Button, my List is for showing Todo Items and the Button is to mark the Todo Item done and show the status on the Button as Text (with a Unicode Checkmark or Cross).
So I want to change the Button Text when a bool attribute binded to a DataTrigger raises PropertyChaged.
My Model Class "TodoItem" implements the IPropertyChanged interface and my "TodoItemViewModel" has a OberservableCollection with TodoItems and implements the IPropertyChanged interface too ( Iam using the NuGet package "PropertyChanged.Fody" to implement the interface).
For Android and iOS its working perfectly, when Iam clicking the Button of a ListView Item, the "done" Attribute of the TodoItem in the OberservableCollection gets changed to "true" and so the PropertyChaged Event gets triggert and causes the Button DataTrigger in XAML to correctly update the Text of the clicked Button.
But on UWP the Button Text sometimes seems to do not update correctly and gets Empty (normally it sould show a Checkmark or a Cross).
Here is my XAML snippet:
<ListView x: <ListView.ItemTemplate> <DataTemplate> <ViewCell> <StackLayout Orientation="Horizontal" BackgroundColor="LightGray"> <Label Text="{Binding name}" FontSize="Large" FontAttributes="Bold" HorizontalOptions="CenterAndExpand"/> <Button Clicked="doneButton_Clicked" CommandParameter="{Binding .}" HorizontalOptions="End" > <Button.Triggers> <DataTrigger TargetType="Button" Binding="{Binding done}" Value="true"> <Setter Property="Text" Value="✔"/> </DataTrigger> <DataTrigger TargetType="Button" Binding="{Binding done}" Value="false"> <Setter Property="Text" Value="✖"/> </DataTrigger> </Button.Triggers> </Button> </StackLayout> </ViewCell> </DataTemplate> </ListView.ItemTemplate> </ListView>
Here is the TodoItemViewModel which is binded as BindingContext in "OnAppearing" method in the CodeBehind of the XAML :
[AddINotifyPropertyChangedInterface] //From NuGet PropertyChanged.Fody public class TodoItemViewModel { public ObservableCollection<TodoItem> TodoItems { get; set; } //Binded to ListView.ItemsSource public TodoItemModel() { } }
Here ist the method for Button Clicked:
private async void doneButton_Clicked(object sender, EventArgs e) { Button btn = sender as Button; TodoItem todoItem= btn.CommandParameter as TodoItem; if (todoItem != null && btn != null && btn.IsEnabled && btn.IsVisible) { if (!todoItem.done) { todoItem.done = true; } else { todoItem.done = false; } await database.Add(todoItem); } }
Here is a screenshot of the ListView on UWP (Problem marked with blue circle):
I hope someone can help me with this annoying problem on UWP...
Thanks!
Regards,
Tom
@Tom92 - Have you checked Bugzilla? There have been a number of XF bugs that have caused issues like this, but in this case I wonder if you might be hitting this one - (see the comment about plain Labels)
@JohnHardman
For testing now Iam changing the TodoItem.name to DateTime.Now in ListView ItemTapped method.
The name isnt getting changed every time I click on the ListView Item, so I think Iam hitting your linked bug.
So now I will follow the status of this bug on bugzilla.
Thank you for your fast help!
I'm getting what I think is a similar problem. I'm trying to change the layout of a grid shown inside a ViewCell, which works by setting LayoutBounds in an AbsoluteLayout. Rarely, an item will generate with the new value, but most often not. I've checked everything, and the control works fine when it isn't inside a ViewCell. All PropertyChanged handlers are running and the layout bounds do seem to be updating, but the visual almost never reflects those changes. | https://forums.xamarin.com/discussion/100283/listview-item-not-updateing-correctly-on-uwp | CC-MAIN-2019-43 | refinedweb | 535 | 54.12 |
RCMD(3) Linux Programmer's Manual RCMD(3)
rcmd, rresvport, iruserok, ruserok, rcmd_af, rresvport_af, iruserok_af, ruserok_af - routines for returning a stream to a remote command
():). (on Linux: a process that has the CAP_NET_BIND_SERVICE capability in the user namespace governing its network namespace)., is writable by anyone other than the owner, or is hardlinked anywhere,.
The rcmd() function returns a valid socket descriptor on success. It returns -1 on error and prints a diagnostic message on the standard error..
The functions iruserok_af(), rcmd_af(), rresvport_af(), and ruserok_af() functions are provide in glibc since version 2.2.
For an explanation of the terms used in this section, see attributes(7). ┌────────────────────────────┬───────────────┬────────────────┐ │Interface │ Attribute │ Value │ ├────────────────────────────┼───────────────┼────────────────┤ │ 4.08 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at. Linux 2016-10-08 RCMD(3) | http://man7.org/linux/man-pages/man3/iruserok.3.html | CC-MAIN-2016-50 | refinedweb | 144 | 67.55 |
For those who might have missed it we recently starting an effort together with Nokia to create a full set of Qt friendly C++ bindings for GStreamer. This effort is spearheaded by Mauricio Piacentini, building on the original code by and working with George Kiagiadakis, who has also started a blog about the Qt GStreamer bindings. In addition for its use in MeeGo we also hope that this effort will make the KDE community first class citizens of the GStreamer community and thus help push multimedia on the free desktop forward. So be sure to bookmark Mauricios blog so that you can follow his progress, he plans on blogging regularly about the effort. As part of this effort the code will also be hosted along with the rest of the GStreamer modules on freedesktop.org.
One thought on “Growing the GStreamer family with QtGStreamer”
You couldnt have found an uglier namespace than “QtGS[t]”, hard to type – what’s wrong with just QStreamer, for simplicity’s sake? | https://blogs.gnome.org/uraeus/2010/10/22/growing-the-gstreamer-family-with-qtgstreamer/comment-page-1/ | CC-MAIN-2016-30 | refinedweb | 167 | 52.33 |
Latest Development News
All news
Windows Phone
Windows Store
5/1/2012
source: windowsteamblog.com
Today.5/1/2012
source: tonicodes.net
List.4/30/2012
by WindowsPhoneGeek
Daily WP7 Development News 30 April 2012:
- Reporting a Concern about an App in Marketplace
- Introducing the jQuery Mobile Metro Theme
- Building A Test Texting System On Windows Phone With TextBelt API
- Bing Maps with custom pushpin and popup interaction
- How to Create Splash Screen in Windows Phone
- Converting the XNA Platfomer Starter Kit to Sprite Sheets
- Intro to XNA on Windows Phone Part 5
Subscribe to our News feed or follow us on Twitter @winphonegeek . (We list the latest Windows Phone 7 development activities.
source: create.msnd
In an effort to maintain high quality apps on the Marketplace, we have created a new e-mail alias to report any app concerns. Before you report a concern, please read this first. This article covers three commonly asked questions about reporting an app:
- Where do I report concerns related to Trademark and Copyright Protection?
- What app concerns can I report?
- How do I report a concern?
4/30/20124/30/2012
source: blog.jayway.com
Live tiles was introduced with Windows Phone. Compared to an icon, which only used to start an application, a live tile is more like a window into your application. A window where you can present up to date information even if your application is not running. Live tiles in one of the strengths of Windows Phone and it has, of course, been transferred to Windows 8.
But there are differences between live tiles in Windows Phone and Windows 8. With a Windows Phone you had greater limitations in display size and performance. In this post we’ll start with a short overview how live tiles work and then continue with an introduction to live tiles in Windows 8.4/30/2012
source: scottlogic.co.uk
This blog post introduces the new jQuery Mobile Metro theme and demonstrates how to create a web UI that detects the device it is being viewed on, to render a Metro UI on WP7 and iOS on other devices:
Introduction
A couple of weeks ago Microsoft announced the formation of Microsoft Open Technologies Inc. which will contribute to open source projects, standards and interoperability. For Windows Phone 7 developers, where the mobile OS market is highly fragmented, any efforts to push standards and interoperability are a very good thing. The first project backed by the Open Tech interop team was Apache Cordova (PhoneGap) allowing you to run HTML5 applications on your WP7, as covered in one of my previous blog posts. A few days ago, the team announced another release, jQuery Mobile (jQM) Metro. In this blog post we’ll take a look at what jQM is and how it helps you build HTML5-based mobile applications.4/30/2012.4/30/2012
source: coderox.se
When creating a solution which requires a map it’s pretty common to also display pushpins that inform the user of locations. This is very easy to accomplish in Windows Phone, but when you also want to respond to the user tapping one of these pushpins and display maybe a popup, then it becomes a bit more difficult. Here is an approach that I find both easy to implement and understand.
The solution is in short to expose a collection of LocationViewModel’s from the map’s view model. This LocationViewModel encapsulates a GeoCoordinate to position the pushpin on the map, as well as two more properties, a Name property (or at least some sort of descriptive text) and a boolean property called IsSelected. Then I create a custom template for the pushpin in the view to include both the actual pushpin as well as a custom popup element that has its Visibility property bound to the IsSelected property of the LocationViewModel, with a simple converter from Boolean to Visibility. With some Expression Blend magic and some custom margins the solution is quite simple. But there are some gotchas…4/29/2012
source: windowsphonerocks.com
Splash Screen makes your App look good when it is loading initially . It might be a good idea to have a splash screen specially for the apps that takes some time to load.
How to Create Splash Screen in Windows Phone ?
You can create Splash Screen in Windows Phone in 2 ways
1. Use static splash screen image
2. Create a animated splash screen
By default , when a Windows Phone project(Silverlight) is created , SplashScreenimage.jpg file is created ans placed in the project folder.
You can replace this image with your image with the same size (480*800) pixels and setting the Build Action property to “Content”.
You can also create a animated splash screen by following the below steps
1. In the existing Windows Phone Project , create a new user control . Ex : SplashScreen.xaml
2. Declare BackgroundWorker and Popup objects . BackgroundWorker class is defined in the namespace System.ComponentModel; and PopUp class is defined in4/28/2012
source: logannowak.wordpress.com
Recently, while working on Cloud Blaster, I converted the Platformer Starter Kit to a sprite sheet from loading the individual images. Before, performance was taking a huge hit with all the different kinds of tiles I was using, but now it like butter, so I figured I’d share.
The process is rather simple. First, you need to make a sprite sheet. There are a lot of programs that do this for you, but I used this, Nick Gravelyn’s Sprite Sheet Packer, since it will also generate a text file that tells you the rectangle dimensions.
Once you have the sprite sheet, you can get right to the code. First, we need to modify the tile class. Get ride of the texture and add in a rectangle, as well as the changing the overloads for it appropriately. | http://www.geekchamp.com/news?pageNumber=348 | CC-MAIN-2017-22 | refinedweb | 979 | 62.48 |
Idea
Implement methods for modified coset enumeration. This is used to carry out the coset enumeration using a modied coset table. It is also called as the modified Todd-Coxeter procedure. The detailed implementation for all the methods has been provided in the Handbook
Algorithm
All the algorithms for the modified methods are mentioned in the Section 5.3.2 of the Handbook[1].
Implementation
- All the modified methods have been implemetned along with the regualr methods with an additional modified keyword.
- For example,
modified_scanis implemented as:
def modfied_scan(): scan(..., modified=True)
- A few methods which weren’t much similar to the originla methods were implemented seperatetly.
Discussions
- Implementation of methods with a
modifiedkeyword.
- Move the existing
scan_and_fillmethod to the
scanmethod with a
fillkeyword as the implementation is pretty much the same.
Trvial example
Modified coset enumeration example.
>>> f = FpGroup(F, [x**3, y**3, x**-1*y**-1*x*y]) >>> C = modified_coset_enumeration_r(f, [x]) >>> for i in range(len(C.p)): ... if C.p[i] == i: ... print(C.table[i]) [0, 0, 1, 2] [1, 1, 2, 0] [2, 2, 0, 1]
PR
Here is the link to the PR ‘Add implementation of the modified coset enumeration’. This, currently, still needs minor changes and will be finalised soon.
References
- [1] Derek F.Holt, Bettina Fick, Eamonn A.O’Brian. Handbook of Computational Group Theory. | https://ravicharann.github.io/blog/modif-todd-coxeter/ | CC-MAIN-2018-39 | refinedweb | 225 | 51.14 |
This article has been dead for over six months: Start a new discussion instead
meensatwork
Newbie Poster
15 posts since Dec 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
•Community Member
Hello,
Is it possible to use ctypes for this? I tried a sample code from net but it is not working.
from ctypes import cdll myDll = ctypes.LoadLibrary('C++dll.dll') mydll.testString()
Can u tell me how to load a C++ dll and call the functions from python?
I can see typo on your code. myDll is not the same as mydll
There is good documentation at Python Site | https://www.daniweb.com/software-development/python/threads/339536/calling-c-dll-from-python | CC-MAIN-2015-14 | refinedweb | 106 | 77.13 |
Alle 22:46, martedì 9 marzo 2004, Andrew Morton ha scritto:> BlaisorBlade <blaisorblade_spam@yahoo.it> wrote:> > In drivers/char/mem.c do_write_mem can return -EFAULT but write_kmem> > forgets this and goes blindly.First: do not forget this first fix.> > Also, do_write_mem takes two unused params and is static - so I've> > removed those.The "file" parameter is anyway unused - so it can be removed; for the ppos parameter your reasoning holds. I'm posting the patch for these two things against 2.6.4 (now I do not remove realp so I avoid the race you describe).Thanks for answering me - you never lose a patch!> > I actually double-checked this - however please test> > compilation on Sparc/m68k, since there are some #ifdef.>> It's a small thing, but:> > --- ./drivers/char/mem.c.fix 2004-02-20 16:27:21.000000000 +0100> > +++ ./drivers/char/mem.c 2004-03-08 12:17:23.000000000 +0100> > @@ -96,13 +96,14 @@> > }> > #endif> >> > -static ssize_t do_write_mem(struct file * file, void *p, unsigned long> > realp, - const char * buf, size_t count, loff_t *ppos)> > +static ssize_t do_write_mem(void *p, const char * buf, size_t count,> > + loff_t *ppos)> > {> > - ssize_t written;> > + ssize_t written = 0;> >> > - written = 0;> > #if defined(__sparc__) || (defined(__mc68000__) && defined(CONFIG_MMU))> > + unsigned long realp = *ppos;> > +>> A thread which shares this fd can alter the value at *ppos at any time via> lseek() .Well, you are right (not found any locking). I've understood that lseek() is known to be racy, and that the bug in my patch is just the range check that does not work any more; but anyway the marked line in the 2.6.3/2.6.4 kernel is racy, too, and I'm unsure if that is allowed; i.e. man 2 write claims even that "POSIX requires that a read() which can be proved to occur after a write() has returned returns the new data. Note that not all file systems are POSIX con- forming." which would imply that write is not racy. Or not?static ssize_t do_write_mem(struct file * file, void *p, unsigned long realp, const char * buf, size_t count, loff_t *ppos){ ssize_t written; written = 0;#if defined(__sparc__) || (defined(__mc68000__) && defined(CONFIG_MMU))//[...]#endif if (copy_from_user(p, buf, count)) return -EFAULT; written += count; *ppos += written; /*If a second thread lseek()'d between when we read realp and this line, we have a race*/ return written;}-- Paolo Giarrusso, aka BlaisorbladeLinux registered user n. 292729--- ./drivers/char/mem.c.fix 2004-03-13 17:56:09.000000000 +0100+++ ./drivers/char/mem.c 2004-03-13 20:36:35.000000000 +0100@@ -102,7 +102,7 @@ } #endif -static ssize_t do_write_mem(struct file * file, void *p, unsigned long realp,+static ssize_t do_write_mem(void *p, unsigned long realp, const char * buf, size_t count, loff_t *ppos) { ssize_t written;@@ -171,7 +171,7 @@ if (!valid_phys_addr_range(p, &count)) return -EFAULT;- return do_write_mem(file, __va(p), p, buf, count, ppos);+ return do_write_mem(__va(p), p, buf, count, ppos); } static int mmap_mem(struct file * file, struct vm_area_struct * vma)@@ -282,7 +282,9 @@ if (count > (unsigned long) high_memory - p) wrote = (unsigned long) high_memory - p; - wrote = do_write_mem(file, (void*)p, p, buf, wrote, ppos);+ wrote = do_write_mem((void*)p, p, buf, wrote, ppos);+ if (wrote < 0)+ return wrote; p += wrote; buf += wrote; | https://lkml.org/lkml/2004/3/13/90 | CC-MAIN-2016-36 | refinedweb | 537 | 71.04 |
MapReduce for Ruby: Ridiculously Easy Distributed Programming
I am very happy to announce that Google's MapReduce is now available for Ruby (via
gem install starfish). MapReduce is the technique used by Google to do monstrous distributed programming over 30 terabyte files. I have been reading about MapReduce recently and thought that it was very exciting for Google to have laid out the ideas that ran Google. I also wondered how they could be applied to everyday applications.
Recently, I gave a talk on Ridiculously easy ways to distribute processor intensive tasks using Rinda and DRb. This talk came from my work with Rinda recently at MOG. wrote an article that explains what map a reduce do, so I will refrain from repeating him. One of the parts Joel unfortunately messed up on was this sentence though:
[...] [...]
Google, nor anyone I know, has written a map function that will "replace" your existing calls to map, like a plugin. In fact, here is some real world MapReduce example code that is used to provide a word count on an arbitrarily sized document:
#include "mapreduce/mapreduce.h"
// User's map function
class WordCounter : public Mapper {
public:
virtual void Map(const MapInput& input) {
const string& text = input.value();
const int n = text.size();
for (int i = 0; i < n; ) {
// Skip past leading whitespace
while ((i < n) && isspace(text[i]))
i++;
// Find word end
int start = i;
while ((i < n) && !isspace(text[i]))
i++;
if (start < i)
Emit(text.substr(start,i-start),"1");
}
}
};
REGISTER_MAPPER(WordCounter);
// User's reduce function
class Adder : public Reducer {
virtual void Reduce(ReduceInput* input) {
// Iterate over all entries with the
// same key and add the values
int64 value = 0;
while (!input->done()) {
value += StringToInt(input->value());
input->NextValue();
}
// Emit sum for input->key()
Emit(IntToString(value));
}
};
REGISTER_REDUCER(Adder);
int main(int argc, char** argv) {
ParseCommandLineFlags(argc, argv);
MapReduceSpecification spec;
// Store list of input files into "spec"
for (int i = 1; i < argc; i++) {
MapReduceInput* input = spec.add_input();
input->set_format("text");
input->set_filepattern(argv[i]);
input->set_mapper_class("WordCounter");
}
// Specify the output files:
// /gfs/test/freq-00000-of-00100
// /gfs/test/freq-00001-of-00100
// ...
MapReduceOutput* out = spec.output();
out->set_filebase("/gfs/test/freq");
out->set_num_tasks(100);
out->set_format("text");
out->set_reducer_class("Adder");
// Optional: do partial sums within map
// tasks to save network bandwidth
out->set_combiner_class("Adder");
// Tuning parameters: use at most 2000
// machines and 100 MB of memory per task
spec.set_machines(2000);
spec.set_map_megabytes(100);
spec.set_reduce_megabytes(100);
// Now run it
MapReduceResult result;
if (!MapReduce(spec, &result)) abort();
// Done: 'result' structure contains info
// about counters, time taken, number of
// machines used, etc.
return 0;
}
MapReduce takes a large data set (in this case a large file), divides the file into many different pieces, and lets 2000 machines each count words and aggregate statistics for a small part of that file, aggregating the result together in the end.
One of the parts that stood out to me is how there is a clear separation of how to do the call to map and how to do the call to reduce. The other part is all the set calls like
spec.set_machines(2000);. I love the simplicity: you tell the system how to map, you tell it how to reduce, you set some options, and run it. Notice specifically that you are not writing network code... this is obviously a very network intensive task, but that is all hidden behind
#include "mapreduce/mapreduce.h"..
I took the lessons from MapReduce, injected my background of Ruby and came up with what I call Starfish..
Starfish takes a large data set (in this case a database), divides the table into many different sections, and lets machines each do work on sections of the database in parallel, aggregating the result together in the end.
Here is some example code:
class Item < ActiveRecord::Base; end
server do |map_reduce|
map_reduce.type = Item
end
client do |item|
logger.info item.some_processor_intensive_task
end
You will notice a few major differences quite quickly. First, you do not need to require any libraries, if this file was called item.rb you would run
starfish item.rbon.
Aside from the differences, you will notice the similarity, in the server you are setting options, setting
map_reduce.type = Itemmuch like
input->set_format(
out->set_filebase("/gfs/test/freq");works.
However the biggest major difference is that Starfish is open-source and easy to use. Performing distributed tasks is now a ridiculously easy reality for programmers that may not have been steeped enough in CORBA or some other library to accomplish before.
I hope that you find this library helpful, please tell me how you use it and how I can make it work better for you. There any many options I didn't cover, so if you do use it, please read the documentation.
UPDATE: I wrote an example of how I sent emails 10x faster than before using Starfish.
Technoblog reader special: $10 off web hosting by FatCow!
31 Comments:
Lucas, this sounds very interesting indeed! Are you at liberty to discuss the architecture at MOG?
I am wondering why it bacame necessary (from an architecture perspective) to read huge datasets (30gb?) from the database and process in memory?
Aren't DBMS systems optimized for this sort of processing or is it something that the DBMS does not offer (horizontally partitioned tables or federated views etc) and therefore necessary to do it in this manner.
I would be very interested in your thoughts on this.
thanks,
1:31 PM, August 18, 2006
very nice sir!
2:28 PM, August 18, 2006
The beauty of google's system is that the data was distributed as well. Aren't you going to have bottleneck issues with database disk i/o?
5:06 PM, August 18, 2006
Certainly, but Google built their own distributed file system to deal with that issue. Starfish is not ideal for super-large scale distributed efforts, but it certainly helps for many of the distributed systems you regularly encounter.
5:23 PM, August 18, 2006
Looking at your reference to GFS ("/gfs/test/freq"), does it mean that your library works on GFS? I didn't know Google had relased this piece of technology. And the same for Google's clusters of commodity Linux PCs. Without that infrastructure, how your library works? Thanks.
5:55 PM, August 18, 2006
mmm... i have a feeling you don't understand the mapreduce operation well. by spliting into server and clients, your abstraction not only leaks the underlaying network, but you completely forgot the reduce part. certainly you made a distributed system but not a map reduce operation. it looks to me like a small wrapper on top of drb.
6:04 PM, August 18, 2006
To address the GFS comment, GFS is a completely independent tool, a filesystem, used at Google exclusively. Neither Starfish nor MapReduce directly know or care about the underlying filesystem involved. Google does utilize the implications of GFS when using MapReduce to handle some of the disk i/o issues. I am not interested in solving that particular problem since I have not personally reached a point where i/o is the limiting factor.
To address the question to my competence, I would like to say that Starfish and MapReduce were written in vastly different languages with different goals in mind. After studying the papers associated with MapReduce as well as the code examples, I thought to myself about the problems MapReduce set out to solve. I am not interested in writing an exact clone of the code involved to run MapReduce, I am interested in solving a similar problem on a smaller scale.
Secondarily, I am very interested in making distributed programming more accessible to programmers who have never tried to do distributed programming before. I wanted to keep familiar terms like "client" and "server," and keep unfamiliar terms at bay. I feel this helps to quickly understand what is going on which aids in maintenance of Starfish code.
To directly address whether or not I understand the what the mapreduce operation does, I can tell you that in Ruby, mapreduce is simply a call to inject.
To address why I did not feel compelled to add a distributed reduce function to the initial release of starfish, I felt that such a function would be much simpler to write as a helper method to the server than a whole separate operation into itself. I may change my mind about that, but I was going for ease of development of distributed applications, and I find helper methods defined in the server much quicker and easier to write than full reduction methods.
Starfish is not built to compete with MapReduce, it is meant to solve smaller scale distributed programming problems. That said, I believe it succeeds at what it does like no other library I have ever seen.
As a final comment, more of a correction, Starfish is a small wrapper built upon Rinda, which is a small wrapper built upon DRb. I would like to thank Matz for making a language like Ruby and Masatoshi Seki for writing DRb (originally in less than 90 lines of code), it is a joy to stand on the shoulder of giants and write such useful utilities like Starfish as a small wrapper.
9:34 PM, August 18, 2006
"MapReduce feels much less like an API and more like a layout, a template that you fill in." it is indeed an occurrence of the "template method" design pattern...
3:39 AM, August 19, 2006
A key feature of Google's MapReduce
is that it's built on top of a batch
system to provide fault tolerance.
So that if a worker node fails
during execution, its subtask will
be transparently reassigned to another node. I haven't looked at the code - does your solution provide fault tolerance? Without it, I doubt the solution would be very practical (but the fact that it's in Ruby is cool!)
I work with Condor and I myself have
recently been thinking about implementing a "poor man's" MapReduce in Python or Ruby on top
of Condor.
7:07 AM, August 19, 2006
It currently does not support fault tolerance, but it will shortly, fault tolerance is easy to add to Starfish the way that I programmed it.
11:26 AM, August 19, 2006
Looks interesting. I posted a few comments on the project page regarding ways to make it more Windows friendly. :)
- Dan
9:41 PM, August 19, 2006
it seems to be a map only, no reduce solution
9:48 PM, August 19, 2006
This is quite misleading:
"I am very happy to announce that Google's MapReduce is now available for Ruby"
Furthermore, the class is named MapReduce.
BUT it's not MapReduce, and it's certainly not "Google's" either.
Yes, it is missing reduce, and there's no point in trying to refute that. MapReduce is NOT simply a call to inject, the same way the stuff you wrote is not "simply a call to #each".
Starfish seems fairly useful on its own; there's no need for you to publicize it (indirect- and somewhat unfortunately) as "Google's MapReduce".
12:02 PM, August 20, 2006
You are entitled to have your anonymous opinion and I am entitled to mine. There are actually ways to do the reduce function in Starfish which I will go into more detail in soon.
1:09 PM, August 20, 2006
That's a great API, indeed! I'd like we have something like that on other languages, maybe in a near future. But, so far, to have something like that on Ruby is great for me.
6:54 AM, August 21, 2006
It's not really MapReduce, but I like your Starfish library. I write about my own MapReduce at my blog. Maybe we can collaborate!
10:50 AM, August 21, 2006
I would love to collaborate, let's see where we can go with this.
11:00 AM, August 21, 2006
Lucas, your library sounds very interesting to. I guess I'm in your target market since I have not played with distributed programming and I have a project coming that would need it. Could you elaborate some more on a n example of how it would be used?
Thanks,
Adrian Madrid
12:18 PM, August 21, 2006
Lucas, I am might impressed with your work thus far. I look forward to seeing the fault tolerance implemented.
Most distributed frameworks are needlessly complex; please stick to your guns and keep the core simple.
Thanks again for your contribution!
Jim
10:05 PM, August 22, 2006
when installing the gem i've got
lib/starfish.rb:179:27: Couldn't find RingFinger. Assuming it's a module
ruby 1.8.4 on tiger
6:05 AM, September 01, 2006
That is nothing to worry about, just a warning.
11:35 AM, September 01, 2006
Starfish doesn't seem to work in Windows.
6:58 AM, October 20, 2006
The examples here: don't show this technology using multiple machines. How easy is it to setup in a distributed environment? It's looking great btw!
12:44 PM, November 03, 2006
i buy hydrocodone at buy hydrocodone - can't find any cheaper
7:06 AM, January 28, 2007
Like some others have said... This seems like it might be useful in a distributed computing environment for doing big tasks... From the example code, I have seen, this is not Map Reduce in the same sense as the Google Labs paper.
Perhaps it's your choice of example? Would you might posting a complete example code of how you would implement the classic example of term counting presented in Section 2.1 of the original MapReduce paper from Google?
4:20 PM, January 29, 2007
I've tried playing with starfish, one thing that is not clear at all from the examples is how to run a client. I've set up a server hitting a mysql table, and running multiple instances of starfish on a single physical node works great. However, if I simply copy the same code to another node and run starfish concurrently on multiple nodes, I get redundant processing. How do I configure the code to run one server and multiple clients across multiple physical nodes? Thanks.
11:58 AM, January 30, 2007
I'm having trouble getting starfish to work with a class hierarchy implemented as single table inheritance in rails.
Is this something starfish can handle, or does it only work with a single class per table?
thanks.
9:13 PM, June 05, 2007
Old thread but i found this in relation to:
12:48 AM, January 03, 2008
I'm the author of Skynet. This article and the code that Lucas wrote was heavily influential in the development of Skynet. Thanks Lucas!
adam
2:10 PM, January 06, 2008
Lucas, is there a way to remove items from the ActiveRecord source immediately after a client processes it from the map_reduce queue? In your email example, this would be the same as deleting an email after it was sent. Thanks!
8:37 PM, February 09, 2008
hi Lucas,
could you please explain something to show this technology using multiple machines? I want to send many mails once but how can I call 10 clients at a time?
4:43 AM, August 26, 2008 | http://tech.rufy.com/2006/08/mapreduce-for-ruby-ridiculously-easy.html | crawl-002 | refinedweb | 2,571 | 62.07 |
PLOT_PX/XPS: a C Graphic Library Package, Part 2
Part 1 of this article was an introduction to PLOT_XPS, a graphic library that lets you generate PostScript files from your X applications. Here, in part 2, we look at what you can actually do with the library. The drawing functions of PLOT_XPS allow users to draw lines or write text in a screen window, a PS file or both.
PLOT_XPS draws lines of any color or width. Three predefined gray pens are available (black, dark gray and light gray). You can use the command ps_pen() to switch between them easily, but the function ps_gray() can change the default gray shade. The ps_rgb(), ps_hls() and ps_cymk() functions change the default pen color if you want something other than gray. The default line width can be modified using ps_line_width(), giving the width in picas or fractions of picas (PS units corresponding to 1/72th inch or 0.35 mm). All coordinates are stored with one digit after the decimal point, leading to a precision of 0.035 mm. This is better definition then the current 600 dpi (corresponding to 0.042 mm per dot) found on high quality laser printers. Once the default grey or the color and the line width are selected, all subsequent graphics and texts will use it.
Polylines are drawn using ps_polyline(), with x and y coordinates in two separate arrays. Complex polygonal surfaces can be drawn using ps_closed_curve(). Its only difference from the polyline drawing is the curve closing and the possibility to fill it the shape and contour it. Simple empty of filled circles, arcs or ellipses are created using the appropriate function, as well as rectangular frames. The following small program traces two sets of circles and ellipses, of different grey shades:
#include <stdio.h> #include <plot_xps.h> main() { int j; ps_iniplot(0,"cercle.ps",0,0,0.,0.,1.,""); ps_origin(7.,5.,0.,0.) ; /* go 7 cm right and 5 cm up */ /* circles drawing */ ps_disk(.25,0.); /* draws a disk */ for(j = 0; j < 4; j++) { ps_circle((float)j); /* draws 4 circles */ ps_movea(0.,2.); /* go 2 cm up */ } /* drawing of ellipses */ ps_ellip_disk(.5,.25,.6); /* draws a grey ellipse */ for(j = 0; j < 4; j++) /* and 4 ellipses */ { ps_ellipse((float)j,(float)j/2.); } ps_endplot('f'); /* keep the file */ } /* main */
The output of this program is shown in Figure 1.
Higher level functions are devoted to complex graphs. ps_ticked_axes, for example, draws a x-y reference with two ticked axes. The axes are drawn from the current position, X axis first. Thus, the given minimum value always is considered as being at the current position. When the tick marks are not provided from the minimum value of the axes, this minimum value is the axis beginning. This allows users to draw graphs slightly shifted from the axes. In addition, a frame can be drawn around the graph that appears to be drawn inside a rectangle, with the lower and left sides ticked. The ticked marks are automatically computed to place small ticks every 1/10 of a unit, medium ticks at 1/2 unit multiples and large ticks at 1 unit multiples.
Figures, then. are annexed to the large ticks. The axes can cross at values other than 0.,0., indicated in user units. In addition, the ticked part can be shorter than the axis itself. Figures annexed to large ticks can be formatted using a standard C printf format, which defaults to "%.2f".
A previous call to ps_font() allows users to choose the font of the legends. Figure 2 shows an example of a rotated graph, where the ticked axes have their origins at -1, -1 and cross 5 mm below their origin. This lets the curves shift slightly from their axes. Related functions ps_x_axis and ps_y_axis do the same thing, but only in one direction, x or y. They always begin at the current position.
ps_histo draws the histogram of values stored in a given array of integers. A flag indicates if statistics must be computed and written on the drawing. In this case, the mathematic library must be loaded when linking the task. According to the directions in the flag, some statistics are computed and drawn on the axis, including mean, standard deviation and mean number of events.
PLOT_XPS writes text, using the existing current gray or color ink, with the current font. Text can be placed anywhere on the drawing board with the needed slanting, the needed size and the needed rotation. The character sizes are always given in centimeters. All the local printer available PS fonts can be used. Nevertheless, if special fonts are needed, it is necessary to indicate in the plot_xps.fonts file the name of the corresponding X font. You then need to recompile and rebuild the PLOT_XPS library. A large collection of text- or value-writing functions are available, from the simplest ps_write("string"), which uses the default font and size, to the most complex ps_chars(), which writes a string of a given size using a relative or absolute coordinate value in user space. Default font and size are chosen using ps_font() and ps_size() respectively, and the color is the current color. Note that X does not text to be placed in any direction other horizontal and left to right or right to left. PLOT_XPS, however, allows users to write in any direction, because it reproduces PS behavior on the screen.
PLOT_XPS avoids the tedious computations necessary when 3-D drawings are needed. The user defines only the observation point of the space where the drawing board projection is performed. A specialized function then computes this projection from the data coordinates in the 3-D space. The following source code draws 27 cubes, with 1 cm sides, arranged as a 3x3x3 cubic matrix. The corresponding PS file output is shown in Figure 3.
#include <stdio.h> #include <math.h> #include <plot_xps.h> main() { int i, j, k; ps_iniplot(NULL,"cubes.ps", /* open a file cubes.ps and a window */ 10,10, /* called my_window located at 10,10 on */ 21,.29.7, /* the screen, with an A4 sheet size, */ .5, /* scaled at half size, without previous */ "My_window"); /* display open (NULL arg. in position 1 */ ps_cms(); /* work in centimeters */ ps_origin(7.,7.,0.,0.); /* go to x=7cm, Y=7cm, * and set here the new * origin */ /* * Set up the 3D orientation and perspective */ ps_3Dsetup(10.,10.,10., /* length of the 3 axes */ 0.,10., /* min max of x user values */ 0.,10., /* min max of y user values */ 0.,10., /* min max of z user values */ M_PI/4.,M_PI/3., /* angle and phi */ 15.,10.); /* distances ref-screen, eye-screen */ /* * Draws the 27 cubes using 3 nested for loops */ for (k = 0 ; k < 3 ;k++) for (j = 0 ; j < 3 ;j++) for ( i=0;i < 3;i++) ps_3Dbar(2.*(float)(i)+1., /* [xyz] cordinates */ 2.*(float)(j)+1., /* of the */ 2.*(float)(k)+1., /* origine of the bar */ 1.,1.,1., /* 3 side lengths */ 1); /* draws an outline */ ps_endplot('s'); /* spools and keeps the PS file*/ }/* end of main */
The PLOT_XPS library is written in fully prototyped ANSI C language. Sources are distributed among eight different files: plot_xps.h (the header file), plot_xps.fonts (the list of available fonts), plot0_xps.c, plot1_xps.c, plot2_xps.c, plot3_xps.c, plot3d_xps.c and plotx_xps.c (the function sources). Each source file includes the man page formatted for get_tex, a public domain program that extracts LaTeX files from a prepared source file (get_tex is included in the distribution).
The plot_xps.h, the header file, should be stored in the default system include directory. This file must be included in each program that uses the PLOT_XPS library. The header file defines all the global variables shared by the functions and the user program, as well as the symbolic constant and the function prototypes.
The plot0_xps.c file contains all the lowest level functions. These are the only functions that actually write in the PS file. They are not documented in the manual, because they can be called only by the other PLOT_XPS functions.
Below are descriptions of the functions that transform user scales or centimeters into PS units. Also described are the functions that compute rotations, change origins, write texts and so on.
plot1_xps.c contain all the functions for initializing and closing the entire system--initialization of the system, first window opening if in PLOT_XPS, closing and spooling the files (or not, according to the arguments), etc. All font selection functions are collected in these files as well. Scale selection, origin translation and settings are in the file, along with rectangle, circle, arc, disk and ellipse drawing functions.
The plot2_xps.c file contain all the functions that control pen movements, text writing, line and color selection, dot selection and so on. Namely, the functions that let users make simple drawings, line after line, are contained here.
The plot3_xps.c file contains all the functions that allow high level drawing using one function call. Ticked axis drawing, histograms, polylines, curves, closed curves, bezier curves and function are stored in these files.
The plot3d_xps.c file contain all the functions to create 3-D drawings, from the 3-D axes up to the 3-D projection of any curve or dot collection. If these functions are used, it is necessary to link the program with the math library.
The plotx_xps.c file contains all the X functions for writing in an X window. In fact, all the X functions are collected in this file. Some are private and cannot be called by the user, mainly because they are static and only in the name space of the PLOT_XPS functions. They represent the lowest level for X library access. The plot0_xps functions use these functions to write in the windows as well as in the PS files. The other X-related functions are callable and documented, and they mainly concern the opening, choosing and closing of new windows (the first window is opened when initiating the whole system). PLOT_XPS only uses the basic Xlib and, thus, does not rely on any X toolkit or X-specific widgets. DEC, Athena or Motif toolkits are not necessary to use PLOT_XPS, giving the user independent status.
The total source code for PLOT_XPS is approximately 9,000 lines of C. PLOT_XPS was compiled and tested on UNIX systems (Linux, Ultrix, OSF, Digital Unix, Tru64, AIX, SunOS and Solaris) and on VMS and Open VMS systems.
A second library, called PLOT_PS, also is available for those not interested in the manipulation of several PS files or in X system access. PLOT_PS proposes exactly the same graphic routines, but it does not provide the functions specific to window management. All the function calls are exactly the same for all routines, except for two--ps_iniplot and ps_endplot--that don't need references to Displays. Nevertheless, most of the function code is completely different.
On an ASCII terminal without an X11 environment, a C program will be linked using PLOT_PS like this:
cc -o my_prog my_prog.c -lplot_ps -lm
The Makefile should look like:
LIBS = -lplot_ps -lm cc -o my_program my_program.c $(LIBS)
PLOT_PS represents 5,400 lines of C and is distributed among seven different files: plot_ps.h (the header file), plot0_ps.c, plot1_ps.c, plot2_ps.c, plot3_ps.c, plot3d_ps.c and plotcol_ps.c. The last file contains all the functions related to color processing.
We have used PLOT_PS since 1985 in applications for information analysis in neuroscience and computational biology. As of this writing, it is at version 6.4. The X version, PLOT_XPS, was developed in 1991. PLOT_PS and PLOT_XPS are still used to produce our working documents, as well as most of the figures for our research papers.
Parts of these libraries were developed by three of my former students. Jean-Noël Albert was the developer of a library for a Benson plotter, from which I later wrote the PLOT_PS library. Sylvain Hanneton wrote a large number of high level functions, and Eric Boussard wrote the X11 implementation of the PS functions (the plotx_xps.c module). All are warmly acknowledged for their contribution. The configure wraparound and some bug fixes were made by Bastien Chevreux.
PLOT_PS and PLOT_XPS were compiled and tested on several UNIX systems (Linux, Ultrix, OSF, Digital Unix, Tru64, AIX, SunOS and Solaris), on VMS and Open VMS systems and on MS/DOS. Both libraries are distributed under the LGPL with the source code. They are regrouped in a tarball file, plot_psxps-6.4.1.tar.gz, which is available on SourceForge. A configure, make and make install setup is provided, and the installation is completely automatic. For VMS users, a DCL command file is included, as is a MS-DOS batch file for Windows users. Two full manuals are supplied (57 pages for PLOT_PS, 88 pages for PLOT_XPS), in TeX, PS and HTML. A CVS site is provided on SourceForge for those who want to contribute and add more functions.
Jean-François Vibert is an MD and neuroscientist who develops programs for his research needs in the field of computational neurosciences. He's been the co-chairman of DECUS France for 15 years, and he released many C and UNIX programs in the public domain through the DECUS library. He teaches C programming to students in biomathematics at the School of Medicine Saint-Antoine, in Paris. | https://www.linuxjournal.com/article/6397 | CC-MAIN-2020-40 | refinedweb | 2,233 | 65.22 |
please teach us available sensor data
Under the condition firmware Version48.18 is applied to CoDrone,
which sensor data are available?
Although I request sensor data using Library's API such as Request_ImuRawAndAngle(),
these sensor data are not send back from CoDrone to Controller.
-Temperature
-Pressure
-ImuRawAndAngl
-IrMessage
-TrimAll
-GyroBias
Only Attitude is available.
If request Attitude data, CoDrone send back it's actual Attitude data.
Based on CoDrone-LINK_05_28-1.pdf document,
could you teach us available sensors?
I've confused to debug software with reading CoDrone-LINK_05_28-1.pdf document.
As soon as I can, I want to know above information due to our education schedule.
Thank you in advance to cooperate with us.
- robolink_wes last edited by
@dracen Apologies for the confusion. The library update we're working on for mid to late March will be able to read out most of the sensor data you listed. We're cleaning up the library and working on a more clear and thorough documentation so that it will be much clearer which functions are available.
If you're able to share, what is your education schedule, just so we're aware?
I did understand that library will be updated and most of sensor data is going to be available.
To tell the truth, at beginning of March, we will hold the result presentation of programming using CoDrone.
I wish I had made it in time.
Are there things what I can do to get sensor data?
I have no choice but wait library update?
- robolink_wes last edited by
Please reach out to us at support@robolink.com, we should be able to schedule some help with you to make a workaround solution before the library update is ready. @arnold_robolink will be checking that e-mail.
- robolink_arnold administrators last edited by robolink_arnold
Hello @dracen the easiest way to pull information of the CoDrone aside from using snap, is with the python libraries. The setup for CoDrone with python does not use the Arduino compatible remote. We are still working on making the tutorials for using and installing python, but I can share with you an example of how you would be able to request data.
from CoDrone.codrone import * #create these to store variables globally rollAngle =0 yawAngle =0 pitchAngle =0 def eventUpdateAttitude(data): global rollAngle, pitchAngle, yawAngle rollAngle =data.roll pitchAngle = data.pitch yawAngle = data.yaw #creates drone object drone = CoDrone(True, False, False, False, False) drone.connect() #set the event handler drone.setEventHandler(DataType.Imu, eventUpdateAttitude) while(drone.isConnected()): #request for the angle data drone.sendRequest(DataType.Imu) sleep(0.05)#make sure to have a delay print("Roll:",rollAngle, " Yaw:", yawAngle," Pitch:",pitchAngle) | http://community.robolink.com/topic/49/please-teach-us-available-sensor-data/?page=1 | CC-MAIN-2019-47 | refinedweb | 446 | 67.35 |
Mastering MEAN
Introducing the MEAN stack
Develop modern, full-stack, twenty-first-century web projects from end-to-end
Content series:
This content is part # of # in the series: Mastering MEAN
This content is part of the series:Mastering MEAN
Stay tuned for additional content in this series.. These technologies weren't written to work together. They are discrete projects that one ambitious software engineer — and then another, and then another — cobbled together. Since then, we've witnessed a Cambrian explosion of web stacks. Every modern programming language seems to have a corresponding web framework (or two) that preassembles a motley crew of technologies to make it quick and easy to bootstrap a new website.
An emerging stack that's gaining much attention and excitement in the web community is the MEAN stack: MongoDB, Express, AngularJS, Node.js. The MEAN stack represents a thoroughly modern approach to web development: one in which a single language (JavaScript) runs on every tier of your application, from client to server to persistence. This series demonstrates what a MEAN web development project looks like end-to-end, going beyond simple syntax. This initial installment gets you started with an in-depth, hands-on introduction to the stack's component technologies, including installation and setup. See Download to get the sample code.
“Every website you visit is the product of a unique mixture of libraries, languages, and web frameworks.”
From LAMP to MEAN
MEAN is more than a simple rearrangement of acronym letters and technology upgrades. Switching the base platform from an OS (Linux) to a JavaScript runtime (Node.js) brings OS independence: Node.js runs as well on Windows® and OS X as it does on Linux.
Node.js also replaces Apache in the LAMP stack. But Node.js is far more than a simple web server. In fact, you don't deploy your finished application to a stand-alone web server; instead, the web server is included in your application and installed automagically in the MEAN stack. The deployment process is dramatically simpler as a result, because the required version of the web server is explicitly defined along with the rest of your runtime dependencies.
The move from a traditional database such as MySQL to a NoSQL, schemaless, document-oriented persistence store such as MongoDB represents a fundamental shift in persistence strategy. You'll spend less time writing SQL and more time writing map/reduce functions in JavaScript. You'll also cut out huge swaths of transformation logic, because MongoDB emits JavaScript Object Notation (JSON) natively. Consequently, writing RESTful web services is easier than ever.
But the biggest shift from LAMP to MEAN is the move from traditional server-side page generation to a client-side single-page application (SPA) orientation. With Express, you can still handle server-side routing and page generation, but the emphasis is now on client-side views, courtesy of AngularJS. This change involves more than simply shifting your Model-View-Controller (MVC) artifacts from the server to the client. You'll also be taking the leap from a synchronous mentality to one that is fundamentally event-driven and asynchronous in nature. And perhaps most important, you'll move from a page-centric view of your application to one that is component-oriented.
The MEAN stack isn't mobile-centric — AngularJS runs equally well on desktops and laptops, smartphones and tablets, and even smart TVs — but it doesn't treat mobile devices as second-class citizens. And testing is no longer an afterthought: With world-class testing frameworks such as MochaJS, JasmineJS, and KarmaJS, you can write thorough, comprehensive test suites for your MEAN app.
Ready to get MEAN?
Installing Node.js
You need a working installation of Node.js to work on the sample application in this series, so now is the time to install Node if you haven't already.
If you are on a UNIX®-like OS (Linux, Mac OS X, and so on), I recommend that you use Node Version Manager (NVM). (Otherwise, click Install on the Node.js home page to download the installer for your OS, and accept the defaults.) With NVM, you can easily download Node.js and switch among various versions from the command line. This helps me seamlessly move from one version of Node.js to the next as I move from one client project to the next.
After NVM is installed, type
nvm ls-remote to see which
versions of Node.js are available for installation, as shown in Listing 1.
Using NVM to list available versions of Node.js
$ nvm ls-remote v0.10.20 v0.10.21 v0.10.22 v0.10.23 v0.10.24 v0.10.25 v0.10.26 v0.10.27 v0.10.28
Typing
nvm ls shows which versions of Node.js you already have
installed locally, and which version is currently in use.
At the time of writing, the Node website suggests that v0.10.28 is the most
recent stable version. Type
nvm install v0.10.28 to install
it locally.
After you install Node.js (either via NVM or the platform-specific
installer), type
node --version to verify that you are using
the current version:
$ node --version v0.10.28
What is Node.js?
Node.js is a headless JavaScript runtime. It is literally the same JavaScript engine (named V8) that runs inside of Google Chrome, except that with Node.js, you can run JavaScript from the command line instead of in your browser.
I've had students scoff at the idea of running JavaScript from the command line: "If there isn't HTML to manipulate, what is JavaScript good for?" JavaScript was introduced to the world in a browser (Netscape Navigator 2.0), so those naysayers can be forgiven for their shortsightedness and naiveté.
In fact, JavaScript the programming language has no native capabilities for Document Object Model (DOM) manipulation or for making Ajax requests. Browsers provide DOM APIs so that you can do that sort of thing with JavaScript, but outside of the browser JavaScript loses those capabilities.
Here's an example. Open a JavaScript console in your browser (see Accessing your browser's developer tools). Type
navigator.appName. After you get a response, type
navigator.appVersion. Your results are similar to those in
Figure 1.
Using the JavaScript
navigator object in
a web browser
In Figure 1, the response to
navigator.appName is
Netscape, and the response to
navigator.appVersion is the cryptic user agent string that
seasoned web developers have come to know and either love or loathe. In
Figure 1 (from Chrome on OS X), the string is
5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36.
Now, create a file named test.js. Type the same commands in the file,
wrapping each in a
console.log() call:
console.log(navigator.appName); console.log(navigator.appVersion);
Save the file and type
node test.js to run it, as shown in
Listing 2.
Viewing the
navigator is not defined error in
Node.js
$ node test.js /test.js:1 ion (exports, require, module, __filename, __dirname) { console.log(navigator. ^ ReferenceError: navigator is not defined at Object.<anonymous> (/test.js:1:75)
As you can see,
navigator is available to you in the browser
but not from Node.js. (Sorry for making your first Node.js script fail on
you spectacularly, but I want to make sure that you are convinced that
running JavaScript in the browser is different from running it in
Node.js.)
According to the stack trace, the proper
Module isn't loaded.
(Modules are another major difference between running JavaScript in the
browser and running it in Node.js. More on modules in a moment.) To get
similar information from Node.js, change the contents of test.js to:
console.log(process.versions) console.log(process.arch) console.log(process.platform)
Type
node test.js again, and you'll see output similar that in
Listing 3.
Using the process module in Node.js
$ node test.js { http_parser: '1.0', node: '0.10.28', v8: '3.14.5.9', ares: '1.9.0-DEV', uv: '0.10.27', zlib: '1.2.3', modules: '11', openssl: '1.0.1g' } x64 darwin
Now that you've successfully run your first script in Node.js, it's time to tackle the next major concept: modules.
What are modules?
You can create single-purpose functions in JavaScript, but — unlike
in Java, Ruby, or Perl — you have no way to bundle multiple
functions into a cohesive module or "package" that can be imported and
exported. Of course, you can include any JavaScript source file by using
the
<script> element, but that time-honored method
falls short of a proper module declaration in two key ways.
First, any JavaScript you include by using the
<script>
element is loaded into the global namespace. With modules, you can sandbox
the imported functionality in a locally namespaced variable. Second, and
more crucially, you can explicitly declare your dependencies with modules,
whereas with the
<script> element, you can't. As a
result, importing Module A transitively imports dependent Modules B and C
also. As your application gains complexity, transitive dependency
management quickly becomes a vital requirement.
Modules are a hotly anticipated feature of the next major version of JavaScript (ECMAScript 6), but until that version is widely adopted, Node.js is using its own version of modules based on the CommonJS specification.
You include a CommonJS module in your script by using the
require keyword. For example, Listing 4 is a slightly
modified version of the Hello World script you can find on the Node.js
homepage. Create a file named example.js and copy the code from Listing 4
into it.
Hello World in Node.js
var http = require('http'); var port = 9090; http.createServer(responseHandler).listen(port); console.log('Server running at:' + port + '/'); function responseHandler(req, res){ res.writeHead(200, {'Content-Type': 'text/html'}); res.end('<html><body><h1>Hello World</h1></body></html>'); }
Type
node example.js to launch your new web server, and visit in your web
browser.
Look at the first two lines in Listing 4. You've most likely written simple
statements like
var port = 9090; hundreds (or thousands) of
times. This statement defines a variable named
port and
assigns the number
9090 to it. Importing a CommonJS module as
you do in the first line (
var http = require('http');) is
really no different. It brings in the
http module and assigns
it to a local variable. All of the corresponding modules that
http relies on are
required in also.
The subsequent lines of example.js:
- Create a new HTTP server.
- Assign a function to handle the responses.
- Start listening on the specified port for incoming HTTP requests.
So, in a handful of lines of JavaScript, you created a simple web server in Node.js. As you'll learn in future tutorials in this series, Express expands on this simple example to handle more-complex routes and serve up both static and dynamically generated resources.
The
http module is a standard part of any Node.js
installation. Other standard Node.js modules enable file I/O, read
command-line input from the user, handle lower-level TCP and UDP requests,
and much more. Visit the Modules section of the Node.js documentation to see the full list
of standard modules and read about their capabilities.
Although the list of included modules is impressive, it pales in comparison to the list of available third-party modules. To gain access to them, you need to familiarize yourself with another command-line utility: NPM.
What is NPM?
NPM is short for Node Packaged Modules. To see a list of more than 75,000
publicly available third-party Node modules, visit the
NPM website. On the site,
yo module. Figure 2 shows the results.
Details of the
yo module
The result page gives you a brief description of the module ("CLI tool for scaffolding out Yeoman projects"); how many times it was downloaded in the past day, week, and month; who wrote it; which other modules (if any) that it depends on; and much more. Most important, the result page gives you the command-line syntax for installing the module.
To get similar information about the
yo module from the
command line, type
npm info yo. (If you didn't already know
the official name of the module, you could type
npm search yo
to search for any module whose name contains the string
yo.)
The
npm info command displays the contents of the module's
package.json file.
Understanding package.json
Every Node.js module must have a well-formed package.json file
associated with it, so it's worth getting familiar with the contents of
this file. Listings 5, 6, and 7 show the contents of package.json for
yo, divided into three parts.
The first elements, shown in Listing 5, are typically
name,
description, and a JSON array of available
versions.
package.json, Part 1
$ npm info yo { name: 'yo', description: 'CLI tool for scaffolding out Yeoman projects', 'dist-tags': { latest: '1.1.2' }, versions: [ '1.0.0', '1.1.0', '1.1.1', '1.1.2' ],
To install the latest version of a module, you type
npm install package . Typing
npm install package@version installs a
specific version.
Next, as shown in Listing 6, are authors, maintainers, and the GitHub repository where you can find the source directly.
package.json, Part 2
author: 'Chrome Developer Relations', repository: { type: 'git', url: 'git://github.com/yeoman/yo' }, homepage: '', keywords: [ 'front-end', 'development', 'dev', 'build', 'web', 'tool', 'cli', 'scaffold', 'stack' ],
In this case, you also find a link to the project's homepage and a JSON array of associated keywords. Not all of these fields are present in every package.json file, but users rarely complain about having too much metadata associated with a project.
Finally, you see a list of dependencies with explicit version numbers, as in Listing 7. These version numbers follow a common pattern of major version.minor version.patch version called SemVer (Semantic Versioning).
package.json, Part 3
engines: { node: '>=0.8.0', npm: '>=1.2.10' }, dependencies: { 'yeoman-generator': '~0.16.0', nopt: '~2.1.1', lodash: '~2.4.1', 'update-notifier': '~0.1.3', insight: '~0.3.0', 'sudo-block': '~0.3.0', async: '~0.2.9', open: '0.0.4', chalk: '~0.4.0', findup: '~0.1.3', shelljs: '~0.2.6' }, peerDependencies: { 'grunt-cli': '~0.1.7', bower: '>=0.9.0' }, devDependencies: { grunt: '~0.4.2', mockery: '~1.4.0', 'grunt-contrib-jshint': '~0.8.0', 'grunt-contrib-watch': '~0.5.3', 'grunt-mocha-test': '~0.8.1' },
This package.json file indicates that it must be installed on a Node.js
instance of version 0.8.0 or higher. If you try to
npm install it on an unsupported version, the installation
fails.
Beyond the platform requirement, this package.json file also provides several lists of dependencies:
- The
dependenciesblock lists runtime dependencies.
- The
devDependenciesblock lists modules that are required during the development process.
- The
peerDependenciesblock enables the author to define a "peer" relationship between projects. This capability is often used to specify the relationship between a base project and its plugins, but in this case, it identifies the other two projects (Grunt and Bower) that comprise the Yeoman project along with Yo.
If you type
npm install without a specific module name,
npm looks in the current directory for a package.json file
and installs all dependencies listed in the three blocks I just discussed.
The next step toward getting a working MEAN stack installed is to install Yeoman and the corresponding Yeoman-MEAN generator.
Installing Yeoman
As a Java developer, I couldn't imagine starting a new project without a build system such as Ant or Maven. Similarly, Groovy and Grails developers rely on Gant (a Groovy implementation of Ant) or Gradle. These tools can scaffold out a new directory structure, download dependencies on the fly, and prepare your project for distribution.
In the pure web development world, Yeoman fills this need. Yeoman is a
collection of three Node.js and pure JavaScript tools for scaffolding
(Yo), managing client-side dependencies (Bower), and preparing your
project for distribution (Grunt). As you know from examining Listing 7, installing Yo brings its peers Grunt
and Bower along for the ride, thanks to the
peerDependencies
block in package.json.
Normally, you'd type
npm install yo --save to install the
yo module and update the
dependencies block in
your package.json. (
npm install yo --save-dev updates the
devDependencies block.) But the three peer modules of Yeoman
aren't really project-specific — they are command-line utilities,
not runtime dependencies. To install a NPM package globally, you add the
-g flag to the
install command.
Install Yeoman on your system:
npm install -g yo
After the package is installed, type
yo --version to verify
that it's up and running.
With Yeoman and all of the rest of the infrastructure in place, you're ready to install the MEAN stack.
Installing MeanJS
You could meticulously install each part of the MEAN stack by hand. Thankfully, Yeoman offers an easier path via its generators.
A Yeoman generator is the easiest way to bootstrap a new web project. The generator pulls in the base packages and all of their dependencies. And it typically includes a working build script with all of the associated plugins. Many times, the generator also includes a sample application, complete with tests.
There are over 1,000 Yeoman generators available. Several of them are written and maintained by the Yeoman core developers — look for The Yeoman Team in the Author column. But the majority of the generators are written by the community.
The community generator you'll use to bootstrap your first MEAN app is named, not surprisingly, MEAN.JS.
On the MEAN.JS home page, click the Yo Generator menu option or go directly to the Generator page, part of which is shown in Figure 3.
The MEAN.JS Yeoman generator
The page's instructions tell you to install Yeoman first, which you've already done. The next step is to install the MEAN.JS generator globally:
npm install -g generator-meanjs
When the generator is in place, you're ready to create your first MEAN app.
Create a directory named test,
cd into it, and type
yo meanjs to generate the application. Answer the last two
questions as shown in Listing 8. (You can provide your own answers for the
first four.)
Using the MEAN.JS Yeoman generator
$ mkdir test $ cd test $ yo meanjs _-----_ | | |--(o)--| .--------------------------. `---------� | Welcome to Yeoman, | ( _�U`_ ) | ladies and gentlemen! | /___A___\ '__________________________' | ~ | __'.___.'__ � ` |� � Y ` You're using the official MEAN.JS generator. [?] What would you like to call your application? Test [?] How would you describe your application? Full-Stack JavaScript with MongoDB, Express, AngularJS, and Node.js [?] How would you describe your application in comma separated key words? MongoDB, Express, AngularJS, Node.js [?] What is your company/author name? Scott Davis [?] Would you like to generate the article example CRUD module? Yes [?] Which AngularJS modules would you like to include? ngCookies, ngAnimate, ngTouch, ngSanitize
After you answer the final question, you see a flurry of activity as NPM downloads all of your server-side dependencies (including Express). After NPM is done, you see Bower download all of your client-side dependencies (including AngularJS, Bootstrap, and jQuery).
At this point, you have the EAN stack (Express, AngularJS, and Node.js)
installed — all you are missing is the M (MongoDB). If you typed
grunt right now to start up your application without MongoDB
installed, you'd see an error message similar to the one in Listing 9.
Trying to start MeanJS without MongoDB
events.js:72 throw er; // Unhandled 'error' event ^ Error: failed to connect to [localhost:27017] at null.<anonymous> (/test/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:546:74) [nodemon] app crashed - waiting for file changes before starting...
If you started the app and see this error message, press Ctrl+C to stop the app.
Now you'll get MongoDB installed so that you can take your new MEAN app out for a ride.
Installing MongoDB
MongoDB is a NoSQL persistence store. It's not written in JavaScript, nor is it an NPM package. You must install it separately for your MEAN stack to be complete and functional.
Visit the MongoDB home page, download the platform-specific installer, and accept all of the defaults as you install MongoDB.
When the installation is complete, type
mongod to start the
MongoDB daemon.
The MeanJS Yeoman generator already installed a MongoDB client module called Mongoose; you can check your package.json file to verify this. I'll cover MongoDB and Mongoose in detail in a later installment.
With MongoDB installed and running, you are finally ready to launch your MEAN app and look around.
Launching the MEAN application
To start the newly installed MEAN application, make sure that you are in
the test directory you created before running the MeanJS Yeoman generator.
When you type
grunt, you should see output similar to that
shown in Listing 10.
Starting the MEAN.JS app
$ grunt Running "jshint:all" (jshint) task >> 46 files lint free. Running "csslint:all" (csslint) task >> 2 files lint free. Running "concurrent:default" (concurrent) task Running "watch" task Waiting... Running "nodemon:dev" (nodemon) task [nodemon] v1.0.20 [nodemon] to restart at any time, enter `rs` [nodemon] watching: app/views/**/*.* gruntfile.js server.js config/**/*.js app/**/*.js [nodemon] starting `node --debug server.js` debugger listening on port 5858 NODE_ENV is not defined! Using default development environment MEAN.JS application started on port 3000
The
jshint
and
csslint modules (both installed by the generator)
ensure that the source code is syntactically and stylistically correct.
The
nodemon package watches the file system for changes
to source code and automatically restarts the server when it detects any
— a huge boon for developer velocity as you make rapid, frequent
changes to your codebase. (The
nodemon package only runs
during the development phase; for production changes, you must redeploy
your application and restart Node.js.)
As the console output suggests, visit and take your new MEAN app out for a spin.
Figure 4 shows the MEAN.JS sample application home page.
The MEAN.JS sample application home page
Click Signup in the menu bar to create a new user account. For now, fill in all of the fields on the Sign-up page (shown in Figure 5) and click Sign up. You'll enable OAuth logins via Facebook, Twitter, and so on in a later tutorial.
The MEAN.JS sample application Sign-up page
Now you have a set of user credentials stored in your local MongoDB instance and can begin creating new articles. Click the Articles menu option (which doesn't appear until you've logged in), and create a few sample articles. Figure 6 shows the Articles page.
The MeanJS article page
You have christened your first MEAN application. Welcome to the party!
Conclusion
You accomplished quite a bit in this tutorial. You installed Node.js and wrote your first Node.js script. You learned about modules and used NPM to install several third-party modules. You installed Yeoman to give yourself a solid web development platform that includes a scaffolding utility (Yo), a build script (Grunt), and a utility to manage client-side dependencies (Bower). You installed the MeanJS Yeoman generator and used it to create your first MEAN application. You installed MongoDB and the Node.js client library Mongoose. And finally, you ran your first MEAN application.
Next time, you'll take a detailed walk through the source code of the sample application so that you can see how all four planets in the MEAN solar system — MongoDB, Express, AngularJS, and Node.js — interact with one another.
Downloadable resources
- PDF of this content
- Sample code (wa-mean1src.zip | 1.38MB)
Related topics
- Build a real-time polls application with Node.js, Express, AngularJS, and MongoDB
- Node.js for Java developers
- getting started with Node.js | https://www.ibm.com/developerworks/opensource/library/wa-mean1/index.html?ca=drs- | CC-MAIN-2018-13 | refinedweb | 4,036 | 59.3 |
rails periodic task
I have a ruby on rails app in which I'm trying to find a way to run some code every few seconds.
I've found lots of info and ideas using cron, or cron-like implementations, but these are only accurate down to the minute, and/or require external tools. I want to kick the task off every 15 seconds or so, and I want it to be entirely self contained within the application (if the app stops, the tasks stop, and no external setup).
This is being used for background generation of cache data. Every few seconds, the task will assemble some data, and then store it in a cache which gets used by all the client requests. The task is pretty slow, so it needs to run in the background and not block client requests.
I'm fairly new to ruby, but have a strong perl background, and the way I'd solve this there would be to create an interval timer & handler which forks, runs the code, and then exits when done. It might be even nicer to just simulate a client request and have the rails controller fork itself. This way I could kick off the task by hitting the URI for it (though since the task will be running every few seconds, I doubt I'll ever need to, but might have future use). Though it would be trivial to just have the controller call whatever method is being called by the periodic task scheduler (once I have one).
Generally speaking, there's no built in way that I know of to create a periodic task within the application. Rails is built on Rack and it expects to receive http requests, do something, and then return. So you just have to manage the periodic task externally yourself.
I think given the frequency that you need to run the task, a decent solution could be just to write yourself a simple rake task that loops forever, and to kick it off at the same time that you start your application, using something like Foreman. Foreman is often used like this to manage starting up/shutting down background workers along with their apps. On production, you may want to use something else to manage the processes, like Monit.
Schedule Tasks Using 'Whenever' Gem- Ruby on Rails, People who set up and maintain software environments use cron to schedule jobs (commands or shell scripts) to run periodically at fixed times, dates, Whether you use ruby for system management or rails for web development, you may encounter periodic tasks, which are triggered continuously according to a certain period of time (1 hour, 2 days…).
I'd suggest the whenever gem
It allows you to specify a schedule like:
every 15.minutes do MyClass.do_stuff end
There's no scheduling cron jobs or monkeying with external services.
Periodic Tasks with sidekiq-cron, Using a third-party add-on, sidekiq-cron, we can create periodic tasks to extend the functionality of sidekiq. rails background processing 4:59. Then Active Elastic Job is the right gem. It provides an adapter for Rails' Active Job framework that allows your application to queue jobs as messages in an Amazon SQS queue. Elastic Beanstalk provides worker environments that automatically pull messages from the queue and transforms them into HTTP requests.
You can either write you own method, something like
class MyWorker def self.work #do you work sleep 15 end end
run it with
rails runner MyWorker.work
There will be a separate process running in the background
Or you can use something like Resque, but that's a different approach. It works like that: something adds a task to the queue, meanwhile a worker is fetching whatever job it is in the queue, and tries to finish it.
So that depends on your own need.
Cron jobs in Rails: A simple guide to ACTUALLY using the , I had the chance to use whenever to schedule a task in Rails, and I'm writing task itself (in my case, sending out batch messages periodically) Redmine periodictask. In some projects there are tasks that need to be assigned on a schedule. After you installed the plugin you can add it as a module to a project that already exists or activate it as default module for new projects. On each project it will add a new tab named "Periodic Task" - just go there to add your tasks.
I know it is an old question. But maybe for someone this answer could be helpful. There is a gem called crono.
Crono is a time-based background job scheduler daemon (just like Cron) for Ruby on Rails..
The awesome thing with crono is that its code is self explained. In order to do a task periodically you can just do:
Crono.perform(YourJob).every 2.days
Maybe you can also do:
Crono.perform(YourJob).every 30.seconds
Anyway you really can do a lot of things. Another example could be:
Crono.perform(TestJob).every 1.week, on: :monday, at: "15:30"
I suggest this gem instead of whenever because whenever uses Unix Cron table which not always is available.
Active Job Basics, Simple In/Out is a Rails app running on Heroku with several background jobs that need to be scheduled to run either hourly, daily, or weekly. In some projects there are tasks that need to be assigned on a schedule. Such as check the ssl registration once per year or run security checks every 3 months. This is the redmine plugin for you if you need such a thing.
Use something like delayed job, and requeue it every so often?
Dev Post: Schedule Recurring Rails Tasks to Run at Any Interval , Thread based scheduler. The most obvious way to schedule a task from within your program is to either loop it forever with a periodic sleep Hi! I'm the maintainer, didn't see this message. I fixed this issue. It should be working ok now (version 3.0.3) Please let me know if something is not working right, directly opening an issue in gihub.
Scheduling tasks in Ruby / Rails, Recurring / Periodic / Scheduled / Cron job extension for Sidekiq Task scheduler that doesn't need to bootstrap your Rails environment every time it executes.
Category: Scheduling, A time-based background job scheduler daemon (just like Cron) for Rails jobs are convenient because you can use one job in both periodic and enqueued ways. lib/tasks/test.rake namespace :crono do desc 'Update all tables' task :hello After you installed the plugin you can add it as a module to a project that already exists or activate it as default module for new projects. On each project it will add a new tab named "Periodic Task" - just go there to add your tasks.
plashchynski/crono: A time-based background job , Cron task is a time-based job scheduler in Unix-like computer operating systems. Cron can be used to schedule jobs to run periodically at fixed With periodic tasks, you can also configure the worker daemon to queue messages based on a cron schedule. Each periodic task can POST to a different path. Enable periodic tasks by including a YAML file in your source code that defines the schedule and path for each task. | http://thetopsites.net/article/50396789.shtml | CC-MAIN-2020-40 | refinedweb | 1,221 | 69.52 |
Microsoft Responds To "Like OS X" Comment
samzenpus posted more than 4 years ago | from the imitation-is-the-greatest-form-of-flattery dept.
(5, Insightful)
sopssa (1498795) | more than 4 years ago | (#30071330)
Random person thinks he knows everything, grows an ego and tells "juicy" stuff to press to boost that said ego while actually knowing nothing.
Nothing to see here. But I suspect lots of Linux/Mac OSX fanatics will be coming in 3.. 2.. 1..
Re:ego (5, Funny)
Anonymous Coward | more than 4 years ago | (#30071388) (5, Insightful)
L4t3r4lu5 (1216702) | more than 4 years ago | (#30071772)
For every Off-topic mod you get, you'll be almost guaranteed one Insightful mod. As long as you're against Jack Thompson. Which I am!
Re:ego (5, Funny)
zmollusc (763634) | more than 4 years ago | (#30071394)
..0
....
OMGBBQ!!!!! Gnome is bettar than both!!!!! and anyway it all comes from PARC work blah blah GEM blah blah Amiga blah
Re:ego (1, Insightful)
OscarGunther (96736) | more than 4 years ago | (#30071484)
Who mod parent a troll?! Have you no sense of humor, sir?
Re:ego (5, Funny)
Mitchell314 (1576581) | more than 4 years ago | (#30071516)
Maybe it's a KDE user who did it.
Re:ego (5, Funny)
Anonymous Coward | more than 4 years ago | (#30071638) (-1, Redundant)
cadeon (977561) | more than 4 years ago | (#30071758)
Please Mod Parent Troll.
Re:ego (0)
Anonymous Coward | more than 4 years ago | (#30071888)
Please Mod Parent Troll.
Re:ego (0, Offtopic)
danbert8 (1024253) | more than 4 years ago | (#30071940)
Why waste the mod points? He's an AC and he's at 0, if you don't like reading shit, raise your threshold.
Re:ego (0, Flamebait)
coinreturn (617535) | more than 4 years ago | (#30071408)
Re:ego (4, Funny)
Jarik C-Bol (894741) | more than 4 years ago | (#30071458) [penny-arcade.com]
Re:ego (4, Funny)
gbjbaanb (229885) | more than 4 years ago | (#30071498)
so did xkcd. [xkcd.com]
Re:ego (5, Insightful)
sitarlo (792966) | more than 4 years ago | (#30071456)
Save face? (4, Insightful)
professorguy (1108737) | more than 4 years ago | (#30071574)
They ain't trying to save face. They are trying to save a lawsuit loss (i.e., money).
Re:Save face? (1)
L4t3r4lu5 (1216702) | more than 4 years ago | (#30071798)
Re:ego (0, Flamebait)
RedK (112790) | more than 4 years ago | (#30071478)
Or you know, this guy just let out the big dirty secret and in an attempt to save face, the "Windows team" puts out an official response that claims the contrary even though at this point it's pretty obvious to anyone with 1 functionning eye, trying to kill the first guy's credibility in order to sweep all of this under the rug.
The end the night by sucking their collective thumb and weeping for their mommies to "make it all go away".
See, anyone can say anything about it. The few people who know the actual truth (the first guy and the Windows team) won't ever tell us the real truth.
Re:ego (1)
gbjbaanb (229885) | more than 4 years ago | (#30071542)
in other news, Microsoft employee says "iPhone is better than WinMobile", cue Microsoft fanbois to criticise employee and distract everyone from the frickin' obvious.
Re:ego (1)
socsoc (1116769) | more than 4 years ago | (#30071790)
iPhone is better than WinMobile
There's nothing new or newsworthy about that statement...
Re:ego (1)
loupgarou21 (597877) | more than 4 years ago | (#30071616)
I'm not so sure that he was really looking to juice his ego. I'm guessing that he probably knew exactly what he was talking about, but his phrasing was very poor. It's not that they were trying to copy Apple with the redesigned UI, they probably did a lot of testing and probably interviewed a lot of computer users about what they do and don't like about the UIs of various operating systems, and probably got a lot of comments, especially from Mac users, about how the average user wants a very simplified user interface where the things they use frequently are easily accessible to the user, and the more complex things, like computer settings are somewhat hidden from the user, harder to get to and accidentally change. So while redesigning the UI, they tried to take that philosophy of a more user-centric UI, not that they were trying to copy the Mac OS interface.
Put aside the ego... (1)
h4rm0ny (722443) | more than 4 years ago | (#30071672)!
Inaccurate, uninformed and soon... (0)
Anonymous Coward | more than 4 years ago | (#30071344)
... unemployed.
Re:Inaccurate, uninformed and soon... (1)
turing_m (1030530) | more than 4 years ago | (#30071390)
sell:nike air max jordan shoes,coach,gucci,handbag (-1, Offtopic)
coolforsale (1677136) | more than 4 years ago | (#30071364)
Something About Bill (0)
Anonymous Coward | more than 4 years ago | (#30071396)
Bill: "STEP INTO MY OFFICE!"
Idiotic Microsoft Employee: "Why?"
Bill: "Cause you're fuckin' fired!"
they've been copying Mac all along... (1)
wvmarle (1070040) | more than 4 years ago | (#30071404)
Re:they've been copying Mac all along... (5, Insightful)
JerryLove (1158461) | more than 4 years ago | (#30071480):they've been copying Mac all along... (1)
Shrike82 (1471633) | more than 4 years ago | (#30071546):they've been copying Mac all along... (1)
Mitchell314 (1576581) | more than 4 years ago | (#30071550)
Re:they've been copying Mac all along... (0)
Anonymous Coward | more than 4 years ago | (#30071628)
If Xerox STAR had never been created, the differences between PCs today would be the clickiness of keyboards and whether or not your display could handle 132-column mode. On the upside, these PCs would STILL be running terminal emulation most of the time. Billions of reboots would have been prevented. Even better, Microsoft's involvement would be limited to a nifty BASIC interpreter, long since obsoleted by other languages. Best of all, mainframes would still be king of the hill and IT would be a great career option. As soon as we can build a time travel device, I propose we go back and eliminate Xerox STAR just to see what happens.
Re:they've been copying Mac all along... (1)
Dolohov (114209) | more than 4 years ago | (#30071656)
More to the point: what on earth is wrong with copying good interface ideas? As a Microsoft stockholder I'd be far more upset if they *didn't* look at Mac OS when designing Windows!
Re:they've been copying Mac all along... (0)
Anonymous Coward | more than 4 years ago | (#30071712)
So Mac copied Xerox Star...
Says the person whose never seen a Xerox Star.
Yes, there are a few similarities, but nothing like Win-Mac.
Re:they've been copying Mac all along... (0)
Anonymous Coward | more than 4 years ago | (#30071858)
Re:they've been copying Mac all along... (1)
digitalhermit (113459) | more than 4 years ago | (#30071868) would the, uh, hi-fi system. And for almost every action I would need to check the junk desk drawer on the bottom left of my screen where I'd find everything else that I needed. Of course, I could start moving things from the drawer to my desktop but in a few days it would be so cluttered that it would be difficult to find anything, especially since the calculator would be the exact same size as my television and my notepad and my journal (that is to say, about 0.75" wide and tall). We might as well have chosen a steering wheel metaphor or a buggy whip metaphor.
Our interfaces seem to border on the ridiculous. On this laptop I'm using right now, there are a dozen extra buttons for media, wi/fi, hibernation, home (not sure what that one does, but it has an image of a house on it). They're all tiny buttons, less than a centimeter square. There are lots of LEDs too. There's no "Check Engine" light though, or a fuel gauge though. But that would be more useful than a hard drive busy light to me.
Why do I have to go to three menus to increase the font size in a document? Hell, I'd like to be able to messy select a line of text and pinch expand the font size. I want to be able to move text around by dragging (some apps can do this). I want consistent behaviour in my web browser as in my document editor. If I want to cut an image from my screen and save it to a file, I shouldn't have to launch two applications to do it (and I don't mean some Alt-PrtScr that saves a bitmap to my desktop but a way to lasso select almost *anything* in a vector format image).
The thing is, we have the hardware power but the interfaces are so clunky that using the power is difficult.
Underwriters (0, Troll)
SgtChaireBourne (457691) | more than 4 years ago | (#30071624)
And in 2003:
And in 2005:
It is truly bizarre that average people allow the shills to make noise promoting such incompetence. Look at their search engine payment bug [softpedia.com] and you are reminded yet again what kind of people they must scrape the bottom of the barrel to get. Not just known-nothings, but fresh-out-of-school ones at that. Sadly that scam has gone on for a generation. What happens if they get into schools or colleges and start posing as staff or faculty??
Re:Underwriters (1)
MetalPhalanx (1044938) | more than 4 years ago | (#30071788)
.
Things not to do if you like your job (5, Insightful)
Random5 (826815) | more than 4 years ago | (#30071410)
Re:Things not to do if you like your job (1)
jDeepbeep (913892) | more than 4 years ago | (#30071612). (1)
DoctorNathaniel (459436) | more than 4 years ago | (#30071636)
Always a classic screw-up.
Re:Things not to do if you like your job (4, Funny)
L4t3r4lu5 (1216702) | more than 4 years ago | (#30071816)
What Apple does right (5, Interesting)
BadAnalogyGuy (945258) | more than 4 years ago | (#30071418) (1)
Shivetya (243324) | more than 4 years ago | (#30071466)
they seem to go the other with iTunes.
I still see no reason for Apple to not allow sizing windows from any corner, let alone hiding/moving the Apple bar at top.
Re:For everything Apple does one way (3, Insightful)
Mitchell314 (1576581) | more than 4 years ago | (#30071560)
Re:What Apple does right (4, Insightful)
Procasinator (1173621) | more than 4 years ago | (#30071482):What Apple does right (2, Informative)
Dupple (1016592) | more than 4 years ago | (#30071548)
Re:What Apple does right (2, Funny)
DarthBart (640519) | more than 4 years ago | (#30071588)
Right click? What is this right click you speak of?
Re:What Apple does right (1)
wolrahnaes (632574) | more than 4 years ago | (#30071894) input, but in both cases they have missed the mark. The "Mighty Mouse" scroll ball was too tiny to be of any use and right-clicking required lifting your left finger off the mouse surface entirely. The new "Magic Mouse" solves the scroll ball issue, but for some reason still requires lifting the left to click with the right.
Not an Apple hater though, this post typed from a Macbook Pro with an Apple aluminum keyboard, but with a Logitech G5 handling the mousing duties. I love the platform, just wish King Jobs would get his head out of his ass regarding the single button thing.
Re:What Apple does right (2, Interesting)
Procasinator (1173621) | more than 4 years ago | (#30071642):What Apple does right (1, Troll)
joh (27088) | more than 4 years ago | (#30071698)
You press Control-F2 and use the cursor keys to get to Some Option.
Re:What Apple does right (3, Informative)
Procasinator (1173621) | more than 4 years ago | (#30071736)
Which is slower, as I mentioned in a reply to another poster who brought this up.
Might not be important to some people, but to me, it's a feature I miss in Mac OS X land.
Re:What Apple does right (1, Informative)
Anonymous Coward | more than 4 years ago | (#30071886)?
Control-F2 to give the menu bar keyboard focus, then use the arrow buttons or first letters of the menu items. Check out the Keyboard pane in the system preferences for other keyboard navigation options. (I found this in less than three minutes, by the way; it's amazing what one can figure out, when one is more interested in learning than complaining.)
Re:What Apple does right (4, Informative)
gtomorrow (996670) | more than 4 years ago | (#30071726):What Apple does right (1)
gtomorrow (996670) | more than 4 years ago | (#30071822)
OOOPS! My reply was meant for the GP and not parent poster...ehmmm, yeh.
Insomma, not for Dupple but for Procasinator.
Re:What Apple does right (3, Informative)
TheRaven64 (641858) | more than 4 years ago | (#30071608) (1)
Procasinator (1173621) | more than 4 years ago | (#30071688)
This is my problem - I do use this manner. It's handy because I don't have to learn the various different short cuts accross different applications. It also allows me to explore the various commands quickly in a new application or get to commands without shortcuts without leaving my keyboard.
control-F2 is something, but it's more keyboard presses to be worth it. As in Control+F2, right, right, right, there is my menu option. So it doesn't allow quick access to actions or exploration without using the mouse.
I know I can configure short cuts to actions I often access, but tbh, I prefer not having too.
Re:What Apple does right (5, Informative)
TheRaven64 (641858) | more than 4 years ago | (#30071802)
Re:What Apple does right (2, Insightful)
Procasinator (1173621) | more than 4 years ago | (#30071934)
Re:What Apple does right (2, Informative)
joh (27088) | more than 4 years ago | (#30071646) (3, Informative)
caseih (160668) | more than 4 years ago | (#30071938):What Apple does right (0, Troll)
mdwh2 (535323) | more than 4 years ago | (#30071580)
Microsoft wants things to be orthogonal, logical, menu driven, hierarchical, and otherwise fully featured. Apple takes the approach that the user doesn't want to fuss with all sorts of menus and submenus (no two button mouse for years!)
MS have dropped the menu approach (think Office) - but personally I prefer the menu approach. And Apple's OSs have had menus for years, anyway.
Apple applications still make use of two buttons, which you have to clumsily press a control key to access.
applications which do not necessarily have any UI themes in common with each other.
No, it's Apple who are the worst offenders here - just look at how Quicktime and Itunes on Windows completely fail to comply with the Windows UI standards.
In my experience, Quicktime and Itunes are the worst UIs I've encountered - anything but elegant. I have trouble finding out how to do simple tasks in Itunes (e.g., getting it to recognise updated mp3 ID tags). Only yesterday, I plugged someone's Ipod into my computer so we could watch something - only to find the software had renamed files into random garbage, distributed across randomly named folders in no apparent logical order. We had to guess via file sizes, and try every single one until we came across it. Apple, it Just Works!
And what does "elegant" even mean? What's your objective definition, and your evidence for this assertion?
As always, subjective assertions without evidence get modded up simply because they are pro-Apple, whilst I bet I - even though I give clear examples and evidence - will get modded down, simply because these facts do not fit with an Apple moderator's worldview (how does moderation work these days, anyway? I haven't had any for years, and it seems they're only given out to those who mod up pro-Apple posts these days...)
Microsoft is doing a lot to emulate Apple. And frankly, it's about time.
God, I hope not. And with "Macs" these days being Apple branded PCs, I'd say the reverse is true.
Re:What Apple does right (2, Informative)
Mitchell314 (1576581) | more than 4 years ago | (#30071598)
Re:What Apple does right (1)
Anonymous Coward | more than 4 years ago | (#30071706)
> Apple's interface is elegant but inflexible. Everything fits into the existing scheme and runs perfectly within that scheme.
Bullshit.
Just look at the "zoom button" debacle on OSX. There is no "maximize window" functionality. The little green button with a "+" in it often makes the window *smaller* - or minimizes it (in the case of iTunes).
The OS is filled with these massive problems because it has been simplified to the point of being retarded.
Re:What Apple does right (1)
jordibares (1276026) | more than 4 years ago | (#30071714)
Re:What Apple does right (1)
Xest (935314) | more than 4 years ago | (#30071774) is relevant in the context of the actions being carried out for their applications too.
So the question is, whilst to some people like you and I the simplified context relevant system seems better, is there an underlying reason many others hate it? Do they simply dislike change? or is there something else there, like a context based system being more confusing for them because things aren't always where they were?
For what it's worth though I actually hate many of the Windows 7 changes, the new gadget system is appalling compared to the sidebar. Gadgets are useless because they're either on the desktop, out the way, and you have to explicitly switch to the desktop to see them in which case if you have to explicitly switch they may as well just be applications or alternatively they can be set to be always on top which means they obscure any windows you're working with underneath them. The sidebar ensured this wasn't a problem by allowing Windows to resize around the sidebar meaning they were both always on top, always available and yet never in the way.
I also found the taskbar changes unhelpful on a large screen, although it's great on the small screen of my netbook where taskbar space is limited, but on my 24" screen at 1900x1200 the new system only uses up about 20% of the length of the taskbar and yet I have to take extra clicks to find the window I want because they're all hidden in their groups. I reverted back to the classic taskbar where the Window I want is available instantly by using the full taskbar.
I even find the start menu since Vista much less efficient to navigate too in all honesty, if you don't type in the name of the program and want to click through because you don't know what icon was added the pre-Vista start menu was far more efficient.
As I say though, I do like Microsoft's ribbon interface. For me it's all about the speed and efficiency at which I can work, and much of the Windows Vista / 7 UI changes seem to add the amount of mouse movement and clicks I need to make, the Ribbon UI however does not as it puts what I need right in front of me when I need it.
Re:What Apple does right (0)
Anonymous Coward | more than 4 years ago | (#30071812)
Windows' interface is flexible but clumsy. While this has gotten much better in later versions, we're still looking at deeply nested menus, and applications which do not necessarily have any UI themes in common with each other.
Please, please do not try to hang "applications which do not necessarily have any UI themes in common with each other" on Windows alone.
Any GUI operating system that allows skinning of applications, whether by design, or by sheer bloodyminded overriding of low-level user interface drawing routines, will eventually have this problem as soon as some programmer decides that he doesn't like the "standard, boring, old window style" and he then proceeds to inflict his new "vision" of what the interface should look like on the user.
Then you wind up with non-rectangular windows in garish colors of the programmer's choosing with buttons that don't look like buttons, no visible menu bar, and few, if any, of the features users are used to seeing in their application windows.
Re:What Apple does right (1)
zmollusc (763634) | more than 4 years ago | (#30071892) try a more modern mac and see how things have altered.
So? (5, Insightful)
war4peace (1628283) | more than 4 years ago | (#30071436)
We are living in a twisted, perverted world, where one can't express an opinion without being beheaded by both the press and the company he's working for. God help us all!
Hi (5, Funny)
Anonymous Coward | more than 4 years ago | (#30071440)
I'm a Mac and Windows 7 was MY idea
News of "staff restructuring"... (0)
Anonymous Coward | more than 4 years ago | (#30071442)
...coming to the guy in 3... 2... 1...
If only.... (-1, Troll)
Anonymous Coward | more than 4 years ago | (#30071444)
Re:If only.... (0)
Anonymous Coward | more than 4 years ago | (#30071494)
employee who 'inaccurate and uninformed' (4, Insightful)
hibernia (35746) | more than 4 years ago | (#30071462)
Re:employee who 'inaccurate and uninformed' (0)
Anonymous Coward | more than 4 years ago | (#30071596)
Mistaken is the Official Rebuttal not the comment (1)
viraltus (1102365) | more than 4 years ago | (#30071468)
Hello Streisand (3, Insightful)
je ne sais quoi (987177) | more than 4 years ago | (#30071474):Hello Streisand (2, Insightful)
bruno.fatia (989391) | more than 4 years ago | (#30071644).
If this is true... (0, Troll)
sitarlo (792966) | more than 4 years ago | (#30071476)
Re:If this is true... (4, Insightful)
recoiledsnake (879048) | more than 4 years ago | (#30071510)
Windows 7 is still clunky, slow, and unstable.
Citation needed. I use Windows 7 and it's certainly not one of those.
Re:If this is true... (-1, Troll)
sitarlo (792966) | more than 4 years ago | (#30071600)
Re:If this is true... (2, Informative)
kannibal_klown (531544) | more than 4 years ago | (#30071514) this is true... (0)
Anonymous Coward | more than 4 years ago | (#30071554)
You don't know how to use it properly then...
I am no Windows fan, I have Snow Leopard, Windows 7, XP and Linux (Suse, RedHat, CentOS and unbreakable Linux) all on differing machines...
All in all, Windows 7 has been stable as a rock on my machine...no problems to report apart from lacking Samsung Scanner Drivers...not MS' fault.
This is not like OS X! (5, Funny)
zebslash (1107957) | more than 4 years ago | (#30071490)
Microsoft has issued an official rebuttal: "We never used OS X as a source of inspiration in the design of Windows 7. This is completely uninformed. We used KDE 4 instead".
Ideas don't occur in a vacuum (3, Insightful)
Interoperable (1651953) | more than 4 years ago | (#30071506)
Hi, my name is Steve Jobs... (1, Redundant)
DaRanged (735002) | more than 4 years ago | (#30071532)
Should've named it Vista7 or Vista-II instead.. (1)
jkrise (535370) | more than 4 years ago | (#30071534):Should've named it Vista7 or Vista-II instead.. (1)
smitty777 (1612557) | more than 4 years ago | (#30071658)
Not sure about that. I think they're trying to distance themselves from Vista. I do agree with you in concept, tho.
Re:Should've named it Vista7 or Vista-II instead.. (1)
Xest (935314) | more than 4 years ago | (#30071860) earmed from it's crappy earlier releases.
That was close (1)
lyinhart (1352173) | more than 4 years ago | (#30071540)
Linux users (-1, Troll)
Anonymous Coward | more than 4 years ago | (#30071556)
Are butt hurt that they cant
/dev/null their /etc/fstab
Paging Mr. Balmer (1)
m0s3m8n (1335861) | more than 4 years ago | (#30071578)
Defenseable (0)
Anonymous Coward | more than 4 years ago | (#30071586)
Sounds to me like the "Liar, liar, pants on fire defense"
I'm a Mac (1, Redundant)
Jezza (39441) | more than 4 years ago | (#30071594)
I'm a Mac, and Windows 7 was my idea!
I agree with MS (-1, Troll)
Anonymous Coward | more than 4 years ago | (#30071630)
Bad Analogy (courtesy MS) (1)
smitty777 (1612557) | more than 4 years ago | (#30071632)
FTA: "When the sun is shining there’s no incentive to change the roof on your house. It’s only when its raining that you realise there’s a problem."
Ahem....um...so I guess by rain, you mean some sort of Katrina like attention getter? Sheesh...
Look and Feel (2, Interesting)
Adrian Lopez (2615) | more than 4 years ago | (#30071734).
"built on that very stable core Vista technology" (0)
Anonymous Coward | more than 4 years ago | (#30071750)
From the article: "it’s built on that very stable core Vista technology, which is far more stable than the current Mac platform, for instance."
Apple's development model, for years, has been to perpetually tweak and improve on their existing operating system code. Not to mention it's Unix, which has been around since the dinosaurs. He even says in the article that XP was completely rebuilt for Vista, which was then gutted again for this new Vista2. He wants to talk about stability? Why am I surprised?
M$, You Stupid Fools (-1, Troll)
Anonymous Coward | more than 4 years ago | (#30071814)
Deny, deny, deny... it doesn't change the fact that M$ ripped most of its UI improvements directly from OS/X. Imagine if someone did that to M$... you'd be sued into oblivion. M$ you suck.
Sounds like.... (1)
SendBot (29932) | more than 4 years ago | (#30071900)
sounds like someone doesn't want to get sued by apple for defamation.
Someone got called out (2, Insightful)
onyxruby (118189) | more than 4 years ago | (#30071912).
If you believe in... (0)
Anonymous Coward | more than 4 years ago | (#30071962)
evolution. Then the chances of a random chain of events leading to Windows 7 looking like OS X is possible. It might even be the only explanation. | http://beta.slashdot.org/story/127122 | CC-MAIN-2014-42 | refinedweb | 4,352 | 76.86 |
Hello, I'm currently trying to write my own hex editor, however, I've noticed that my program is horribly slow at loading files. Anything in the range of 500kb is fine, but afterwards in the 1MB range, the delay to the completion of the whole operation is noticable in seconds, e.g a 4.5 MB file takes about 12 seconds to process on a good run. I know this is a problem, because I've used other hex editors that will load a 200+MB file in less than that time.
I'm pretty sure this is due to the fact that my program reads the file byte by byte and performs an alogrithm on each byte to convert them into hexadecimal format. Currently, I'm reading in one unsigned char per byte in the file, them calling my function to convert that into a string object. I've tried reducing the number of reads, such as in reading 16 bytes at a time, but that still won't reduce the number of times I need to call the function to convert it to hex, and thus far, has not been able to produce any noticable gains in speed.
I've cut out all of the GUI lines of code and altered the following code to work as a basic command line representation of only reading in the file, which is where I'm having bottleneck problems. I've been trying to optimize this section for days, but I can't figure out how it could be done. I'm sure there's something efficient that I should be doing, but I'm horribly unaware of it.?Code:
#include <iostream>
#include <fstream>
using namespace std;
/* Convert Int To Hex String */
string umulti_base(int input1, int input2) {
/* Temporary Function Variable */
string ans = "", bit = "0123456789ABCDEF";
int incr = 1, value = input1, range = input2, count = 0;
/* Grab Highest Power On Base */
while((incr * range) <= value) {
incr *= range;
++count;
}
while(count >= 0) {
for(int x = range; --x >= 0;) {
if((value - (incr * x)) >= 0) {
ans += bit[x];
value -= (incr * x);
break;
}
}
incr /= range;
--count;
}
return ans;
}
int main() {
/* Variables */
string file_name;
unsigned char mem;
ifstream file;
int file_size = 0, b = 0, e = 0, file_get = 0;
/* Get File Name Input */
cout<<"Enter File Name : ";
cin>>file_name;
cin.ignore();
/* Open File */
file.open(file_name.c_str(), ios::binary);
/* If File Can Be Opened */
if(file.is_open()) {
/* Get File Size & Reset File Pointer */
file.seekg(0, ios::beg);
b = file.tellg();
file.seekg(0, ios::end);
e = file.tellg();
file_size = e - b;
file.clear();
file.seekg(0, ios::beg);
/* Cycle Through File Byte By Byte & Convert To Hexadecimal */
for(int x = -1; ++x < file_size;) {
/* Read 1 Byte Into Char */
file.read((char*)(&mem), 1);
/* Convert to Hex */
cout<< umulti_base((int)mem, 16) << "\t";
}
cout<< "\nTask Complete \n";
}
/* If File Cannot Be Opened */
else {
cout<<"File Could Not Be Opened \n";
}
return 0;
} | https://cboard.cprogramming.com/cplusplus-programming/115007-binary-file-manipulation-speeds-printable-thread.html | CC-MAIN-2017-22 | refinedweb | 484 | 66.47 |
SP_signal()
#include <sicstus/sicstus.h> typedef void SP_SigFun (int sig, void *user_data); SP_SigFun SP_signal(int sig, SP_SigFun fun, void *user_data);
Installs a function
fun as a handler for the signal
sig.
It will be called with
sig and
user_data as arguments.
The signal
The function
An extra, user defined value passed to the function.
SP_SIG_ERR if an error occurs error. On success,
some value different from
SP_SIG_ERR.. may only call other (non SICStus) C code
and
SP_event(). Note that
func will be called in the main
thread.
If
fun is one of the special constants
SP_SIG_IGN or
SP_SIG_DFL, then one of two things happens:
sighas already been installed with
SP_signal(), then the SICStus OS-level signal handler is removed and replaced with, respectively,
SIG_IGNor
SIG_DFL.).
Note that
SP_signal() is not suitable for installing
signal handlers for synchronous signals like
SIGSEGV.
SP_event(), Signal Handling. | https://sicstus.sics.se/sicstus/docs/latest/html/sicstus.html/cpg_002dref_002dSP_005fsignal.html | CC-MAIN-2017-22 | refinedweb | 143 | 67.15 |
public class Futures extends java.lang.Object
Used as a service to sub-tasks, collect pending-but-not-yet-done future tasks that need to complete prior to *this* task completing... or if the caller of this task is knowledgeable, pass these pending tasks along to him to block on before he completes.
Highly efficient under a high load of short-completion-time Futures. Safe to call with e.g. millions of Futures per second, as long as they all complete in roughly the same rate.
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
public Futures()
public Futures add(java.util.concurrent.Future f)
public void add(Futures fs)
public final void blockForPending() | http://docs.h2o.ai/h2o/latest-stable/h2o-core/javadoc/water/Futures.html | CC-MAIN-2018-17 | refinedweb | 116 | 58.69 |
Hey.
sounds like a good feature request, I'll keep that in mind, but I don't think that I can't implement ALL user-requested features with the first open beta release, nevertheless it's a good idea !
Regarding the UScript/C++ doc: it's not well documented currently, but I will provide a rich illustrated and comprohensive pdf-based documentation for the SDK, not only for it's classes
without it, it'd be rather useless for unexperienced users
good ! I'll be glad to help, just tell where to go to your forums our site, or pm me here, what ever you prefer
yeah ! thanks :)
and wait time is nearly over, if you want to get your hands on it before official open beta then head straight to UT99.org and ask for internal beta testing (starting 31.03.) !
I'm currently deeply occupied with the new Menu / Interface System, it takes much more time than expected, it's 25 % C++ and 75 % UScript, using the new system creating new menus and interfaces won't require any coding at all !
that's also why I didn't post new media the last 2 weeks
thanks !
EVERYTHING can be set up to suit your needs, you don't want shaders ? then turn them off ! they're then either replaced by software-emulated combiner effects or are simply not present, the particle engine is too performance demanding ? then set it on a performance friendly level fitting your machine !
I think no one will be forced to buy a new PC just to use the SDK properly
Cool group ^^
sorry, but didn't you read the description ?
it's a game and software development environment for unreal engine 1 based on the engine frame of unreal tournament
yes, this will be included
As somebody still may have not yet recognized:
>> This has been cancelled 2 years ago ! <<
Most of it's core features live on in the Project "Unreal Tournament SDK", which is present at moddb too (moddb.com/mods/unrealtournamentsdk)
thanks dude ! much appreciated ! :)
I really deeply appreciate every single mod track, thank you very much !
I'm doing the best I can, to offer an "OPEN SOURCE UDK" for everyone
31.03.10 the internal beta at UT99.org gets released and thus the development accelerates as multiple users work on it, giving feedback and testing it from a customer point of view
Also an indipendent website is being build by xilefian, so stay tuned ;)
Another new UT Mod/Mutator here !
Going to get Half Life 2 only because of that that mod !
Yes if everything turns out well (Internal Beta Testing @ UT99.org) I'll release the first public beta on summer !
oh and regarding the menu.. it was just an alpha version, the x-menu system is pretty much straight forward and you can adjust many things and have a lot of widgets to use"
I cannot code a new launcher/exe without the source code, AND many people ARE interested, I know it already
import and delivery fees are irrelevant, there's steam and UT99 can be loaded down for 5-10 bucks or so, from anywhere in the world
even if I would have an own exe, it would be useless, still relying on a binary engine framework, AND I can't just simpyl code (it would take too much time) an own complete engine framework TOO, I say it ONCE AGAIN : the SDK works UPON the engine framework of UT, parallel to it, it's not a completely new own build of an engine
Everything regarding the SDK is open source already..
A new executable isn't needed for this, since everything can be launched by the original exe
PhysX is support on any machine, no matter which graphics card, it works on ATI Cards too, it's just not hardware accelerated
The SDK uses DirectX 9.0c and OpenGL 3.2 - As I still have Win XP I'm not able to develope beyond DirectX 9, and I'm not eager using DirectX 10+ , since OpenGL is far more flexible and faster..
hehe thank you all, didn't thought the alpha version would impose that much ^^ just being said the following: you've seen only a very small preview of what will be possible in the beta and further builds
cool ! good to hear, so welcome "aboard" :)
You'll have a complete framework creating advanced mods, total conversions and semi-indie games using the SDK, if you want to blend simplicity of Unreal Engine 1 Editing with additionally added Cutting-Edge Open Source Technology, then this is for you
I doubt that they'll allow it, besides I want to release an open beta first and see how it developes along the scene, if the requests for an indipendent title are that much, then I give it a try
omg replication.. yes.. I get headaches when I'm even thinking of it.. anyway, you know how to contact me if you need me :)
not yet trid, but I will soon, been currently busy with my new menu system..
I appreciate that you're trying to help, but there're two issues concerning this:
1. Even the demo stands under copyright, copying it's binary engine framework, is the same as copying it from the fullversion
2. The engine framework of the demo is of inferior functionality and it is below Engine Build 436, the hardcoded features of the SDK have been compiled with the public headers of the 436 build, there would be a version missage
ok, I'm looking forward to it, if you should need any assistance I would be happy to help (if I have time) :)
oh wow, I highly appreciate your offering ! An indipendent, professional website for the SDK would be awesome (I can do many things, but I fail when it comes to webdesign lol)
I found out that Unreal Engine 1 can manage ALL resources like newer Engine Versions. You simply have to call the Game's exe with your own Inis cast on, that should be known already, but in the inis you define dynamic paths that loads stuff from UT Dir and SDK Dir, that don't depend on the InstallDir Name and Letter of the HDD. The installer will search for the UT exe thus finding where exactly UT is installed on your system, setting up the Paths for your SDK client regardless of where UT is installed.
You'll need for each Unreal Engine 1 Game an own port of this SDK, because as for THIS SDK it depends on Engine.dll, Core.dll etc. of Unreal Tournament Build 436. Deus Ex, Wheel of Time etc. has own Builds of Engine.dll etc, which makes it incompatible for my Hardcoded Features, if the Engine Game is below 436 build. Nevertheless as for Games like Unreal, or Deus Ex, a Port won't be that difficult. Don't know about Wheel of Time, Harry Potter and co.
thank you very much !
yes this is indeed a great fascinating vision, but first go find 10+ unreal engine designers/modders willing to do that..
Beta 2.0 is out ! Gonna test it.
What I can see from the description, the overall concept is ok and interesting. Elemental inventory and weapons is a good start.
On the second view, while watching the video, this looks for me like yet another (currently) simple standard-weapon change mod. Also the weapon fire sounds sometimes extremely strange, especially when it comes to that one "load-up-sound".
Additional new gameplay features like custom moves, ammo stealing or the armor system sound good and refreshing, so I'm looking forward for the not yet working features being implemented in a future release.
I give it a 7/10
no, sorry, again: you have to have either Unreal or UT installed, I'm not authorized to provide a runtime of unreal engine 1, the SDK is just a solution to get around engine limits ? | http://www.moddb.com/members/hoor-paar-kraat/comments/page/7 | CC-MAIN-2015-06 | refinedweb | 1,343 | 64.54 |
Hello! This week we have implemented property of hygiene and lexical scoping of global symbols in macros and quotations. Full description of these features is (or will be) in paper and tutorial. In short: - hygiene Symbols introduced by macro expansion does not conflict with symbols from other macro expansions and top level code. For example with macro definition macro m(ex) <[ def f () { printf ("x") }; $ex; f() ]> code def f () {printf ("y") }; m(f()); would be transformed to def f () { printf ("y") }; def f_34 () { printf ("x") }; f (); f_34 () Thus symbol "f" introduced by macro is "renamed" to avoid capture of other symbols. - lexical scoping of global symbols Global symbols used in macros (quotations) are searched in namespaces imported in place where they are defined, not in place where macro is expanded. For example using System.RegularExpressions; macro m () { <[ Regex ("a+") ]> } used in code, where System.RegularExpressions are not imported, like def x = m (); expands to full name visible at macro definition site def x = System.RegularExpressions.Regex ("a+"); This stuff is still under testing, but all features seems to work very good. Kamil Skalski | http://nemerle.org/mailman/pipermail/devel-en/2004-April/000030.html | crawl-001 | refinedweb | 184 | 51.38 |
Type: Posts; User: parz; Keyword(s):
Looks like he's on dialup - unless thats DSL (doubtful) - in which case, I wouldn't worry too much, since he had a dynamic IP - the only way they can trace him down is to go to his ISP, check through...
Ok - So I was working on this program in Java. The purpose is to be able to
create an instance of class "Shape", which extends "FilledGraphical", which
extends class "Graphical Component". When...
I typed the code as follows:
#include <iostream>
using namespace std;
int main()
{
char first_name[64];
char last_name[64];
No - the one I had was legit - the generator allowed you to install on multiple machines without having to have a giant booklet of CD-keys. It's mainly used for businesses.
I know that I used to have a Windows XP 8-in-1 CD. On this CD, you could install Pro:Multiple Licence, OEM, Table, and Multimedia (and same with Home). In order to install the multiple Licence one,...
If you haven't been to, you should. This gives a perfect example of programming genious wrapped around a very mudane subject.
Yes - I recommend everyone learns how to use emacs (or rather, becomes familiar with it - there are so many add-on libraries and such that mastering it can take a while). I prefer to use vi, mostly...
So...let's recap:
(Type) vi [filename]
(To edit file - press) i
(To stop editting) ...
Man - It really sucks when the quality of AO posts is reduced to that of fart jokes. | http://www.antionline.com/search.php?s=0565367718ccd901bed1a04f10d436d3&searchid=3679727 | CC-MAIN-2015-48 | refinedweb | 260 | 70.53 |
J Kuslich, Software Engineer, IBM
09 Jun 2005Updated 10 Nov 2005
Rational XDE Professional v2002, Microsoft .NET Edition, is a powerful modeling and productivity tool for developers that integrates with Visual Studio .NET. This article introduces XDE's major features and takes you through a simple example project.:
Software design is a process practiced by all developers,
whether they do formal design or scratches on a napkin. Often development teams
working against tight schedules don't feel they have the time to devote to a
more comprehensive design process. Design documentation is scoffed at in some
organizations, since it's often voluminous and must constantly be kept up to
date; after all, the ultimate goal of software development is good code, not
good design documents. Yet good software design leads to good code. What
developers really need is a design tool that's closer to the code they're
working so hard to write.
Rational XDE Professional v2002, Microsoft .NET Edition, is
both a sophisticated software modeling tool and a productivity tool for
developers. This "extended development environment" integrates directly with
Visual Studio .NET and even runs within it. It merges the practices of software
design and coding into a seamless, coordinated process supporting the work of
real-world developers. XDE isn't just a tool for analysts, it's a software
development productivity tool for development teams.
This article will introduce you to the major features of XDE
and help you start working with it quickly. To keep this article brief and
focused, I'll assume you're familiar with software development and design.
Experience with a software modeling tool like Rational Rose will be extremely
helpful. In addition, you should have used at least some version of the Visual
Studio tools so that you can follow along with the example, which was produced
with Visual Studio .NET. You don't have to know how to write code for the
Microsoft .NET platform, but knowing the basic concepts of .NET development in
the C# language will be helpful.
XDE Feature Overview
I'll start the tour of XDE with a brief introduction to its
major features that will help you build better software:
Integration with Visual Studio .NET - XDE is so tightly integrated with Visual Studio.NET
that it runs inside it as an add-in. I can't think of a better way to access a software engineering tool than from inside the integrated development environment (IDE) itself.
UML modeling - XDE has sophisticated software modeling features, including support for much
of the Unified Modeling Language (UML). You can build a design model that
incorporates UML model elements such as classes and use cases, and there are
diagramming tools for building diagrams (for example, class and sequence
diagrams). You can use the modeling features by themselves, but the real power
of XDE is in its integration of modeling with the coding process.
Code synchronization - XDE can generate code from models and vice versa, and
keep the two in sync. In the real world, much of the development process
involves writing a great deal of straightforward code, such as class and method
definitions, and the hard part of writing a class is designing it (especially
when it must interact with other classes). With XDE's code synchronization
features, you can generate code from your design model elements, saving coding
time. You can also generate model elements with your code and keep your models
and code in sync, so you don't have to spend time manually keeping the design
model up to date.
Support for team development - Teams already have source code control systems to help them
share source code files and control their versions. XDE provides several ways
to work with existing source code control systems to share and control access
to model elements.
Custom code templates - In addition to enabling automatic generation of code from model
elements, XDE lets you create and apply your own custom code templates. You can
bind code templates to methods of your modeled classes, and XDE will generate
the code from the template in the method body. Code templates can be reused on
many methods, improving consistency and reducing the amount of boilerplate code
that you have to type yourself. Those of you who use C++ should note that code
templates are nothing like templates in C++; in XDE, code templates are chunks
of reusable code that you can tell XDE to generate for you for elements in your
model.
Design patterns - XDE provides concrete support for the software engineering concept of design patterns. A design pattern is a formalized
description of a piece of software that can be applied repeatedly in the
designs of many different applications. It generally describes a common
software mechanism, such as a proxy object that facilitates communication
between two other objects across various communication mechanisms. Such a pattern
is specific in intent but isn't tied to any particular piece of software.
Design patterns help you to improve productivity and quality by reusing proven
concepts throughout an application, and to ensure consistency by designing the
same mechanism (such as the proxy object) the same way each time. With the
design pattern feature of XDE, you can create, store, and reuse design patterns
in your models.
Getting Started with XDE
Since XDE integrates directly into the Visual Studio .NET
environment, before getting started you should have installed Visual Studio
.NET. The first release of XDE is designed to work with C#, so make sure you've
installed Visual C# as part of your Visual Studio .NET configuration. Later on
I'll show how XDE can work with Visual Basic .NET and managed C++ code.
Once you've installed XDE, you may want to dive in and start
using it right away, but you have a few things to consider first. As I
mentioned earlier, XDE isn't just for use by a couple of high-level architects
or analysts in a technology group. It's meant to be used by developers working
in teams, so it supports the need for teams to share access to software models.
After installing XDE, you'll need to consider how your team will work with and
share models and model elements, so that you can configure XDE to meet your
needs.
XDE provides four options for storing models and model
elements, as described below. Models are stored as files, and, depending on the
file storage options you choose, some elements may be stored in separate files
as well. You need to choose a file storage policy that best suits how your team
works with models.
You can set the file storage option through the Tools >
Options command, as we'll see in our example later. For more information on how
models are stored, see the XDE help topic "Setting Model File Storage Policy."
The Relationship Between Models and Code
Another concept you should understand before working in XDE
is the relationship between XDE models and code. There are essentially three
types of model that you can build with XDE an analysis model, a code model,
and a reference model and each model relates to your code and software
project somewhat differently.
You might construct an analysis model during
the initial analysis and design phase of a project. These models typically
describe business requirements with elements such as use cases, and define the
initial architecture and high-level design for a project. These models may be
related directly to code, but often they're built more for analysis than for
code construction. Analysis models are often prepared by analysts and
architects and used by developers as a reference for detailed software design.
A code model contains
elements that map one-to-one with code elements. You build code models to
describe the detailed design of your software. This is the type of model that
you can use with XDE's round-trip engineering features to generate code,
generate model elements from code, or keep the two in sync. Code models are the
heart and soul of XDE and are what developers will work with day in and day
out. After all, the whole purpose of modeling software is to understand how to
build code. The code, not the model, is the software; the model isn't an end in
and of itself. It's important to understand this tight relationship between
models and code, because it's the key to improving productivity and to keeping
developers as involved with the design of the software as they are with the
code.
The distinction between an analysis model and a code model
in XDE is minor. It's mostly a difference of intent and purpose: one is focused
on defining the problem and the other on building a solution. In general,
you'll only synchronize code models, and not design models, with code.
XDE does distinguish reference models from code and analysis
models. A reference model represents the elements in a
.NET assembly that may or may not have been produced by the development team.
You may not always have control over the code in assemblies that your project
uses, and in the case of third-party assemblies you may not even be familiar
with the design and internals of the code. Reference models are useful for
visualizing the design of third-party assemblies or assemblies produced by
other teams within your organization. XDE generates these models for you. It
can even generate reference models for the assemblies that are part of the .NET
platform itself!
Although you cannot modify a reference model, you can add
diagrams, such as class diagrams, to your code model and include elements from
reference models. This may help you get a better picture of code you're not
familiar with.
XDE can generate reference models for any .NET assembly, not
just those written in C#. This is the one area where the first release of XDE
interoperates to some degree with Visual Basic .NET and managed C++ code: XDE
can generate reference models for .NET assemblies written in these languages as
well.
Creating Your First Code Model
Now that you have this background, I'll give you a tour of
what it's like to work with XDE, walking you through the process for creating a
simple code model. Here are the steps:
I'll take you through the details of these steps below. In
addition, you can download the Visual Studio .NET project (including the XDE files).
Create a Visual C# Project
The first step to creating a code model is to create a new
Visual C# project in Visual Studio. To follow along in this example, you should
create a C# Windows Application type of project. For this project type, Visual
Studio .NET generates a couple of source files, which are accessible from the
Solution Explorer. One of these files is named Form1.cs; rename it as
frmMain.cs, rename the form frmMain, and set the form's Text property to "Simple Example".
Form1.cs
frmMain.cs
frmMain
Text
Add a Code Model
At this point, no XDE model file exists. We could create it
in one of two ways: by adding a new model to the project or by generating (via
synchronization) a new model from the existing code. Granted, there's not much
code at this point, but if you're creating a code model, the quickest method is
to generate it after creating your project.
To generate the model, right-click the project in the
Solution Explorer and choose Synchronize from the context menu. Alternatively,
you could select the solution or project and click the Synchronize icon in the
Solution Explorer toolbar.
When synchronizing for the first time, you'll notice a
flurry of activity in Visual Studio .NET. XDE does several things on initial
synchronization:
Set the File Storage Policy
At this point, before saving your project, you need to set
the file storage policy for the model if you don't want to use the default. For
this example, to store each model element in a separate file, change the policy
to "Automatic All" as follows:
Now, save the Visual Studio .NET project by clicking the
Save All icon in the toolbar. This saves all of your Visual Studio .NET files
and also saves your XDE model file. In addition, since you've selected the
"Automatic All" file storage option, each model element is stored in a
separate file. At this point you have only one class corresponding to your
form, and you should see it in the directory in which you saved your project.
Take a moment to examine the directory and the file types for the files XDE has
generated.
These files can now be stored in a source code control
system, such as Rational ClearCase or Microsoft Visual SourceSafe. You can
manage the model and element files through your source code control system just
as you'd manage your C# source code and project files.
Developers in a team working on a model set up this way can
make changes to model elements without having to fight over access to a single
model file. They can check out the files they need, make their changes to
either the code or the model, and then synchronize the files and check them
back in, making them available for reference or for use by other developers.
Add Model Elements
At this point we're ready to build software. We can add
model elements through XDE, write C# code, or both. XDE will take care of the
rest by keeping the code and model in sync whenever we synchronize the model.
(Note that there's also an autosynchronization feature, which I don't use here but
which you can learn more about through XDE's help documentation.) We'll see how
this works in a moment; you'll have an opportunity to explore the modeling
functionality in addition to learning how XDE generates code from models.
For this example, we'll model a simple "Hello, World"
application. The example is simple so that the focus can remain on learning how
to use the features of XDE.
Our application will have two classes other than our Windows
form, frmMain. The first class, CGreeting, will represent a general type of greeting, and the second, CHelloWorld, will derive from CGreeting. The class diagram in Figure 1 illustrates the relationship. Note that CGreeting has one method, greet, and that CHelloWorld overrides this method.
CGreeting
CHelloWorld
greet
Next you'll add both of these classes to the main package of
your model. To add a class to a package, right-click the package in the Model
Explorer, choose Add UML, and select Class.
The easiest way to create a generalization relationship
between the two classes is to create it using the class diagram, as follows:
Next, add the greet method to each class. To add a method (known as an operation in XDE) to a class, right-click the class, choose Add UML, and select Operation. You can also add operations to a class by clicking the ellipsis button of the Collections property in the property page for the class and selecting the Operations tab.
greet
Collections
Generate Code from the Model
Now that you've defined your classes, you're ready to
synchronize your model again and have XDE generate code representing your
classes and methods. Right-click the model in the Model Explorer and choose
Synchronize, or click the Synchronize button in the Model Explorer toolbar.
Then right-click the CHelloWorld class and choose Browse
Code. This takes you to the Solution Explorer and highlights the CHelloWorld.cs file. Listing 1 shows the code that should have been generated.
CHelloWorld.cs
namespace HelloWorld
{
public class CHelloWorld : CGreeting
{
public void greet()
{
}
}
}
Notice that XDE not only generated the class definition but also properly generated the inheritance relationship between CHelloWorld and CGreeting in the code, just as you specified in your class diagram. With no duplication of effort, your code was matched to your design.
At this point, let's try to build the Visual C# project and see what happens. From the Build menu, choose Build. Unfortunately, the build
fails with a build error in Visual Studio .NET. The error message states:
The keyword new is required on 'SimpleExample.CHelloWorld.greet()' because it hides inherited member 'SimpleExample.CGreeting.greet()'
The keyword new is required on 'SimpleExample.CHelloWorld.greet()' because it hides inherited member 'SimpleExample.CGreeting.greet()'
As we'll soon see, the implied solution to this error is a bit misleading, but the message does indicate the problem correctly: we attempted to override a method improperly in C#. This was not a problem or a bug in XDE, which synchronized our code and model just as we specified. XDE saves us the time of generating our class and method definitions, but it doesn't do everything for us; it isn't magic and doesn't eliminate the need to write code. (If it did, many software developers would be sorely disappointed.)
When overriding methods in C#, we must declare the method in the superclass as virtual and specify that the method in the subclass will explicitly override the method of its superclass. The error message we received was Visual Studio .NET's best guess at what caused the problem, but in this case the new keyword isn't in fact what we need. We can add the virtual and override keywords to our C# code as indicated in bold in Listings 2 and 3.
new
virtual
override
namespace HelloWorld
{
public class CHelloWorld : CGreeting
{
public override void greet()
{
}
}
}
namespace HelloWorld
{
public class CGreeting
{
public virtual void greet()
{
}
}
}
Now rebuild the project and you'll find that this time there
are no build errors.
While much of the code you write by hand, such as method implementations, produces no content within your model, it turns out that modifiers such as virtual and override are represented in the XDE model. Synchronize your model and code and then select the greet method of the CGreeting class in the Model Explorer. Look at the value for the LanguageModifiers property: it's now set to the value virtual, which corresponds with the modifier you added in C#. Select the CHelloWorld class and look at its LanguageModifiers property. There you'll see the value override, matching what you typed in
C#. With no duplication of effort, the model was kept in sync with the code.
LanguageModifiers
Next, we'll add some implementation code to the bodies of
our two greet methods.
Modify the Code to Add Application Logic
Modify the bodies of the greet methods as shown in
bold in Listings 4 and 5. Be sure not to forget to include the using
statements at the top of each file as shown, or building your project will produce errors.
using
using System.Windows.Forms;
namespace HelloWorld
{
public class CGreeting
{
public virtual void greet()
{
MessageBox.Show("Hi!");
}
}
}
using System.Windows.Forms;
namespace HelloWorld
{
public class CHelloWorld : CGreeting
{
public override void greet()
{
MessageBox.Show("Hello World!");
}
}
}
Now we need some way to call our methods. To do this, let's add two buttons to our form that will call the methods and display the message boxes. Go to the Solution Explorer, right-click frmMain.cs, and choose View Designer. Drag two buttons to the form from the Toolbox and give them the labels shown in Figure 2. Set the name
property of the button labeled "Greeting" to btnGreeting and the name property of the button labeled "Hello World!" to btnHello.
name
btnGreeting
btnHello
Now double-click btnGreeting to generate a
Click event handler, and edit the body as shown in Listing 6. Do the same for btnHello, editing the body as shown in Listing 7.
Click
private void btnGreeting_Click(object sender,
System.EventArgs e)
{
CGreeting grt = new CGreeting();
grt.greet();
}
private void btnHello_Click(object sender,
System.EventArgs e)
{
CHelloWorld hw = new CHelloWorld();
hw.greet();
}
Rebuild your project and execute it to see it in action.
Synchronize to Update the Model
Finally, I'll show how your model can be updated from the
code you write. Open CHelloWorld.cs and type in the code
in Listing 8 to add a new method named sayGoodbye to the class.
sayGoodbye
namespace HelloWorld
{
public class CHelloWorld : CGreeting
{
public override void greet()
{
MessageBox.Show("Hello World!");
}
public void sayGoodbye(int numTimes)
{
for (int i=0; i < numTimes; i++)
MessageBox.Show("Goodbye!");
}
}
}
Resynchronize your code and model. Then expand the CHelloWorld class in the Model Explorer, and you'll see that the new sayGoodbye method has been added to the model as an operation. Expand the operation and you'll see its argument, numTimes, represented. If you
look at the properties sheet, you'll even see the C# type int stored in your model in the TypeExpression property. Even your class diagram has been updated; if you open it, you'll see that the sayGoodbye method is now shown on the diagram as a member of your class.
numTimes
int
TypeExpression
Only the Beginning
XDE has even more features for building consistent software and improving productivity that you should explore. The code templates feature enables you to store and generate reusable code along with the code generated by the defined model elements. With the design patterns tool, senior developers can create reusable design elements that can be applied many times in the same project or in multiple projects.
Whether you use a full implementation of the Rational Unified Process or an agile process like Extreme
Programming, Rational XDE has features that developers and development
teams need in order to stay productive without sacrificing software design and
modeling. Software models are excellent communication tools, but they're
time-consuming to maintain. With XDE, you can concentrate on designing and
building good software while still producing up-to-date models that the entire
development team can reference and work with. Integrated directly with the
Visual Studio .NET IDE, Rational XDE is a tool for the entire development team.
Acknowledgments
Many thanks to Davor Gornik and Raj Kesarapalli for their
assistance in reviewing this article. Thanks also to Caroline Rose for her
editing work and to Gary Clarke for his guidance.
Resources
About the author
JJ Kuslich is a software engineer who designs and builds data-driven business applications. Over the years he has also worked as a software architect and project manager, and has written many articles along the way. He currently works in the Pacific Northwest and lives just 15 minutes from a dozen hiking trails that do his body (and mind) good.
Rate this page
Please take a moment to complete this form to help us better serve you.
Did the information help you to achieve your goal?
Please provide us with comments to help improve this page:
How useful is the information? | http://www.ibm.com/developerworks/rational/library/04/r-1378/index.html | crawl-001 | refinedweb | 3,811 | 61.87 |
# $NetBSD: Makefile,v 1.196 2003/01/03 15:34:30 luke, except for the # /etc configuration files. # If BUILD_DONE is set, this is an empty target. # distribution: # Builds a full release of NetBSD in DESTDIR, including the /etc # configuration files. # buildworld: # As per `make distribution', except that it ensures that DESTDIR # is not the root directory. # installworld: # Install the distribution from DESTDIR to INSTALLWORLDDIR (which # defaults to the root directory). Ensures that INSTALLWORLDDIR # is the not root directory if cross compiling. # release: # Does a `make build', and then tars up the DESTDIR files # into RELEASEDIR/${MACHINE},.so: builds and installs prerequisites from libexec/ld.*.so do-build # # Enforce proper ordering of some rules. # .ORDER: ${BUILDTARGETS} includes-lib: includes-include includes-sys includes-gnu: includes-lib # # Build the system and install into DESTDIR. # START_TIME!= date build: .if defined(BUILD_DONE) @echo "Build already installed into ${DESTDIR}" .else @echo "Build started at: ${START_TIME}" .for tgt in ${BUILDTARGETS} @(cd ${.CURDIR} && ${MAKE} ${tgt}) .endfor @echo "Build started at: ${START_TIME}" @printf "Build finished at: " && date .endif # # Build a full distribution, but not a release (i.e. no sets into # ${RELEASEDIR}). "buildworld" enforces a build to ${DESTDIR} != / # distribution buildworld: .if make(buildworld) && \ (!defined(DESTDIR) || ${DESTDIR} == "" || ${DESTDIR} == "/") @echo "Won't make ${.TARGET} with DESTDIR=/" @false .endif (cd ${.CURDIR} && ${MAKE} NOPOSTINSTALL=1 build) (cd ${.CURDIR}/etc && ${MAKE} INSTALL_DONE=1 distribution) .if defined(DESTDIR) && ${DESTDIR} != "" && ${DESTDIR} != "/" (cd ${.CURDIR}/distrib/sets && ${MAKE} checkflist) .endif @echo "make ${.TARGET} started at: ${START_TIME}" @printf "make ${.TARGET} finished at: " && date # # Install the distribution from $DESTDIR to $INSTALLWORLDDIR (defaults to `/') # If installing to /, ensures that the host's operating system is NetBSD and # the host's `uname -m` == ${MACHINE}. # HOST_UNAME_S!= uname -s HOST_UNAME_M!= uname -m installworld: .if (!defined(DESTDIR) || ${DESTDIR} == "" || ${DESTDIR} == "/") @echo "Can't make ${.TARGET} to DESTDIR=/" @false .endif .if !defined(INSTALLWORLDDIR) || \ ${INSTALLWORLDDIR} == "" || ${INSTALLWORLDDIR} == "/" .if (${HOST_UNAME_S} != "NetBSD") @echo "Won't cross-make ${.TARGET} from ${HOST_UNAME_S} to NetBSD with INSTALLWORLDDIR=/" @false .endif .if (${HOST_UNAME_M} != ${MACHINE}) @echo "Won't cross-make ${.TARGET} from ${HOST_UNAME_M} to ${MACHINE} with INSTALLWORLDDIR=/" @false .endif .endif (cd ${.CURDIR}/distrib/sets && \ ${MAKE} INSTALLDIR=${INSTALLWORLDDIR:U/} INSTALLSETS= installsets) (cd ${.CURDIR} && \ ${MAKE} DESTDIR=${INSTALLWORLDDIR} postinstall-check) @echo "make ${.TARGET} started at: ${START_TIME}" ) @echo "make ${.TARGET} started at: ${START_TIME}" @printf "make ${.TARGET} finished at: " && date # # Special components of the "make build" process. # check-tools: .if ${TOOLCHAIN_MISSING} == "yes" && !defined(EXTERNAL_TOOLCHAIN) @echo '*** WARNING: Building on MACHINE=${MACHINE} with missing toolchain.' @echo '*** May result in a failed build or corrupt binaries!' .elif defined(EXTERNAL_TOOLCHAIN) @echo '*** Using external toolchain rooted at ${EXTERNAL_TOOLCHAIN}.' targ in cleandir obj includes do-${targ}: ${targ} @true .endfor .for dir in tools lib/csu lib/libc lib gnu/lib do-${dir:S/\//-/}: .for targ in dependall install (cd ${.CURDIR}/${dir} && ${MAKE} ${targ}) .endfor .endfor do-ld.so: .for targ in dependall install .if (${OBJECT_FMT} == "a.out") (cd ${.CURDIR}/libexec/ld.aout_so && ${MAKE} ${targ}) .endif .if (${OBJECT_FMT} == "ELF") (cd ${.CURDIR}/libexec/ld.elf_so && ${MAKE} ${targ}) .endif # XXX many distrib subdirs need "cd etc && make snap_pre snap_kern" first... # dependall-distrib depend-distrib all-distrib: @true # # we don't want the obj target in etc invoked as part of the normal # course of events because that makes it too early. therefore, define # a neutral version of the target that bsd.subdir.mk would create. # obj-etc: @true .include <bsd.obj.mk> .include <bsd.subdir.mk> # # now, make a "real" target that will recurse into etc to enact the # obj target, and .USE it onto the end of the obj handling for the # current directory. note that this is only done if we already have # commands for the obj target (we won't if we're not making objdirs), # and only if etc is a target subdirectory. # .if commands(obj) && (${SUBDIR:Metc} == "etc") real-obj-etc: .USE @(echo "obj ===> etc"; \ cd ${.CURDIR}/etc && ${MAKE} obj) obj: real-obj-etc .endif build-docs: ${.CURDIR}/BUILDING ${.CURDIR}/BUILDING: doc/BUILDING.mdoc groff -mdoc -Tascii -P-b -P-u -P-o $> >$@ | http://cvsweb.netbsd.org/bsdweb.cgi/src/Makefile?rev=1.196&content-type=text/x-cvsweb-markup | CC-MAIN-2014-41 | refinedweb | 649 | 54.39 |
This may be perhaps the first time I’ve embraced an article from the Yale Environment 360 forum, the opener reads:
Environmentalists have long sought to use the threat of catastrophic global warming to persuade the public to embrace a low-carbon economy. But recent events, including the tainting of some climate research, have shown the risks of trying to link energy policy to climate science.
Al Gore’s latest book where he had to photoshop in some hurricanes comes to mind.
The NCDC sponsored climate change report where they photoshopped in a flooded house also comes to mind.
And, yes even the snowstorms reportedly caused by global warming this winter are also reminders of how common this bogus linkage to weather is.
From:
Green think tank tells environmentalists: Leave climate change science behind
By Ben Geman
Leaders of a contrarian environmental think tank, The Breakthrough Institute, have a way to get beyond the climate science wars: Break the link between global warming research and the push for low-carbon energy.
Ted Nordhaus and Michael Shellenberger, in a new essay in Yale Environment 360, [Titled: Freeing Energy Policy From The Climate Change Debate] argue that environmentalists are too eager to link natural disasters and dangerous weather to man-made climate change.
…
They.
…
The Yale Environment 360 website has a comments section below the articles. Look for a lively response to their new piece.
Have to agree Anthony, pretty level headed story. Sure wish more environmentalists were not so over the top and full of…………..HOT AIR
Sincerely,
John
Luboš Motl says:
Amen. Stop scaring the children!
There’s no reason for environmentalists to have any say on energy anyway, especially when they don’t know one thing about science and oppose nuclear. Our energy use has been decarbonising for generations as explained by many scientists and writers from Dr Patrick Moore to Michael Crichton.
Whenever environmentalists do get involved, it is to try to steal credit for what is happening anyway or to do the dirty work of western governments in persuading poor nations, especially black people, not to develop or to bribe the political elite of those nations to keep their people in a state of backwardness. They also purchase land for cheap in the name of conservation to prevent productive use of those lands, then after a while sell them on to favourable corporations.
Apart from Patrick Moore’s Greenspirit I can’t think of any environmental organisation which isn’t damn dirty.
I definitely agree. Energy conservation, sustainability, minimizing pollution, etc are good things, but the repeated tying of these things to global warming messes things up royally.
I was trying to explain how CAGW is, at best, a possible hypothesis that is doubtful and he countered with something like – well cutting back on fossil fuels is a good thing. Of course it is (my wife works in a lab working on alternative energy…I don’t know how he could think I didn’t realize this)! I tried to explain to him how the two are very different and shouldn’t be linked (CAGW demands immediate/crazy action, whereas sustainable solutions will likely creep slowly over decades), but I don’t know if he got it.
I’m glad more people are starting to discern between the two.
-Scott
I agree with the message of this particular essay. However, after reading the authors’ 2004 article, The Death Of Environmentalism, it appears they simply blow in the political winds. My kingdom for a progressive who is capable of critical thought.
Well if it smells like a duck, and sheds feathers like a duck; it’s a duck !
So what’s with this LOW CARBON ENERGY GIMMIC; if it is supposed to be divorced from “Climate Science” or “Climate Change”.
The very words LOW CARBON mean they haven’t got the message.
It isn’t the carbon;IT’S THE WATER; STUPID !
So let me understand, they were using climate change nee’ global warming merely as a ploy to get an environmentalist agenda through? In other words, THEY are not even certain whether it’s true, they were using it only to get their agenda through.
What next, the threat of cute polar bears starving to death?
Oh wait, they already used that one.
So, essentially: The fraud isn’t working, time to throw in the towel, and just admit the real motive..>…… an irrational hatred of hydrocarbon fuels…. oh, and a death wish to shut down all civilization.
… the first in a 12 step process?
“George E. Smith (16:55:28) :
[...]
It isn’t the carbon;IT’S THE WATER; STUPID !”
Yeah. We need a low water economy. Dewaterize the economy! No Evian for you.
must’ve been swallowed by the spam filter...
Interesting, they are going back to their original ‘green’ idea. But how will civilisation change to their will when there is no doom to avoid? Are these people a bunch of wingers that cannot accept that progress means destroying old ideas like the sun revolving around the earth or that the earth is flat. In order to make an omelette you must break some eggs – releasing a little bit of plant food into the atmosphere is a good thing :-)
Getting the most out of fossil fuels: Globlal Trade should mean exchange of goods for goods, not pure transfer of wealth at the greatest expenditure of energy.
Excessive importation is the epitomy of energy inefficiency. That stuff doesn’t travel on sailboats, it requires lots of bunker oil to get it here.
Internal transportation should rely most on rail, which is far more energy efficient than semi. It’s out-of-balance.
).
If you want clean, you have to regulate. (Personally, with clean i don’t mean CO2-free but other people have different ideas of clean; in both cases, the same applies: without regulation, no company will do it – it harms their competitiveness)
If one notes trends, one will observe that expanding energy use correlates to HUGELY expanding energy reserves.
(This is one case where correlation may indeed equal causation.)
We now have a climate caste system. The enlightened
progressives and their fear mongering minions.
This is fun; more popcorn please!
One might even ask if carbon-based energy use cannot be convincingly connected with AGW why there is a particularly pressing imperative to reduce use of carbon-based energy in the first place . . .
This is a major step in the right direction. I think the concept of the intertwining of advocacy & science has fired up many of the scientific types on this blog because the degradation of science in general was apparent. This is a good 1st step in separating politics & science & restoring the credibility of science.
To those who still seem offended by the term “low carbon” energy, it is perfectly acceptable to use that term & not imply a global warming link. The other way to interpret it is “high efficiency” energy (ie more work per btu is equivalent to more work per net carbon molecule). Higher efficiency is always better- both personally & societally – regardless of your personal politics.
Well the trouble with that Yale site is they don’t have somebody like Chasmod who is awake at the switch.
When it comes to placing a comment on that site; their moderator process is about as slow as postal chess.
If they ever post my short comment; it will be into its second or third half life.
[Hey! ~dbs, mod]
Uhmm, subtext reads, “change tactic” not common goal. There’s nothing wrong with “carbon free” energy. Except that it won’t happen in my lifetime nor yours. Neither, is there anything wrong with carbon based energy. Yes, we’ll probably run out, eventually. But, again, not in my lifetime nor yours, nor your children’s. I would like to say that I don’t understand the obsession with carbon based energy, but it seems clear to me, that there are too many humanists hell bent on taking humanity out of the human race. Like it or not, human progress and standard of living can still be measured in terms of carbon emissions. Call me strange, but I see upward movement in both as a good thing. Further, I see that the laws of energy/physics/nature still apply to mankind. As far as I know, we still cannot create energy. Find the “perpetual motion machine”, and we should all be living in a utopia soon. Until then, there’s no need to rush efficiency, it’s man’s nature to strive for it. It continually happens regardless of the tactic employed.
My take anyway.
Don’t ethanol and biodiesel have carbon in them … how does their use equate with a low carbon economy? And if we are able to synthesise transport fuel from hydrogen (produced from off-peak nuclear generated electricy) and CO, produced by pyrolysis of biomass, would that count as part of a low carbon economy.
Methinks, if they want to focus on alternative fuel sources – good idea. But they need to forget this nonsense about carbon.?”
Step 1: “Admitted we wanted the world to be powerless
—that we were trying to make everyone’s lives unmanageable….”
It’s a shame the environmental movement has been taken over by such a shoddy argument. There are plenty of real reasons to do many (not all) of the things the AGW preachers want us to do. If the whole environmental movement is discredited, bad things will result.
And then there’s this:
Don’t overreact; this doesn’t prove we’ll have a big recovery in the summer minimum, but it’s a nice start. The facts are “inconvenient” for the AGW faithful right now.
Predicting the end of the world always works well for a while. But when the world doesn’t end as predicted, the preacher’s following melts away.
evanmjones (17:29:45) : “…if carbon-based energy use cannot be convincingly connected with AGW why there is a particularly pressing imperative to reduce use of carbon-based energy in the first place . . .”
Good question. Answer: The United States has the largest reserves of coal in the entire world. China covets these reserves and would like to buy them at 5 cents on the dollar. OPEC would like to increase our dependence on foreign oil and gas. By making coal illegal, our enemies can ruin the US in one fell swoop. US allies (if there are any) will be over-run. Obama will bow.
Looks like the ‘greens’ are going into retreat.
We have plenty of fossil fuels for the foreseeable future and, if industry is left to it’s own devices, alternative sources of energy will be discovered and commercialised.
CAGW and ‘peak oil’ are both false memes.
“evanmjones (17:27:09) :
If one notes trends, one will observe that expanding energy use correlates to HUGELY expanding energy reserves.
(This is one case where correlation may indeed equal causation.)”
It surely does. Expanding energy use leads to a fall in reserves expressed in yearly consumption. This triggers a price rise and an increase in exploration activities and development of new technologies, making previously unviable reserves economically viable.
So is it finally time to put into the dustbin of history one of my pet peeve expressions ” carbon footprint ” ?
I will be happy never to hear that term again!
Lets face it, the truth is finally now out there, and the population are getting it. We have been scammed.
Too many people get caught up in the hype, including scientists and other professional folks, including journalists.
Think about it, the planet is 70 % water , 25 % desert ,mountain, ranges, and ice covered poles..Which leaves 5 % of the planet for all civilization, the most of which live along the coastal regions of the planet, including people , animals , and other aspects of all civilization. Lets also not forget that all of the earths inhabitants could easily fit in the smallest state in the USA. ( tight squeeze albiet ) . Doesn’t matter, it is just an example of how small we are.
The point is, man is an inconsequential presence on this planet. We have zero impact on its climate, but we do inpact local environments with pollution etc. That is something we can affect.
The Global footprint expression parlayed by many in the green movement ( including Al Gore gag me ) always left me with a sick feeling in my gut…….I knew it was wrong, and now finally I am proved right. Its time to put that puppy into historys dustbin.
Thanks for the opportunity to speak my piece.
Ian
ya, this is coming from the guy who said he invited the internet……….i call B.S.
look AL i see were u are going but its just not going to happen, and if it does i will personally kiss your ass……seriously im that confident that your theory is not just flawed but totally wrong. oh btw that volcano in Iceland……..u might want to throw that into the equation.
The other myth that has yet to be exposed, like AGW, is what our carbon based energy situation really is. Supposedly we are running out, while ridiculous alternatives like wind and solar are explored.
This is doubtful. Why?
First some background. The Oil industry is essentially a cartel. Opec is of course the visible face which is the producing cartel. However, they rely on the support and distrubution cartel (formerly called the 7 sisters, Exxon, BP, etc, otherwise known as Big Oil) to get their oil and gas from the ground to the consumer. In effect, the controlling cartel is not the producers, and they have a symbiotic relationship, and may be considered one and the same.
So all we know about reserves comes from this cartel. By claiming shortages, and dwindling reserves, and in effect ensuring supplies just meet demand, they ensure high prices (used to be 3 dollars a barrel 35 years ago) . There is interlocking directorships in Oil and Investment Banking (David Rockefeller says hi) so the financial arm helps drive market prices up with speculation in futures (they also make money shorting these futures when they bring prices down from unsustainable increases)
Big Oil (not using any specific company name) does not pay market price for oil, having entered into long term contracts with producers. However, their refineries pay market price. Profits get hidden in the tax havens (ever wonder why the tankers are registered in places like Pananama?). The off shore company where the tanker is registered buys the oil for say 50% of market price from the oil producer (who is dependent on them for hardware needed to get the oil from the ground, store it and ship it). Then sells it to the refinery in the US at somewhat less than market price (locking up the profits elsewhere, hence less tax in the US). US oil production is problematic in this regard.
In any event, 35 years ago we were supposed to be running out of oil globally, and today have reserves double what they were 35 years ago (of course consumption has also doubled).
One curious thing which proves my point that we have far more oil than Big Oil would like us to know is their obvious reluctance to search for oil in the US. Leased land goes undrilled. Some will mention environmental concerns inhibiting their ability to search for oil. Ask yourself this.
In the aftermath of 9/11, with Arab oil producing nations looked upon as a threat, and this country dependent on oil, not to mention our military which uses more oil than most countries, how could Bush and Cheney, Big Oils biggest buddies, not be able to open up the drilling, especially along the coast. Even if Congress would not go along (it was a Republican Congress), he could have used an Executive Order siting National Security concerns and he would have had the full support of most Americans. He didn’t. Why?
The answer is that Big Oil does not want to increase supplies. Things are doing very well as is thank you.
There is also Thomas Golds abiogenic theory of oil in the deep hot biosphere. He claims some oil wells thought to be depleted are being refilled (although not at the rate in which it was depleted), and that fossil fuels are not of biogenic orgins, but are upwelling from the deep earth, even in areas not thought to have oil do to the lack of sediments (just have to drill deeper). As an astro-physicist at NASA he claimed most planets have plenty of hydrocarbons, and that these compounds exist naturally throughout the universe from the beginning and did not require carbon based life to form them.
Obviously, nobody can prove this but Big Oil. The Russian scientists know, informing Thomas Gold that they developed this theory first, and have implemented their knowledge to increase Russian oil production despite having been thought to be running out of oil 20 years ago . They have no motivation to speak out publicly as this would depress oil prices, a commodity their economy depends on.
This takes us to nuclear energy. An accident at TMI that many say was sabotage cooled Americas interest in nuclear power. At the same time, double digit interest rates caused by the Fed, the banking industries lackey (remember the interlocking interests) made the financing cost for nuclear power plants so high the venture would be unprofitable. In addition, the US refusal to recycle spent nuclear power rods means waste is accumulating (recycle rates can be as high as 97% , and new generation power plants can use the spent power rods from older plants as is), and is used by environmentalists as the key argument against nuclear power.
Thus the biggest threat to Big Oil was removed. Since then, Big Oil through other companies and with the cooperation of the US and European nations and Australia have been acquiring land containing uranium oxide supplies and uranium enrichment plants. Once the cartel for this energy source is ready, there will be a push for nuclear power. Energy prices will of course be kept high since the supplier will be a cartel. In the meantime, those countries seeking to develop enrichment plants will meet with threats and sanctions.
The banking industry will be in a position to make a pile by loaning money to finance nuclear power plant development. This will probably happen when oil prices test 150 dollars a barrel again. Double digit inflation will likely be on the horizon, and the banks making such loans to these nations will need to be bailed out, and in return more resources from these nations will be promised to cover the loan in default. In the meantime, more loans will be available for them to buy oil if needed. Maybe at that time loans will be in the form of carbon credits and payments in carbon dollars.
Richard North,
The claim is that ethanol and biodiesel cause less carbon emissions than the equivalent natural hydrocarbons. Or… that they might eventually. The “cleaner” argument is much stronger when it isn’t focused on the carbon emissions but other emissions – the sulfur content is dramatically lower.
There are a variety of problems with the ‘lower carbon emissions’ position, some crippling. But they keep getting included in the environmentalists lists because the do have the virtue of being “sustainable”. (Or… nearly sustainable. A breakthrough or three on enzymatic of catalytic formation methods would be quite helpful to their argument.)
OT, but related to the eco-zealots desires, our “beloved” (10% approval rating) Congress is emboldened by illegally passing an illegal law to work on passing another illegal law based on this “science”. Here is the link.
This just shows that even with climategate, even with colder winters, even with the house of cards falling, and even with the discredited scientists, our Congress still doesn’t care about the true science, just political goals. You can write your representative 200 times a day and it won’t matter. It didn’t matter when people marched en masse at Washington. It didn’t matter when people called so often to their representative, the phone lines were overloaded. They still voted for a bill despite the will of their representatives. You should write anyway and tell them to back the truth by voting against any carbon tax. But it is clear how our Congress has become drunk with power. If carbon taxes passes, along with the implementation of the 2700+ page health care bill, this country will dream of having living conditions found in North Korea. (Obvious hyperbole.)
(By the way, federal health care controls are illegal because of the 10th Amendment to the US Constitution which prohibits the federal government from taking rights not specifically given to it in the Constitution. The idea is to concentrate power in the states. Managing health care or controlling CO2 emissions is not a power given to the federal government in the Constitution.).
Have you seen the many tax incentives to suppress any new innovation by keeping the current inefficient crap going?
Free markets want to sell more junk energy technology than look at anything that could really make power as it sells more parts and turbines and keeps the price of power high.
So stop scary stories for kids and focus on getting more energy and energy independence. Sounds like the right approach for our country with the highest fossil fuel reserves on the planet.
No? What, that’s not what he means?
I’m sorry, but I don’t see the objectivity of an essay who’s intent is still to de-carbonize our economy, and that the revenues raised would be solely used to develop low carbon industry. It looks like the Precautionary Principle, only now done without a basis to do so.
Clean energy as they described it includes reducing carbon.
Too bad the Green’s ideas for energy are just as wrong as their ideas on the climate.
We had windmills. We got rid of them. Why? Because they suck as a power source.
Solar is just as bad, probably worse because it’s even more expensive than wind.
“Green think tank tells environmentalists: Leave climate change science behind”
Wow. The first major crack from within.
P.S.
Here’s a link to a video showing an example of how truly God-awful the Green’s energy ideas are.
pft (17:59:37) :
Look at the USGS surveys. By the U.S’ own reports, we have more and more recoverable oil and natural gas, seemingly, every year, in this nation. That verifies your assertions except that the real information is out there, but no one cares to look. Given man’s natural propensity for efficiency in all things. There is absolutely no reason for any concern for us running out. (Natural gas, the coal derivative, is NOT a finite resource, but then, I don’t believe oil is either.)
I digress, money makers will continue to make money. It’s their nature. Of course, they feign shortage. Policy makers usurp power. It’s their nature. Our nature should be to ensure they don’t get too carried away. Sadly, too many of our ‘brotherhood of man’ are only too eager to believe people shouldn’t make money and the policy makers have our interests at heart. Liberty and freedoms, apparently are passe ideas.
Doug Badgero,
If “The Death of Environmentalism” is by the same guy I think it is – sorry I don’t have his name handy – he was the rising young star of the environmental movement when he wrote that… almost in a fit of rage about how unyielding, uncompromising, and ineffecive the Green Movement had become. He now works, of all places, with Wal Mart and is making potentially thousad of times more difference with them then he was “fighting the good fight”. If I recall I ran across him on an episode of Penn and Teller’s “BS” (real name of the show is Penn and Teller’s Bullshit but mods feel free to snip)
I was a Boy Scout when I was a kid and me favorite, albeit inconsistent, pastime is going to National Parks… hiking, and photographing nature. I cannot stand for the political advocacy and outright scam groups like the Sierra Club have become. I’d rather burn my money than let a cent of it go their way – they are not about nature, they are anti-humanity.
Kudos to these kids for realizing that reason trumps extremism, and that hitching their wagon to a f…. (not the four letter F-word but the five letter one) will only backfire in the end. I wish them all the best!
This article in this context is a health sign, but I find it confused in 2 ways.
Firstly, if we remove the (phoney) Climate Science argument for low-carbon economy, then why would we continue to work for low carbon economy? Their argument would make sense if it were saying that the CAGW argument should be abandoned as a way of persuade the public to embrace a shift to arenewable energy economy – and I would applaud that!
Secondly, they are too easy on the science advocates of catastrophic global warming when they say:
In 1981 Hansen was already telling the New York Times of 6 – 9F temp rises and 15-20 feet sea level rise in next century. As soon as the 1970s cooling was over, Schneider and Hansen pushed hard with the alarmism, against a background of disapproval from climate scientists still debating the net effect of human caused cooling (aerosol) and warming and all the complex uncertainties surrounding the assessment of these effects. In 1988 Hansen told congress he was 99% certain. These scientist alarmists only slowly won over the support of the environment movement during the course of the 1990s with alarmist rhetoric.
It was these scientists who used their apocalyptic senarios to capture the attention of the environmentalists, not the other way around. And it was these scientists who first characterize all resistance as corrupt (Big Oil), anti-scientific, short-sighted, or ignorant.
ENDGAME by Alex Jones investigates & attempts to join the dots & explain the powerful agendas behind CLIMATEGATE. Greens & Climate Scientists don’t have the power to orchestrate the UN, National Governments, Corporations, Banksters, Media & Science. [SNIP. Aargh! Post the "truther" (and worse) conspiracy theories elsewhere. We don't do those here! ~ Evan]
It is most recently being employed to demonise the truth & libertarian/tea party movements in the US.
Greens & Scientists were just the patsies for what our prime minister loves to refer to as the NEW WORLD ORDER.
Know your opponent. Join the dots. Take back your power. Love & Truth.
Translation-Let’s stop trying to justify inferior energy sources on their benefits to improving the weather, since they don’t, and start propounding their merits, which are non-existent.
Yeah, that’s the ticket.
“rickM (18:29:51) :
I’m sorry, but I don’t see the objectivity of an essay who’s intent is still to de-carbonize our economy, and that the revenues raised would be solely used to develop low carbon industry. ”
Maybe they are Malthusians and see limited resources as a principal problem. As i said, we would have at least 500 years to solve it but some people, especially people paid for, just want to rush it. The German solar industry has a very well-oiled (oops!) lobby, for instance.
evanmjones (17:29:45) :
One might even ask if carbon-based energy use cannot be convincingly connected with AGW why there is a particularly pressing imperative to reduce use of carbon-based energy in the first place . . .
………………………………………………………………………………………………
Class…….class……..I have an announcement:
today’s gold star for making the most sense goes to Evan M Jones.
DirkH (17:02:38) :
Yeah. We need a low water economy. Dewaterize the economy! No Evian for you.”
If you spell “Evian” backwards you get “naivE”. That’s what I consider environmentalists to be.
.”
Yeah but that does not help expand the government and destroy the middle class. No communism no deal.
–
Hm. Problem is that when you “Break the link between global warming research and the push for low-carbon energy,” there’s no reason to suffer the prohibitive costs of “low-carbon energy.”
The combustion of fossil and non-fossil hydrocarbons for the generation of energy obtains not because of collusion or conspiracy or corporate plotting, but because, ceteris paribus, it is the most cost-efficient way to power vehicles, drive railroad transport, fuel aircraft, and power commercial maritime and riverine shipping.
The “low-carbon energy” alternatives – except for light water moderated nuclear reactors in the generation of baseload electrical power – simply aren’t workable. Petrochemicals beat the hell out of everything else.
No global warming scare, no “low-carbon energy” requirement, and that leaves the ‘viros standing there in the street with their pudenda hanging out and no idea how to fumble their zippers up.
–
reuters has a piece on this, but only MSM coverage is NYT Blog. quite a big story really given who the traders are:
30 March: NYT Blog: James Kanter: HSBC Ejects Carbon Traders From Index.
Climate Exchange owns the European Climate Exchange, the Chicago Climate Exchange and the Chicago Climate Futures Exchange. The chairman of Trading Emissions, Neil Eckert, is also the chief executive of Climate Exchange….
the companies HSBC removed from the index had failed to reach the minimum market capitalization of $400 million..
You better sit down for this one….)
If they can convince people on the real merits then more power to them. Just don’t make crap up and – worst of all in my book – try and scare monger little kids with “ZOMG we’re all gonna die” scenarios that are at best worst case scenarios (at worst complete and intentional scams).
TBH, I don’t think it would even come close to working but hey, be honest about it. That I can support.
I have spent my whole working life in nuclear power. I can assure you that the accident at TMI was not sabotage. It was a combination of design deficiencies and operator error, as these things usually are, e.g. Exxon Valdez, etc. Also, since we generate essentially none of our electricity in the USA from oil, the expansion of nuclear will have little or no effect on our demand for oil.
Peak oil theory is idiotic The price of oil, or anything else, is largely determined by monetary policy, in particular the growth of the money supply. Money supply growth has been high since the beginnings of the housing crisis. All you have to do is look at the price of other commodities. Are we also running out of gold, silver, sugar, copper, etc?
[quote openunatedgirl (19:05:59) :]
Talk to any one from New Orleans.
[/quote]
Hurricane Katrina was a category 3 storm, which makes it middle of the road. Katrina was an unprecedented political failure, not an unprecedented natural force.
[quote openunatedgirl (19:05:59) :]
I am not claiming to know all the facts
[/quote]
Good thing, since your entire post is nothing more than repeating the gossip you’ve seen on TV. I simply don’t have the time to go through it and explain why you’re wrong on basically everything you say.
But if you want the public to be educated, start with yourself.
I guess the conclusions of this “Green Think tank is a kind of breakthrough but I simply don’t agree with the entire focus on a low carbon economy.
We simply need carbon fuels, not only to produce steel, aluminum, glass, concrete and other construction materials.
We need oil to produce plastics, clothing, pesticides, fertilizer, medicine, resins, paints, you name it.
For the current and next generation we don’t need to focus on energy at all and we certainly don’t need the climate gang on our shoulders meddling with the very basis of our economies.
Energy in fact is a non item because we have plenty of it.
We have cheap shale gas available to power highly efficient natural gas fueled power plants for a very long time.
We have plenty of oil available, we can generate gasoline from coal and sulfa free diesel from natural gas.
We already know how to handle and burn these fuels without negative effects for the environment and our health. We only need to apply those technologies world wide and further optimize efficiency.
Even if we don’t further optimize efficiency rates, there won’t be a peak oil situation for a long time.
We have all the time in the world available to further develop real innovating technologies that is not only able to replace fossil fuels, fulfill our energy needs, but also our need for raw materials and food production and help humanity through the onset of the next ice age.
The best way is to invest in new propulsion technology for space exploration and power generation.
In terms of time we are at the brink of real quantum jumps in development that are currently underway.
Future technology will enable us to manipulate matter on a molecular level and it will enable us to produce any material we need in any required quantity.
Power and energy will be a spin off of such a process so we will also have sufficient energy available for fresh water production from sea water where ever we need it and hydrogen for transportation.
Within a few decades from now we will look back and laugh about this period in time especially about those who are prepared to role back our civilization for individual profits, power and the desperate attempts to “save the planet” that needs no saving.
I see a bright future for all of us only threatened by wacko politicians, politicized science and a frightened public putting their trust and faith into the hands of the wrong people.
These folks have nothing better to do than stir up $#!t, in order to satisfy their own paranoia and greed. If they can’t do it in the political arena, they will do it in legal arena. Nuisance lawsuits such as those being brought (below) are the stock in trade. Of course their logic is absurd, since the end point of their argument would be that “man-made global warming” (by definition “man-made”) is the result of human existence and therefore everyone on the planet is guilty of being a public nuisance. I wonder if they could get a volume discount on lengthy stays at the Padded Walls Hotel if they went thru Orbitz?
Quote:.
jorgekafkazar (17:54:10) :
Yes, the Chinese and EU are getting our coal:
Who’s getting the best of that deal?
Scott (16:46:37) :
I definitely agree. Energy conservation, sustainability, minimizing pollution, etc are good things, but the repeated tying of these things to global warming messes things up royally.
I gotta disagree with you Scotta.
1. Energy conservation only makes sense in economic terms. Buying twisty bulbs is uneconomic given the light output and energy savings, over their lifetime.
2. Sustainability is unsustainable. The Earth, even the Solar system, is NOT sustainable. The Sun will grow to red Giant size in a few billion (5-15?) years time. It’s not even clear the universe is “sustainable”.
3. Minimize pollution is good, but only up to a point, and at what level is it pollution rather than natural environment. For example, it was good to get rid of the London smogs. But, there is a natural level of organic compounds in the atmosphere; or arsenic in lakes; or lead or uranium in the soil, or radon in the basement. It is folly to attempt to reduce “pollution” to, or even below, natural levels. Just because we can measure it to parts per billion and we know if we give mega-doses to rats for a year, they die, doesn’t make it pollution.
openunatedgirl (19:05:59) :
“You really want to challenge that we are ruining our environment? Really? Talk to any one from New Orleans. True, global warming was not the culprit there, but the rather the destroying of wetlands for profit.”
We were warned for two generations about what would happen in New Orleans if a major hurricane came ashore there. The levees were designed for a fast moving category 3 hurricane and Katrina was a slow moving storm. The city had to be constantly dewatered to keep it from flooding when it wasn’t even raining. Much of it is below sea level for goodness sake. Storm surge did not damage that city, flooding beyond the design capabilities of the levees did.
openunatedgirl,
Couldn’t agree more – and I think Anthony might say the same thing. Out of all the ways we could spend our time, effort and money regarding environmental issues… “decarbonization” of the economy might just be the absolute worst way we can spend it.
For me at least, I am not applauding their goals, just their apparent intent to have the conversation on honest terms.
And why are we having China build our clean-coal technology?
So much for those ‘green’ jobs.
openunatedgirl (19:05:59) :
New Orleans was built below sea level and the levees weren’t rebuilt – opposed by enviromentalists. Go drown in your crypto-socialist misanthropy.
I remember saying back in late November (and in this forum, I believe), that I give AGW another nine months of momentum. That was based on the time between Nixon’s “I am not a crook” speach and his resignation. This latest news , methinks, is right on schedule!
“openunatedgirl (19:05:59) :
[...]
To address the overall tone of this message board, I would like to say that I am completely depressed by the majority of your comments. You really want to challenge that we are ruining our environment? Really?”
You shouldn’t be that depressed, openunatedgirl. I’ve lived through the 70ies in Germany. We had lead paint, leaded gasoline, lots of carbon monoxide and SO2 from the smoke stacks, acid rain, all kinds of funny chemicals for cleaning and other purposes that have lots of C atoms forming funny rings, asbestos in the school buildings i learned in (funnily one day they were cordoned off), in the army i used a cleaning chemical on tanks that was verboten a few weeks later (cancer causing it was they found out after we had exhausted the stuff) and on and on and on it goes… Birds of prey were nearly extinct because DDT made their eggs crack more easily.
All these problems have been solved, long before any wind turbine or PC panel was erected. Car catalysts, prohibition of lead in paint and gasoline, prohibition of asbestos, DDT, desulfurisation of power plant chimney exhaust.
Nothing to do with renewable energy. Germany has become a rather clean country and the only awful smell you get in some places is when you’re downwind from a brewery. And that is probably not even toxic.
Just install some filters on your power plants and you should be done. If you don’t already have that. Doesn’t cost that much.
Monique (18:34:38) :
“Green think tank tells environmentalists: Leave climate change science behind”
Wow. The first major crack from within.
————————–
Reply:
Yup. Who’d want the albatros of “climate change science” around their neck? Now, not even the AGWers!
For the record, I agree with Poptech.
This quote….is worth repeating again….and again. The true CRUX of the matter.
.”
And it also has served to undermine legitimate environmental concerns, such as pollution, habitat destruction, and the disastrous overfishing of the world’s oceans.
One day soon…it will be a matter of historical record…as to the scam of CAGW and thus Al Gore…for the duration of his life…will never, EVER be taken seriously…again.
No loss! And good riddance!
Chris
Norfolk, VA, USA
“Greens pushed climate scientists….”
So Greens are now pushing their Trial Lawyers along with their EPA comrades and activist judges… they don’t need college kids anymore.
The day climategate happened they knew they lost the science battle, the day glaciergate happened and the world actually read IPCC AR4, they knew they lost their momentum and the battle for the worlds collective mindset.
So now they’re going to see if they can win the money battle. Watch out everyone, just when you least expect it, someone will walk up to you and say, “Smile, you’ve been sued by a Greenie!”
Maybe I was just agreeing to part of openunatedwhatshername.. on second read at least
The important part here is *oppurtunity cost*, for each dollar we spend on X we do not spend it on Y (unless, of course, the government has gone completely out of control and just printing money with no thought to its repurcussion… but that would never happen amirite? :P )
That’s what I was trying to get at. To reclaim the wetlands around New Orleans we’d need to shut down the dredged out deep shipping lanes of the Mississippi River – what effect do you think that might have? As others have pointed out, New Orelans had its own economic equation when it came to the levee system, which in hindsight was a complete miss. The wetlands had nothing to do with the storm surge overtaling the levee system through Lake Ponchetrain.
As DirkH mentioned, there are many *very* effective ways by which money can be spent on environmental issues… but they should be debated openly and honestly.
I see no breakthrough. All I see is certain folks distancing themselves from a theory they were only too happy to blindly embrace, defend and use to the max for their own ends until such time as that theory fell on hard times. I find it telling that these mental giants only began their retreat when it became clear that Ma and Pa Kettle were no longer buying that crap.
“NickB. (19:14:47) :)”
Probably you mean sulfate and black carbon particles. As i said in my comment to openunatedgirl, both can be filtered. The sulfur can be filtered with flue gas desulfurization, PM10 and other black carbon particles can be removed with catalysts. In Germany, Diesel is cheaper than gasoline due to less tax – don’t ask me why the tax is lower but it is so – that’s why german carmakers all have a lot of Diesel cars to offer. They now get equipped with catalysts that filter the carbon particles out and when the filter is full they burn the collected particles to CO2. I guess similar filters are used in power plants as these particles are cancerogenous, the smaller the worse.
We have a cogeneration plant near the city center of Braunschweig, my home town. All that you see coming from the smoke stack is some condensed water vapour. You get a little industry snow from it in winter. The plant runs on coal and gas, i think.
R. de Haan (19:17:07) :
Good post Ron.
magicjava (19:15:52) :
[quote openunatedgirl (19:05:59) :]
“Talk to any one from New Orleans.”
“Hurricane Katrina was a category 3 storm, which makes it middle of the road. Katrina was an unprecedented political failure, not an unprecedented natural force.”
I certainly agree about the unprecedented political failure part, magicjava. However, even though Katrina was technically downgraded to a three by the time it made landfall, it was no ordinary three.
It carried with it the energy (especially storm surge and battering wave action) of its recent past, as a strong category five.
The weaknesses of the Saffir-Simpson scale are coming to light. Case in point, in 2008, Ike was a technically a two when it hit Texas, but it carried with it the storm surge energy of a strong four. And the extreme damage on the Bolivar peninsula bears this out.
Also, back to Katrina, the person citing New Orleans was off, as you said, but more than the reason there was political and infrastructure failure in New Orleans. The REAL damage was to the east of New Orleans, on the Mississippi coast, which was obliterated by the worst storm surge since Camille (and in some cases worse) in 1969.
Chris
Norfolk, VA, USA
Quoting DirkH (17:26:25) :
“Actually, no. Energy companies would go for the cheapest energy, and that is hydrocarbons for at least the next 500 years or so (oil, coal, gas, and now huge amounts of shale gas becoming economical).”
Commenting:
First off, you have to be British to use such condescending phrases as “actually, no”. But I digress.
Natural Gas has always been the cleanest fuel of all. Now, we find that we can extract it directly from the gas bearing shale that everyone knew was the Source Rock of the gas they drilled in natural traps above said shale. They never thought they could extract that gas because the shale is impermeable. (i.e., it won’t give up the gas).
Now, with new technology, researched and developed at great (private) expense in North Texas, it is not only possible, but feasible and economical.?
encouraging:
29 March: BusinessGreen: James Murray: “Climategate” blow fragments corporate response to global warming
Survey reveals more than half of respondents believe “jury is still out” on the urgent need to tackle climate change
That is the conclusion of a major new survey from the Economist Intelligence Unit, which polled more than 540 senior executives…
The survey, which was sponsored by the Carbon Trust, IBM, Hitachi and software company 1E, found that just over half of respondents believe the “jury is still out” on the urgent need to tackle climate change, while 32 per cent of companies polled said they do not yet have a coherent strategy in place to address energy use, an increase of seven percentage points on last year.
Moreover, just 12 per cent of businesses said they were introducing new green products to keep up with rivals, and seven out of 10 respondents said that carbon reduction policies are primarily driven by public relations issues…
But report co-editor Chenoa Marquis said that the findings represented “good news for GE, Siemens and those companies that are moving ahead with low-carbon products as they have an opportunity to open up a gap on their competitors.”
Are you comforted by the “Yale to Greens” essay? I am not. The article can be summarized as; “the greens lied and global warming died”. Now that the “cats out of the bag” they say that we only did this to save the planet from carbon pollution. And we are to say, OK all’s forgiven. Not me. Their agenda is still clear and has been stated over and over. They want to create a new society that depends on governmental control, that is devoid of capitalistic ventures, and in which wealth is redistributed by taxing the rich. Oil and coal companies are obstacles to their destroying our free enterprise economy. Yet oil and coal are the only way wealth can be created in underdeveloped countries. The rich politicians want to control small countries by giving carbon credits to the leaders of small countries who will steal all the money from their poor. How does one justify trusting a group that collectively lied to us for 20 years by fabricating a global warming hoax that we are all going to die from exhaling a few parts per million of CO2 to the atmosphere and who are intentionally undermining the development of wealth in underdeveloped portions of the planet? Their “mea culpa” hides their real intensions to control the world’s economy. I won’t buy it!
“openunatedgirl (19:05:59) :
You really want to challenge that we are ruining our environment? Really? Talk to any one from New Orleans. True, global warming was not the culprit there, but the rather the destroying of wetlands for profit.”
Katrina was a category 3 storm. Most of the damage to property (Flooding, not wind) was largely due to poorly built and maintained levees, mostly it appears, in some of the poorest neighbourhoods there. The rest of the damage being attributed to climate change/environmental damage which was pure popaganda.
When you build a city below sea level, in a basin, on a flood plain and don’t maintain your defenses, nature will strike and win out in the end.
@Ian (17:57:31) notes that all of humanity could fit into our smallest state.
Yeah, but only in Manhattan-sized apartments. You could, however, put all of humanity into typical suburbia — dad, mom, 2.3 kids on a sixth of an acre — in an area roughly the size of Texas. It would never work, though; it’d be a couple of hundred miles to the nearest strip mall.
===
This whole “renewable energy” nonsense drives me up the wall. For nearly all of its history, humanity has depended on “renewable energy”; as a result, for example, the entire US east of the Mississippi was basically denuded of forest by the turn of the 20th century. The total remaining whitetail deer herd was estimated at the time at a quarter-million. Then the US went to a fossil-fuel economy and now the East is reforested (just look down while flying over it some time) and the states of Alabama, Wisconsin, and Michigan (the only ones I know off the top of my head) have deer herds of around three million EACH.
But now, of course, we have to fix that by devastating vast swaths of countryside and wildlife habitat with utterly useless turbine monstrosities, which generate nothing actually useful except subsidies and tax breaks for fat cats on Wall Street. Criminal lunacy.
Friends, we next have to save the environment from the environmentalists. Go figure.
I found the cogeneration plant in Braunschweig in the german wikipedia:
Link to various map services:¶ms=52.278611111111_N_10.514722222222_E_dim:1000_region:DE-NI_type:landmark_&title=Heizkraftwerk Braunschweig-Mitte
Link on google maps:
So you see, it’s not far from the city center.
The lefties will never pursue the energy angle, it is too obvious. Sure, for a short time they can claim an energy shortage, but most people will wonder why they don’t create more energy. The energy crisis didn’t work for Carter, it won’t work now. For their scheme to work, they must label the user of the energy as the problem. It’s politics.
For kicks and giggles I went to a “Green” precinct meeting once in the Minneapolis area (and believe me, this is a socialist state). There were about eight shaggy, unshaven individuals there – and they were the women. The Green’s don’t have the same political steam in America that they seem to have in Europe. I can’t see them having any substantial leverage with our Congress or with our culture for that matter. I’ll tell you what does though. The UN and the EU. The UN and the EU have strategically used global warming as the principle attack engine in its endless and relentless campaign for global socialism. It’s the same old bunch, Baby. The usual suspects and their intellectual surrogates in government, media and finance. AGW = social control.
“West Houston (20:19:12) :
[...]?”
I’m a Kraut, mein bester. I’m coming from Lower Saxony, i hear that we have a lot of shale here and i actually enjoy the prospect of some home-grown fossil fuel production.
When i said that industry by itself wouldn’t make energy production clean i had in mind the fact that flue gas desulfurization or filtering out black carbon simply adds cost. If you don’t force industry to install filters they won’t do it. That’s where environmental regulation makes sense, and that’s where lawmakers fulfill a useful role.
And i wish the US all the best with their own projects in this regard.
Robert of Ottawa (19:28:57) :
That type of move (lawsuit your recovery efforts into the dirt) is exactly the m.o. that has ruined much of California’s forests after fires. They go cherry-pick a judge and get an injunction to stop all salvage.
Lawsuiting energy and manufacturing in the US is their next planned move.
The have 3 test cases already in motion.
Pressed Rat: I’ve always wanted to ask, how does Minnesota believe in global warming? How is it possible for people in the coldest state believe that 1. the earth is warming and 2. it is better to be cold?
I am in Washington state and our experienced fraud team made a special trip to Minnesota to ensure that Al Franken is your senator, so I have much to apologize over.
Here’s the story on the ‘nuisance’ angle the Greens are going tort over:
Still don’t understand what they mean by “low carbon economy”. It’s as vague as “carbon emissions” or “carbon footprint”. I get the impression that in the popular imagination carbon is associated with blackness and dirt, a superficial take on the problem that has been encouraged by a plethora of clumsily Photoshopped images of water vapour belching from cooling towers and chimneys. Surely the aim of any development in prime movers (because that is essentially what we are talking about) from James Watt onwards has always been to obtain maximum efficiency. What has changed here? – Well the fact that over the last forty years or so this has been coupled to an increasing demand for the minimum of environmental contamination in the extraction and exploitation of energy sources and the treatment of waste. In all these fields it seems to me that there is still room for improvement and still the need to exercise constant vigilance. But judging by the changes I have seen in my lifetime we’re we’re well on the way towards achieving that goal.
“DirkH (20:47:22) :
[...]
And i wish the US all the best with their own projects in this regard.”
Not to be misunderstood: The best of luck for the shale projects, not for Cap&Trade “projects” which i find rather detrimental.
I object to the use of environmentalists when the correct term is AGWer or the neutral climate concerned. Many environmentalists, especially those old enough to have sought an energy transformation since before climate became an issue, hold contrarian views on climate. Many of us believe the focus on CO2 is actually hindering that transformation.
Re green energy (carbon-less) and carbon-based energy, this might be of interest.
The short version is that OPEC is not going to let oil become sufficiently expensive for alternatives to oil to become economic.
pft:
Further to your oil cartel comment, look what happens to people who were off the grid for their natural gas. The Ontario government shut down a small natural gas well dug in 1931, and being privately operated by an elderly Ontario couple to heat their house (and formerly 3 neighbours’ houses too) ostensibly for health and safety reasons. The couple was forced to pay to have the well capped (to the tune of at least $15,000) out of their private savings.
See
Governments are definitely part of the energy cartel. Anyone who thinks, in this day of global conglomerates, that either privatization OR nationalization of energy will solve the problem of the little people being squeezed for all we’ve got has got bats in his or her belfry. N.B. the last observation is just a general comment, not a response to anybody here. Nor are any of these organizations truly interested in developing more efficient means to utilize energy, so long as there is money to be made the old fashioned way.
What I’ve found most infuriating about the green eco-fascists is their eagerness to help the governments and energy cartels drive up the cost of energy, with no regard to the suffering this will cause many ordinary people, and especially the poor. If only they would be hoist by their own petard on this! But even more infuriating is how many people in urban centres seem to think that raising the price of gas and oil will be just fine – they’ll just continue to ride their bikes and take the subway thank you very much. For the rest of us wood stoves will be the answer to home heating (that’ll put paid to the greenhouse gas problem, eh?), if the ‘green’ scenario comes to pass, but won’t solve the problem of high food and commodity prices. Yikes!
Nordhaus and Shellenberger: “In recent years, bipartisan agreement has grown on the need to decarbonize our energy supply through the expansion of renewables, nuclear power, and natural gas. . .”
Last I heard, natural gas was made of carbon and hydrogen, and when burned produces CO2 and H2O. So you won’t ‘decarbonize’ our economy by using it.
But so what? If not for putative ‘climate change’, why do the greens want to ‘decarbonize’ the economy at all? It is nice to see these two authors admitting that the alarmist warnings of dire catastrophes from imminent ‘global warming’ caused by CO2 are so much poppycock. Clearly they are admitting that most of this vaunted ‘climate science’ was not science at all, but scientism in the service of a political agenda.
Is that agenda the ‘decarbonization’ of the economy? Or is that aim really an excuse for something else, something having to do with control, with an end to the values that have driven our civilization to ever-new heights of prosperity, abundance, and freedom?
Having them retreat from the alarmist tactic is a battle worth winning, and certainly worth posting here. But it’s not winning the war, not yet.
We’ll win when they throw in the towel and admit, ‘carbon’ is good and vital for the continued progress of mankind.
/Mr Lynn
“Greens pushed climate scientists to become outspoken advocates,,, some climate scientists attempted to oblige. The result is that the use, and misuse, of climate science by advocates began to wash back into the science itself”
“the use, and misuse, of climate science by advocates”?
Let’s get to it.
We have been witnessing crimes.
Publicly funded elected officials, bureaucrats and academia, (independently and in many cases in chorus) have been deliberately distorting and fabricating science to advance their causes and self interests.
Their agendas, their careers, their positions and salaries, their departments and institutions all stood to gain and did benefit from their deceit.
It wasn’t non-criminal cheerleading or innocent worry and confusion.
It is calculated and the fraud is still underway.
I have no doubt their are millions of people around the globe who are angered by the deceit and will demand consequences for the perpetrators.
AND,,, CO2 emissions are not pollution and we need the abundant supplies of coal, oil and natural gas for decades to come.
@DirkH (17:26:25) :
).
- – - – - – -
Dirk, you’re only half right. Your figure of 500 years is easily off by more than factor of 10 (I initially thought that “500 years” was a typo, but you repeated that figure again in a later post, so I guess not)..)
One example of an alternative energy scheme which is already less expensive than hydrocarbon fuels is passive solar. I was involved with passive solar energy research almost 30 years ago. People have been utilizing passive solar heating ( I use it myself as an auxiliary), at less than 1/10th the cost of heating with natural gas, heating oil or electricity. Granted passive solar is not a panacea, but it is also acutely under-utilized.
The efficiency of solar panels continues to increase, and the price will continue to decrease as economies of scale begin to affect the price, but that’s a few decades off into the future. If wind turbine manufacturers would get their act together and shift their model to microgeneration, the wind energy industry will thrive. There are numerous alternative energy souces being researched. One is here:
Another is a solid hydrogen fuel:
“The US Air Force finances a project using ammonia borane (H3NBH3) to pack hydrogen gas for using it in fuel cells
. Jadoo Power Systems was given a contract this week to develop ammonia borane pellets for hydrogen generation.”
What every person on the planet should know!
Access to cheap and safe energy should be a human right!
1. Anthropogenic Global Warming or Climate Change is a political induced scam!
CO2 is not a climate driver, temperatures show no significant up or down trend.
Much warmer periods have happened before and each of them saw the rise of great civilizations.
The past ten thousand years we saw the Minoan, the Roman and the Medieval warmth period when it was much warmer than today and the Little Ice Age with much lower temperatures that happened without our current CO2 emissions.
Warming never has been a problem, what we must fear is cold!
See:
The science behind AGW/Climate Change presented by the United Nations IPCC AR-4 report is corrupted! and everything that has been told about melting ice caps and rising sea levels is a lie. and
2. The potential and the benefits of the so called “Green Renewable Energy”, wind, solar and bio fuels is hyped!
It is relative expensive, it can’t deliver the promised output we need to maintain a healthy economy and it certainly can’t replace coal oil and gas.
Bio fuels in terms of land use and prize compete with food production and topical forests (palm oil) promoting famine in the Third World and destruction of our remaining tropical forest.
Bio fuels also consume large amounts of water.
Production requires considerable amounts of fossil fuel.
That’s why renewable fuels and energy at the current level of development are at best niche market solution.
Most Green Renewable Energy is not “Green” at all!
3. The demonizing of carbon fuels is a foolish!
Fossil fuels can be burned safe without harmful emissions.
CO2 is the gas of life, it makes plants and algae grow and it is certainly not a dangerous pollutant.
Without fossil fuels we can not maintain high yield harvests to feed the world
(1 unit of food takes 4 units of oil to produce!), no medicine, no fertilizers, no pesticides, no plastics, no transport and distribution, no steel, no aluminum, no glass, no clothing, paints, resins and no wind mills or solar panels.
To demonize fossil fuels is not only dangerous, it is also plain stupid!
Without fossil fuels our current civilization, standard of living and life expectancy would not be possible.
4. Peak Oil is an illusion!
Oil Companies and the big banks manipulate oil prices based on the popular notion that we are at the end of the oil age and stocks are running low!
This is not the case and current stocks will serve generations to come.
Socialist Governments and the United Nations (IPCC AR-4) use the Peak Oil argument in support of their “Green Agenda”
Their policy is to tax the CO2 emissions released by burning fossil fuels and deny the Third World the opportunity of development.
This is pure fraud.
5. Cheap energy is now available for all of humanity as energy dependence and peak oil NO LONGER EXIST!
THIS CHEAP ENERGY SOURCE IS SHALE GAS AND IT IS FOUND IN ABUNDANCE ALL OVER THE WORLD IN 75% OF THE WORLDS SEDIMENTS!!!!!!!!!!
Shale gas is a clean burning fuel suitable for high efficiency gas power plants to generate cheap electricity, to heat our homes, offices and factories and power trucks, trains and busses.
Some US producers have declared they can make a profit at $1 MMBTU or below, especially considering how close new supplies are to population centers.
This is not only important for the USA where shale gas extraction was invented and immense deposits will serve several generations but it is also important for Europe and especially for the Third World because they now have the opportunity to develop efficient and affordable electrical grids, key for any economic development.
Is Shale gas a peace maker?
On a geopolitical level shale gas is a major game changer as it eliminates potential conflict between Nations over energy resources and makes countries and populations free and independent.
All people have to fear is Government Control and propaganda based rule that limits or even denies access to cheap energy in pursuit of Global Power and Domination.
Governments currently pose the biggest threat to our freedom, prosperity and future as they no longer support the vital interests of their populations.
This goes for all current Governments in power, especially the EU Government and her Member States, the US Obama Administration, the Government of Canada, Australia, New Sealand and Japan and all other Nations that signed the United Nations Copenhagen Accord and the United Nations Chapter 21. See: http//green-agenda.com
This in short is the message that has to go out now.
Energy independence for generations to come and the technology to secure it is the real revolution of our time threatened only by “LACK OF INFORMATION”.
Only elect those politicians who support this vision and reject deny any power or support to any politician, Government or policy that intends you to think otherwise or takes advantage of the fact that we live on a carbon planet, with a carbon based life cycle and a carbon fueled society.
I have to disagree Mr. Watts.
Their goal is still to remake the “entire global energy economy.” They only claim that they can’t do it with the soft climate science any longer. They still want to send us back to the caves.
I wish I was as smart as they are. I wonder if they are as smart as Mao and Stalin, their heros. Get ready to slaughter another hundred million souls, in your name, if they are.
I wish I could dictate the perfect solution, legislate that the Earth will be at the perfect temperature, like they can. Are we to believe that if we cut our carbon emissions there will be no more bad weather? Obama oversaw the worst winter in decades on the east coast. I thought he could control the weather, or have we not done enough to limit our carbon footprint?
Their stated mission remains to decarbonize the blah, blah blah to save us from ourselves.
If we decarbonize like they want us to, we trash all of our fridges, microwaves, stoves, cars, computers, cell phones and light bulbs.
These environmentalists have realized they can’t waste any more time trying to justify their goals with climate science because it is viewed as fraudulent.
What will be the new threat? Meat diets? Dairy products? Ocean acidification? Tundra thaw? Future famine due to droughts and floods? The next doomsday scenario will rear its ugly head very soon, I am sure.
I hope to debate a young Yale environmental evangelist someday.
EJ
Refreshing news.
Now maybe we can get some greens back to doing REAL green things (instead of FAKE climate-catastrophe nonsense)?
Recently a major commercial development was permitted in a public park locally. Years ago there would have been a massive protest, but it seems none of the greens give a sh*t about parks & trees anymore – they just want to run around freaking out about FAKE climate “problems”.
Shame on you fake greens. Protect the parks & natural forests and oppose toxic pollution. Stop wasting your time misrepresenting nature — natural climate variations are a part of nature – show some respect for nature.
Paul Vaughan,
Ecologist, Parks & Natural Forests Advocate
I have to agree with what a lot of other commenters already said. The article is very clear that the climate propoganda has discredited itself, and thus “new” reasons for a “low carbon” economy must be found:
————-
understood in its proper role, as one of many reasons why we should decarbonize the global economy, climate science can even help contribute to the case for taking such action.
————-
They don’t say what those “many reasons” are, and the wording suggests that they simply assume that “high carbon” is bad and should be obvious to everyone that it is. Here lies the ultimate fallacy that somehow a return to “simpler times” and a less industrialized economy is “obviously” better than what we have now. Having read a thing or two about history, this doesn’t seem that obvious to me.
Yes, shale assures that the world will never, ever run out of (or even remotely short of) fossil fuels. It’s purely a matter of cost of extraction, a cost which dramatically declines in the face of hands-on experience and technological progress.
The AGW advocates may be wrong, but we would have to plunge into the heart of the next glacial period in the next five years for them to be as wrong as the Club of Rome (and the various other resource panicmongers). It’s very, very difficult to be as sublimely wrong as the Club of Rome.
Global warming is mere exaggeration and irresponsible, uninformed, damaging speculation. But the Resource Scarcity premise is the third biggest lie in history.
(Number two is that the rich get richer and the poor get poorer, and number one is that wars never solve anything.) But, then, any honest liberal knows that. (Well, half a brain also required.)
Thatcher, while not the mother of AGW, was certainly the wet nurse. I admire the Iron Lady but she did a lot of damage in her madcap scheme to disembowel the coal mining unions and promote nuclear power. The rest of Europe climbed on board because, jealous of America’s strength based on free enterprise and cheap carbon energy, they saw their chance to take her down. Canada and the US should be standing shoulder to shoulder to push back on AGW nonsense. Instead, Obama starting drinking the kool-aid and appears set to help Europe push America down the same dead-end path of socialism. I had such high hopes for him but now I’m somewhere between alarmed and disillusioned.
EJ: EJ (21:33:32) : “What will be the new threat? Meat diets? Dairy products? Ocean acidification? Tundra thaw? Future famine due to droughts and floods? The next doomsday scenario will rear its ugly head very soon, I am sure.
It already has: Ocean Acidification.
As a close half-sister to the CO2 scare, this one follows the same farudulent premise: Reduce manmade CO2 or the world will end.
Unfortunately, sham policies based upon scientific scams [ the spuedo-religion of CAGW] does nothing whatsoever to advance cleaning up the Earth from man-made pollution, habitat destruction, and overfishing.
Rather…it throws all of of those legitimate concerns, under the bus.
Where was Al Gore when he could have spoken up for the wholesale elimination of large sharks in the world’s oceans who have ruled the deep for hundreds of millions of years?
Where was Al Gore when he could have championed finding a solution to the disastrous gigantic Pacific trash gyre?
Where is Al Gore speaking up for 1/4 of the world’s population who does not have electricity, and their chances are even more dire now given that hydrocarbons have been demonized by he and Hansen and others?
The world’s first poised carbon billionaire was conveniently silent…because he KNEW he could not make any money on any of the foregoing.
It is for THAT reason, and for the millions of third world women and children who will die due to some “green” experiment gone bad, that Al Gore’s name will always be a well-deserved curse word on my lips!
Chris
Norfolk, VA, USA
Paul Vaughan (22:07:36) :
I could not agree with you more, Paul.
Chris
Norfolk, VA, USA
The more I think about it…the more I see red…and lightning bolts start to shoot from my eyes:
Al Gore [forgive me but he really is culpable here] can not make money on real and legitimate environmental causes…so, curiously, you never hear him using his platform to speak out on such.
But he CAN make a lot of money…on telling and propagating a lie and a fraud.
That is royally *****d up!
Chris
Norfolk, VA, USA
Any fool knows that the so called “Climate Scientists” need their funding cut, and the key cards disabled.
However, I am all for Sensible Science developing new energy forms and conservation.
I am not for 66 year paybacks as unsubsidized PV systems require – and of course the maximum panel life is 20-30 years – and Anything that requires a subsidy is non-economic.
Insulation, Orientation, Thermal Mass, Daylighting, Stack Ventilation, Sensible Planning, Xeriscape, Telecommuting, etc., and more CO2 (for the plants)
Correction on “spuedo-religion of CAGW”. Meant “pseudo-religion of CAGW”
UGH….I write too fast. Fire that editor [me].
“Where was Al Gore when he could have spoken up for the wholesale elimination of large sharks in the world’s oceans who have ruled the deep for hundreds of millions of years?”
SHOULD have said:
Where was Al Gore when he could have spoken up AGAINST the wholesale elimination of large sharks, who have ruled the deep for hundreds of millions of years, in the world’s oceans?
Sorry for having to keep correcting.
To err is human.
And IPCC.
Marlene Anderson
Canada and the US should be standing shoulder to shoulder to push back on AGW nonsense. Instead, Obama starting drinking the kool-aid>>
Canada will stand “shoulder to shoulder” with the US, only in that our economy is so intertwined with the US that we must adopt the same basic regulations or see our products stopped at the boarder. That said, Obama and Clinton seem more interested in slapping allies like Canada around while apologising to and appeasing enemies. A lot of Canadians were swept up in Obamamania. I wonder how they will feel about being p****ed on for trying to get a converation going between the countries that border the arctic on how to administer it:
The arrogance of being told how we should be dealing with our native peoples (the US having such a stirling record on that), and being told that countries like China and India and others who don’t border on the Arctic should have had a seat at the meeting? Is that the whole list now Hillary? Are you sure you don’t want Al Queda invited too, they’be been complaining about climate change as well. How about Khadaffy and Chavez while we’re at it? Ar are you just ticked that some tiny insignificant country actually took a leadership position on something without you? I thought that the end of the Bush era was no more bullying the planet. Well turns out that meant no more bullying enemies, just allies instead.
The Yale article shows more than it states by its context to a broader issue that surrounds it.
NOTE-doing this on my Blackberry so spell & grammar checking is out the window : )
1) The part of world that is modern is energy intensive.
2) The more wealthy societies in the modern world are the most free.
3) Within that wealth and freedom exist the ability to have a greater ability to promote imtellectual systems (ideaologies).
4) Not all of those ideaologies are compatible with sustaining the production of energy or the freedom.
5) The militant/political green ideaology (activist environmentalism) is one of those that are not compatible with the energetic modern free societies.
6) The more commonsense individualistic approach to living-in-a-healthy-place is compatible with the energetic modern free societies.
7) A tactical retreat by militant/political green ideaology as shown in the Yale is not a strategic defeat for them.
8) Stay vigilant
The more important topic of what is the basis of the militant/political green ideaology is another topic. It is a very important & intriging topic.
John
I still laugh everytime I see that southern hemisphere cyclone off the coast of Mexico on the cover of Al’s book. It’s all about marketing. The science be damned!
Anthony,
I welcome your acknowledgement of this issue and this first signal of open mindedness. I hope you can take it forward.
Best.
You know the tide has turned when President Clinton made jokes about it.
Tide turned you note. Not tide fully in.
What a breath of fresh air! But I strongly doubt that Obama would pay any attention to it..
davidmhoffer (23:06:26) :
David, you forgot Robert Mugabe.
I think this post remind us why this solar minimum should be called “The Gored Minimum”. If it develops.
Because 40 years from now no one will remember the AGW scam. Just like almost everyone today have forgotten the Ice Age scam of the seventhies. (except a few)
But “The Gored Minimum” ….will forever remind the coming genererations about that one man who was such a clever advocate for the AGW scam.
@ pft:
One very good reason the US does not look for oil in the US is that it is foolish to use up a resource when it will only get more expensive. Use the resource as sold by others while it is cheap – when it is expensive, develop your own resource potential to cover local demand, and even make a profit of those with less foresight.
It is what I would do, and as I understand from my father’s girlfriend who has a well in Texas (as many there do), the govt puts strict limits on production in the US. It makes sound economic sense to me.
openunatedgirl (19:05:59) :
Certainly there are problems caused by our abuse of the environment, and even our foolish town planning and useless response to emergencies.
Unfortunately the current misplaced obsession with demonising CO2 is causing most environmental efforts to be misdirected to preventing the addition of just one more molecule of CO2 for every 10,000 molecules of air.
We can address real issues properly and move to a renewable energy cycle, without crippling the western world’s economy, and without imposing massive restrictions on developing counties and enforcing continued poverty on them. But we can only do this if we accept that burning fossil fuels has not changed anything perceptibly, and probably will not in the future, and certainly not more than we can cope with given the expected state of our technology in half a century (assuming we don’t cripple our economy, etc, etc, etc).
Well, I guess it’s time to put these out there again:
We have a functionally unlimited supply of ALREADY DEVELOPED energy technologies. All that matters is what is cheapest and how stupid the various governments can be.
We run out of energy when there are no longer eroding mountains on the earth and the oceans are gone:
And we never run out of resources to use to make things:
The comment about The Club Of Rome being very wrong is “spot on”. The Club Of Rome “running out panic” is horridly and spectacularly wrong. I’ve also seen references that assert they are among the early folks pushing the AGW broken meme as well.
The reality is that we have no need to “conserve” resources. We ought to conserve species and forests as they can be extinguished, but things like copper and iron don’t leave the planet and things like coal just turn into CO2 that goes into limestone that gets cooked back into oil per one of the demonstrated abiotic oil chemical pathways.
So yes, we ought to clean up the trash (it is the treasure from which we can recover resources, like oil and copper) and keep crap out of the air. But ‘decarbonizing’ makes about as much sense as ‘dewatering’ your bathroom or ‘defooding’ your kitchen. I’m all for efficiency improvements where it makes sense, but mandating that I put a mercury filled device prone to breakage in food preparation areas is just crazy. Especially when we have at least 10,000 years of proven energy supply at low costs.
DirkH (19:35:20) :
‘Ere! There is nothing wrong with the smell from a brewery! All of the smells are awesome, even the heavy yeasty one. An in Germany the laws dictate no chemicals too, so it will definitely not be toxic! Drinking it is, of course, but it is enjoyable, so that’s OK.
For gods’ sake, don’t tell the greenies about the CO2 produced or they’ll tax or ban the stuff!
(speaking as an ex-brewer and current full-time amateur ‘quality control officer’)
More than thirty years ago I was convinced that looking after the global environment was what the Green movement was all about and I approved of the movement in general terms. Then I noticed that various individuals of my acquaintance who had joined Green organisations were beginning to display many of the slightly odd mannerisms of other old acquaintances who had become Charismatic Christians.
It was no great cognitive leap to realise the Green movement had, sadly, become a religion and one that was seeking world domination. I put them to one side, in my mind, until Climategate arrived and my personal bull**** detector went into full alert mode. I am grateful that I was steered to this site in my search for information and I am cheered that this group from Yale are at least beginning to distance themselves from CAGW, CC or any of the permutations of doom. But in their pursuit of ‘low carbon energy’ they have missed the very relevant fact that Man continually refines technology; as an example, in the late 1950s I owned a 650cc 4stroke British motorcycle which was grossly unreliable, drank copious quantities of petrol and oil and was generally an exciting beast. My son now rides, among other machines, a 1200cc Yamaha which uses a fraction of the petrol my old 500cc bike did, uses no oil between services and is not only utterly reliable but is increadibly fast compared with my old beast. And sounds about as exciting as a sewing machine. The error many who are clueless about machinery of any kind is that they do not realise just how powerful and dramatic changes in established technology and machinery can be; most Greens shudder when they see a fast car, but Porsche is one manufacturer which has refined current design to the point where they now have built a very fast sports car which uses a fraction of the energy that a Toyota Prius does and yet the Prius with it’s enormous carbon footprint (silly term, I know, but the Greens love their mantras) will no doubt remain a religious icon to the Green movement..
Sorry for a typo; I have referred to the same bike as both 650cc and 500cc – it was a 650cc machine, in fact. And despite its myriad faults, I loved it with a passion only other enthusiasts can understand!
””””Kate (01:29:35) :.”””””’
Kate,
Your excellent points I concur with, but your tone I think should be more hopeful.
Not only do politicians have long memories, the blogosphere has even longer memories . . . . . . and there are a hell of a lot more of us. : ) And people like Watts, M & M, etc etc, too numberous to mention here.
Cheer up.
John
“in the late 1950s I owned a 650cc 4stroke British motorcycle which was grossly unreliable, drank copious quantities of petrol and oil and was generally an exciting beast.” Twenty bucks says it was a Norton Commando. Was my favorite machine also. When it ran.
Point of clarification: Let’s not make the mistake that the socialists do with ‘healthcare’: access to goods and services produced by others is never a ‘right’. It may be eminently desirable, a wish devoutly to be achieved, but not a right.
“True rights,” says Walter E. Williams, “such as those in our Constitution, or those considered to be natural or human rights, exist simultaneously among people. That means exercise of a right by one person does not diminish those held by another.” The government cannot provide goods and services as ‘rights’, because the government has no resources of its own; it must first take in order to give. See Prof. Williams’s illuminating essay here:
That said, the rest of R. de Haan’s contribution is right on the money! I recommend you all print it out and post it prominently for all the alarmists, warmers, doomsayers, Luddites, Marxists, and faux-environmentalists to see and contemplate.
And also read and re-read E.M.Smith’s (03:20:24) seminal “There is no shortage. . .” posts, linked in his comment above.
/Mr Lynn
Come on all you well meaning green folk — there are real problems to address before you lose all your credibility: how about the pollution of the oceans and the depletion of the global fisheries, for example?
I am not sure if this will work. AGW theory has cost many billions in direct and indirect costs, and an accounting should be demanded.
AGW true believers dearly love their apocalypse, and actually believe.
AGW profiteers, like Gore, windmill salesmen, and the industrial groups pushing for cap-n-trade smell trillions in trading revenues.
This is not going to go away easily.
And promoting the idea that non-carbon based energy will work without nuke power is a delusion.
All the talk about wind and solar replacing conventional sources because economy of scale will make those technologies’ economically viable in the future is pure fantasy. The numbers cannot possibly EVER pencil out because of horrendous capital cost that can never be brought to heel due to:
1) Pathetic energy density. It simply requires too much manufactured hardware to product too few kilowatts, even if you assume absurdly optimistic conversion efficiency.
2) Pitiful capacity factor. All that hardware lies idle “when the sun don’t shine and the wind don’t blow”.
3) Huge power plant footprint. As a result of the pathetic energy density, wind and solar have an enormous physical footprint that makes them all but impossible to thread through the U.S. environmental review process where many of the same folks who say they want renewables stand waiting to stop it. T. Boon Pickenss learned this one the hard way; think “Texas Prairie Chickens”.
Do they still count as a think tank when their conclusion is a decade late and patently obvious?
I’m going to start a real estate think tank and issue a report that states that federally fueled real estate speculation is a bad idea.
This is just more of stage 3 in the grief process (a la Judith Curry); bargaining. They’re essentially saying, “see, we’re willing to throw the greenies under the bus, for mucking things up, so please let us CAGW/CC PNS “scientists” continue, OK?” Well, sorry, but no, it’s not OK. It’s way, way past too late. That ship has sailed and reached another continent. The damage is done, and the “climate wars” will continue. This fight is far from over. The fat lady hasn’t even begun to warm up her pipes.
First of all I agree with those who regard the Yale Environment 360 article positively. For too long here has been a concerted effort to link every environmental ill to climate change. (A recent link was between whaling and CO2 emissions). The downside has been that many urgent dangers, hunting, habitat encroachment, etc. have been ignored. There are also good reasons for the long-term future of the planet to develop safe renewable energy sources. The next ice is due in a few centuries time; imagine trying to survive if we’d all used our fossil fuels for long-haul holidays.
openunatedgirl
My understanding is that for the US or Europe to replace 10% of its petrol with ethanol would require 40% of its agricultural land. If these facts are correct then biofuel can only be a small part of the solution.
If we could just divert all this “greenie” energy into building another set of pyramids out in the desert somewhere… all done with hand labor, all funded by their own pockets with no outside contributions whatsoever, and all workers fed with their own organic gardens, maybe we’d be able to contain the envionmental hysteria gripping the gullible masses for the next 40 years.
Just a fanciful wish.
“toyotawhizguy (21:24:04) :
[...]
Dirk, you’re only half right. Your figure of 500 years is easily off by more than factor of 10 (I initially thought that “500 years” was a typo, but you repeated that figure again in a later post, so I guess not)”
You *could* be right. I was thinking about known reserves here. As soon as some other technology is cheaper it will overtake the market. But it needs to become cheaper first! This is more difficult than it seems to be – as Roger Sowell points out, the guys with the oil wells will try to counter any pretender technology by lowering their prizes. Their technology is proven, they can exploit a huge existing infrastructure and economies of scale.
A lot of the shiny new technologies will fall by the wayside.
I (and a lot of other people) place my bet on microcogeneration in individual households, using gas as the fuel (synthesized from wind/solar power if you want or the fossil variant), a fuel cell, producing heat and electricity.
Hydrocarbons are just the best way to carry hydrogene with you.
I’ve commented before on this website, mostly at the very start of Climategate regarding the legal aspects of the FOIL applications. I’ve had 40+ years of interest in climate and technology, but I do not have a professional technical backround, so I read WUWT far more than I comment. But 2 things about this article and the comments. First, the Skeptics have won the debate; CO2 is not proven to be a “climate changer” and it probably is NOT a material climate forcing– this article shows how the AGW true believers are eating their own and using new propaganda. Second, 2 commenters to this article show the stark philosophical difference between Skeptics and AGW true believers– openunated girl and DirkH. ‘Girl’ feels like we should get rid of evil carbon and ‘those evil corporations’ should be forced to do, but since she’s true believer, she assumes no consequences for herself, because in her rainbow and unicorn AGW world, cheap endless wind power will work for her if those evil corporations get out of the way. Total divorce from reality. DirkH on the other hand, looks at the world objectively and clearheadly and offers specific value judgments — he proposes that we should let free people and markets implement an even cleaner world. You can debate details with DirkH, challenge his assumptions, maybe improve on his ideas. You can’t do that with ‘Girl’ –she believes what she believes, and she won’t let reality intrude. DirkH and Girl show the divide between Skeptics and True Believers. There is a third group — the AGW rent seekers. The scientists (Mann, Hansen et al), trading speculators ( Deutsche Bank, ENRON), the politicians (the EU, Obama et al) and propagandists (Gore) who all ride the gravy train of government and foundation funding and who are scamming AGW for profit and political power. They of course are far worse and more dangerous than Girl, and they use people like Girl to further their greed for money and power.
D. King (20:14:04) :
“R. de Haan (19:17:07) :
Good post Ron.”
Thanks for your kind remark, you’re welcome.
When I hear a greenie weenie mention a “low carbon economy” he has fishished convincing me he doesn’t know what he is talking about. even Immelt the Chairman of GE mentioned doing without carbon. If he hangs turbines on tall Sequoia trees, the trees are still made of carbon.
Then they add, “do away with carbon”. Has anyone ever done that? I know of people that move carbon but none that eliminated it.
If they mean a carbon combustion influenced economy, then they are not so bad off. Most of the drive toward electric cars is the theory that electricity generated elswhere by use of carbon to build the plant or build the tower is like the Carbon and CO2 doesn’t exist.
Where are the pictures of the natural gas fired generators to back up the wind turbines?
Now the fetish is for rail transportation. In my area, rail is Amtrak and it stops once a day at 3 in the morning. It means I have to drive my family and luggage 90 miles round trip to a train depot in a gas guzzling Chevy. Of course the urban legendary economists don’t realize travel by rail over a couple hundred miles increases the need for an overnight stay.
Is there a requirement for the “doo gooders” to not think about what they claim solves problems?
toyotawhizguy (21:24:04) :.)
If you’re using the government derived numbers for CPI, then you are off by a factor of at least 4.
Let it be clear the Greens have done their job.
We now have a totally infected political establishment that is determined to push through their concept of a centralized World Government.
A new bi-partisan climate/energy bill is prepared by US Senators as we speak and the G7 are on a similar course.
The power of the electorate is undermined on any possible level as are civil rights and individual freedom.
The only way to stop the current course of events is to confront the political establishment.
For this the window of opportunity is closing fast.
That is the reality.
Pressed Rat (04:52:30) :
I was thinking Triumph Bonneville. You’re probably right though as the Triumph engine was better than the Norton.
On the other hand, the Norton frame was better than the Triumph which is why so many put the Triumph engine in the Norton frame to get the Triton.
DaveE.
Kate, I am so with you. Scientists are not the problem here! Politicians twist whatever the current environmental hot topic is to meet their own political agenda.
To address all the comments on hurricane Katrina, I didn’t really mean to open that can of worms and I apologize. But to be clear, I am not defending environmentalists. I am defending scientists. If you have doubts that the severity of the damage done by Katrina was not in part due to the depletion of the wetlands, you need to give your head a shake, and talk to an ecologist. I know a great one if you want some contact.
And yet, at the end of the article the authors say:
. “
When knowledge becomes institutionalized it turns into politics. This began more than two thousand years ago when some chose knowledge should be officially transmitted through an intitution, the Church, so it involved power and money making, thus the new church was to choose who were the official sages/saints, the knowledge bearers. Then the two currents divided: gnosticism (today´s climate skeptics, among others) and agnosticism (official scientists, settled science, climate change believers, the Neo-pagan-Club of Rome-Gaia Church).
However real knowledge, understanding, not needing institutions, was the work individuals who strive for knowledge, and institutions like the church, and, after the american and french revolutions, the state/government/politicians, missed it and invented fake knowledge, fake philosophy, fake ethics. Pagan churches were founded, like francmasonry which, btw, recognizes what they call the “verbum dismissum”, the lost word, the lost “logos”, the lost knowledge.
If anybody thinks he/she knows and thinks to institutionalize such a knowledge, then he/she simply does not know, as knowledge is everywhere.
spitthedog
My understanding is that Nuclear produced electricity is the cheapest source of electrical energy, with coal the next cheapest but still a lot more expensive. France has predominantly nuclear produced electricity which is divorced from the world price of hydrocarbons. Why have the rest of the higher technology economies not followed this cheaper energy route? Perhaps the market economy is distorted by polital and environmentalist ideology, but apparently not in France. There can be no economic reason for not going nuclear with electricity production. Coal and oil will find plenty of opportunity in the chemical industry.
Cliff
OT but you have been mentioned int he New York Times Anthony.
I’m still in shock because I can’t figure out the combo environment+yale, after all yale hasn’t produced an intelligent environmentalist for, well, ever, but now suddenly they get it together. It’s prolly a trick.
Pressed Rat and Anthony Allan Evans – nearly right, it was a Norton Domiracer.
Cost me a small fortune to rebuild immediately after I bought it in a very shabby state as the front end had been through a small fire which had cooked the front tyre, the paint and the chrome. Looked and sounded marvellous when it ran, but tended to vomit oil on/in my shoes, but only if I was wearing good ones. The electrics were by Joseph ‘Prince of Darkness’ Lucas, which meant lots of walking/pushing in dark and/or rain, but I still loved it immoderately and have been passionate about bikes ever since.
“”". “”"
I believe that Anthony’s citation was to the Yale Environment-360 forum article; not to the Yale Journal article. So I read what the 360 forum article said; and that is what I commented on.
I’ll leave it to the Yale Journal to demand a retraction from those two authors, if they have misrepresented the Journal paper; they are the ones who know what they meant in their forum article.
“”". “”"
Let’s see; so we start at about 1kWatt/m^2 maximum, and we go down from there via conversion efficiency (think of the Carnot efficiency of a wind turbine).
I don’t think you can even cover the ground with Saran wrap for the cost you have to have for an economical green energy plant.
“”" Claude Harvey (06:01:45) :
All the talk about wind and solar replacing conventional sources because economy of scale will make those technologies’ economically viable in the future is pure fantasy. The numbers cannot possibly EVER pencil out because of horrendous capital cost that can never be brought to heel due to: “”"
If you substitute Claude Harvey for Ed Shearon above; you might end up with a combination that makes sense; If you can figure out what I did wrong; please keep it to yourself; it’s embarrassing enough, as it is.
“”" Big Al (22:21:43) :
“”"
Simply wunnerful ! So now we are back to about 1 kW/m^2 max; not counting conversion efficiency. So what makes this better than any other solar clean green free renewable energy scheme.
I bet you can use solar energy to get carbon out of carbon dioxide too; that would give us an endless supply of clean carbon energy so we don’t have to use dirty fossil carbon.
Good article.
Carbon offset traders, environmental CAGW advocates and climate scientists:
Three Little Lambs Who Have Lost Their Way
Cliff (08:50:02) : you have been badly mis-informed on the price of nuclear-based electric power. It is the most expensive of coal, gas, nuclear, geothermal, and hydroelectric, and is more expensive than some forms of solar and wind.
see
There are so many reasons to become better stewards of our beautiful earth. Picking global warming and pointing fingers only served to push people who are not being over the top recyclers further toward a fringe. Hence comments I have seen on here before that say forget the environment, I will let my hummer idol all day, I left my lights on during earth hour for the fun of it. When you ask the same people if they think we should be more energy independent, they agree. When given the option that lowers their monthly bills by 15%, they agree..
Roger Sowell (10:42:09) said:
I will go read the article, but I wonder if this is the same in China, and whether it’s because some players in the energy marked decided to make life difficult for other players in the energy market and used their tame politicians and certain ‘environmental groups’ and their hysteria to cause this to come about.
NK (06:34:24) :
Thanks for the kind words. You should know that my hobby is trading. I have to keep my eyes open. It’s an ideology in its own right if you will.
NK (06:34:24) :
But don’t be so hard on “girl”… she’s right when she says the New Orleans disaster is partly due to the deterioration of the wetlands. You take water for irrigation out of a river and it will deliver less sediment to its delta, and the land in the delta slowly sinks, everybody knows that, the same thing is happening in Bangladesh.
Her only mistake is that she seems to think that “decarbonizing the economy” will somehow help. I blame this mistake on a lack of information on her part, not on ignorance.
As DirkH has pointed out above , we can clean up fossil fuel emissions . Indeed , we’ve done a good job here in the US . We’ve done such a good job , in fact , that about the only major effluent left from burning fossil fuels is co2 . Unfortunately , the greenies have obsessed on fossil fuels for decades , so they had to find something hideous about co2 emissions . Hence the advancement of the AGW theory . Fortunately , the wheels seem to finally be falling off that one .
DirkH–
you are very welcome.
PS: I am not criticizing openunatedgirl, I am just pointing out that her comments show an adherance to a fixed ideology, carbon AGW, to the exclusion of rational analysis. my criticism is for the third group I detest, the rent seekers who want treasure and power from controlling the rest of our free choice of energy supply.
cheers
Not so.
EIA – 2016 Levelized Cost of New Generation Resources from the Annual Energy Outlook 2010
Nuclear is slightly cheaper than hydroelectric, and significantly cheaper than any form of wind, let alone solar power. Nuclear is even cheaper than a couple of forms of natural gas, and one form of coal. On the other hand, it is more expensive than several forms of coal and natural gas, and slightly more expensive than biomass and geothermal.
As for New Orleans, best everyone do a little historical research. There is no good location for a city at the mouth of the Mississippi, not when the city was founded in 1716, and not today. The geology and hydrology are terrible.
Lasciate speranza voi che entrate….
Mr Sowell,
I have worked my entire career at a nuclear plant and you are in part correct about the costs. Nuclear is expensive to build and cheap to operate. Currently constructed nuclear plants are the cheapest base load generation available save hydro. This is, of course, because coal and gas pay much higher fuel costs and those costs vary significantly year to year and month to month.
I am also skeptical of anyone who claims to know how much it costs to build a nuclear plant in the USA today. We have not attempted to build one in 30 years so in my opinion any estimate is a complete WAG. Although I certainly would agree it will be more than a similar sized coal or gas plant. What you get is more price certainty for the future. Nat gas is currently about 4.00, even at that relatively low price it is easily twice as expensive to operate a nat gas plant today than it is a nuke. That is why they are always some of the last resources dispatched as load rises.
Wind and solar don’t even get to play in this discussion because they are not dispatchable and never pay off their capitol cost absent subsidies and mandates. If we build these facilities then we will use them when they are producing power – which we have no control over.
The fact is that GREEN arguments touch the feeling hearts of many people, though the majority of them ignore some simple things as the more you recycle the more uses will have any item, so hurting production economy and decreasing jobs
Or CO2 it is NOT BLACK SOOT or it is what we exhale, etc.
I read it.
Nordhaus, Ted, and Michael Shellenberger. “Freeing Energy Policy From The Climate Change Debate.” Opinion. Environment 360, March 29, 2010.
That dog won’t hunt.
You’ve been had by the nuke folks. The cost of nuclear that you usually see are the variable costs: fuel and operations and maintenance. They do not include capital recovery, which can be enormous. Unless, of course, your utility is an investor owned one and sold its nuclear plants for cents on the dollar. The new owners have virtually no capital recovery costs. But did the unrecovered costs disappear? Nope. You have a neat little item in your bill with some innocuous title where you’re still paying. They spread it out over 20 or 30 years to minimize it, but these sales of nuclear generation happened in the mid-90′s.
As to new nuclear costs, well the two that Southern Company are going to install with federal loan guarantees, cost about $7,000 per installed kilowatt of capacity. Each unit is 1,200,000 kw so do the math. When you figure in the cost of capital for these guys along with variable costs you get a very different picture..
Paul (11:03:05) :
There are so many reasons to become better stewards of our beautiful earth….
I’ve been on a few recent large appliance quests, most notably one to replace a 30-year-old G.E. top-load washer. An awful lot of stuff out there is designed to make the casual shopper feel good about how “green” they are. But I’d argue that a low-flow toilet with a faulty flush mechanism (another story) looks no prettier than a tradional one sitting on a mound of trash in a landfill. And I’d guess a trashed Energy-saving washer is about as green as an older model. A big question is: which lasted longer?
It seems many of the washers may deliver on the promise to use less water and less electricity using just the right settings, but their durability, thanks to sensers and easily-fried electronic elements, appears to be a very big question. Most of the salesmen I talked to just shook their heads at the notion of a 30-year-old washer; they just aren’t designed to last that long, and the “consumer advising” agencies many of us have come to rely on are not reliable. See, here, on the recent Energy Star Fraud:
I have posted to Yale 360 several times and often they have either edited my posts dramatically or simply didn’t post them. It is obviously an organization funded with our tax money dedicated to keeping the flow of “green” coming.
Okay, the “Greens” have given up trying to support manmade warming and instead are trying to convince us that spending hundereds of billions on power that is the world’s most expensive, requires tax credits and grants to build and is wildly variable requiring 100% back-up from fossil fuel plants, cannot measurably clean the air or reduce carbon dioxide either…..and to top it off treats birds (mostly raptors and bats, many endangered) as if they were milk shakes in a Hamilton Beach mixer.
A truly Piriac victory.
Mr Shearon,
I am most definitely including levelized capitol cost in total nuke cost. As does the EIA report referenced by Larry D.
Regarding solar thermal generation you are factually incorrect. There are two ways to make electricity from the sun. PV cells take sunlight and turn it directly to DC current and solar thermal focuses the sun’s rays on a body filled with a fluid (can be water) to create steam. The steam is then used to drive a turbine to make electricity. This is thermal solar energy and it most definitely only works when the sun is shining. Even if you could “store” the energy of the sun for later use, you can not store more energy than has been incident upon your particular part of the globe.
Well scrub that Yale site. Nothing more boring than looking in a mirror that feeds back only one’s own reflection.
Too bad they have the same disease that “Real Climate” has.
Hey chaps, censorship automatically brands you as a bunch of losers; incapable of taking part in a debate.?”
I though it was the first in a Ten step process –
Ten Steps to Dictatorship by Naomi Wolf
1. Invoke a terrifying internal and external threat. check - CAGW and world Financial meltdown
2. Create a secret prison system – a gulag – where torture takes place that is outside the rule of law, perhaps employing military tribunals. Start by targeting people outside the mainstream of society. As the line blurs, more and more ordinary citizens get caught up in the noose. It’s always the same cast of characters: journalists, editors, opposition leaders, labor leaders and outspoken clergy. check – reports of military torture of prisoners and rumors of military type trials being considered on mainland USA
3. Create a paramilitary force – a thug caste. You can’t close down a democracy without one. You can send that paramilitary force to intimidate civilians. Then it doesn’t matter if you still have the essential institutions of a democracy functioning, because people are too intimidated to push back. check – Blackwater
4. Create an internal surveillance apparatus aimed at ordinary citizens. You don’t need to surveil everyone. If everyone thinks they are being surveilled, that’s inhibiting. check – cars with Ron Paul bumper stickers are stop by police check points as Terrorists
5. Infiltrate and harass citizens’ groups. That helps ensure citizens won’t have the trust level to work effectively together. Boy are we seeing this. Food and Water Watch, Organic Consumers all have ties to Rockefeller and the UN so they SUPPORT corporate take over of our food supply.
6. Arbitrarily detain and release citizens. This will frighten them. check farmers/co-ops targeted and all those roadblocks and license checks as well. And do not forget the torture and deaths by tazer of innocent people.
7. Target key individuals: lawyers, people in the press, academics, people in the media, performers, even civil servants, so people see there are repercussions if they stand up against you. Again Ron Paul, Bob Barr, Chuck Baldwin supporters are on the terrorist watch list.
8. Restrict the press. Investigate, intimidate and imprison reporters. Accuse them for treason.. Start using the words of a closing society: terrorist, enemy of the people, sabotage, espionage, treason. Over time, replace the real news with fake news. Derry Brownfield kicked off the air and two Florida reporters fired, not to mention John Munsfield’s story about e-coli contamination at Con Agri being pulled at the last minute. Reporters knocked down and tazered at political demos. Also Wiki leaks is supposed to have a video of reporters being murdered????
9. Expand the definitions of espionage and treason so more and more people are included. Recast criticism as espionage and dissent as treason.
The list is now over a million and that doesn’t include bumper stickers. I was just told by an ex-secret service guy that ALL ex-military, ex-CIA, ex-FBI…. are now on the “Homegrown terrorist” possibles list
10. Suspend the rule of law. Subvert it by decree and/or declare martial law. Is that what the tea parties are about, to start a major confrontation?
Boy can’t you have lots of fun with this list and the scuttle butt drifting around on the internet….
“”" Ed Shearon (15:14:50) :
You’ve been had by the nuke folks. The cost of nuclear that you usually see are the variable costs: fuel and operations and maintenance. They do not include capital recovery, which can be enormous. …..
…..……
So presumably (as judged by your arguments) SoCal Edison, is building these two solar plants entirely using free green clean renewable (solar) energy, sicne you didn’t mention anything about the energy capital costs of their plants.
One thing we know for sure is, that we started off with nothing but free clean green renewable solar energy; it was even quantized and came in chunks called “figs”. But it barely served to sustain just a few of our ancestors; and they didn’t become successful, until they discovered stored chemical energy; and eventually the fossil fuel form of stored chemical energy.
So no matter how you want to cut it, and jigger with the economics calculations; along with the pollution and other environmental costs; we can say assuredly that fossil fuel worked; it got us to where we are; whereas free clean green renewable solar energydid not and could not.
And if you want to figure out the per capita costs of the energy and pollution clean up and other environmental factors, and then compare that to all the damage our few ancestors did to the fig trees; I have no doubt that we are way out in front of their achievements.
If you want your grandchildren to go back to clambering around in fig trees for renewable energy; be my guest.
Do you have any idea what the total pollutant output of a silicon production factory is; not to mention the noxious materials that must be obtained and controlled in the fabrication of free clean green renewable PV solar energy; at a rate of maybe 10 Watts per Square foot (tops).
I’m waiting with bated breath to see the first solar energy plant replicate itself using its own energy output; and have something left over to sell on the open market against its competition.
Of course if you have some other non-solar free clean green renewable energy source that I haven’t heard about yet; well maybe that could be a winner; sell you house and bet on it.
Mr Lynn (05:26:56) :
R. de Haan (21:29:14) :
What every person on the planet should know!
Access to cheap and safe energy should be a human right! . . .
“Point of clarification: Let’s not make the mistake that the socialists do with ‘healthcare’: access to goods and services produced by others is never a ‘right’. It may be eminently desirable, a wish devoutly to be achieved, but not a right”.
Mr. Lynn,
I have made this point to prevent Government from enslaving it’s populations by charging excessive energy taxes and “Cap” policies.
I did not state energy should be made available for free! I only said it should be available to everybody on the planet at an affordable price!
In the case of shale gas, available in 75% of the world’s sediments we have the opportunity to generate affordable electricity all over the world with explortion companies and distributors still making good profits.
I don’t agree with your “Health Care” example because in this case Government is forcing Americans to buy Health Care. If they refuse they will be fined, if they can’t pay the fine, they go to prison and they will have a criminal record!
Besides that, if Government is in a position to force people to buy health care, what will be next? Will they be forced to buy a car from Government Motors?
Anyhow, thanks for your support for the remaining content of my posting.
R. de Haan (17:10:51) said:
Hmmm, the words I have seen suggest that the IRS does not have the power to enforce the fines associated with not buying health care … possibly an oversight on the part of the Democrats, but who could possibly have figured that out given that the bill was some 2000+ pages.
““”” Ed Shearon (15:14:50) :
You’ve been had by the nuke folks. The cost of nuclear that you usually see are the variable costs: fuel and operations and maintenance. They do not include capital recovery, which can be enormous. …”
The capital cost of wind is 1 1/2 times that of nuclear. The cost of manpower for wind is also 1 1/2 times nuclear. The cost of solar is higher.
The arguement that nuclear fuel is energy intensive is provably false. The fuel is a very minor cost. the cost of producing kilowatt hour of nuclear energy is the lowest cost of any power except water power and is a fraction of wind or solar. Another major cost of wind or solar is the requirement to run high power lines to remote locations which, in many cases, doubles the capital cost. Nuclear plants have to be constructed near water sources which coincindentally is where most people live and work. ……..and, of course, nuclear fuel can be recycled as it is for France at the Hague in the Netherlands. A concern is the by-product plutonium which Carter outlawed as being to easy to convert to weapon grade material.
There is no logical reason not to utilize nuclear. We could also continue to utlize coal and clean it by desulphurization and with flyash precipitators. We could burn nutural gas which is pretty clean. I agree there is no economic or ecological reason to build wind and solar. They are pork projects. They clean no air by any measurable amount and they cannot shut down one fossil fuel plant.
Pork, pure and simple.
I understand, and agree with, your reasons. And I understand that you did not say energy should be free to all.
My point is that it is common today, especially on the Left, to assert that human needs create ‘rights’ which can be met only by government: the right to food, to shelter, to a job, to healthcare—and energy? What’s next? A good car? An LCD TV? And I wanted to emphasis that this conception is alien to the concepts that inform the American Experiment.
Our system of restricted and republican (small ‘r’) government is based on the notion of ‘natural rights’, to “Life, Liberty, and the Pursuit of Happiness,” which, as Prof. Walter E. Williams points out, are inherent in our natures and cannot be given by other citizens or government (though government can prevent us from exercising them).
Human needs for goods and services can be satisfied by individual and group endeavor, but not by government, unless the government takes from some and gives to others, because government creates nothing on its own. So a ‘right’ to something enforced by government inevitably becomes a strait-jacket of rules and penalties imposed in the name of ‘fairness’ (hence the ‘mandate’ to buy health insurance).
It ought to be the policy of our government to encourage private industry to provide cheap and plentiful energy for everyone, and the government can best do so by getting out of the way and giving the markets and entrepreneurship free rein. The world has coal, natural gas, uranium, thorium, and other resources in abundance, and the technologies for utilizing these are improving every day.
While no one has a ‘right’ to cheap, abundant energy, no government should have the right to curtail our production of it. It is the key to the continued progress of human civilization, and to the development of the third word. The trick, in this Republic make sure we elect people who understand this imperative, and will not seek to curtail human freedom and enterprise in the name of providing for its citizens what they should be providing for themselves.
We don’t disagree.
/Mr Lynn
Correction (last sentence of penultimate paragraph): The trick, in this Republic, is to make sure we elect people who understand this imperative, and a government that will not seek to curtail human freedom and enterprise in the name of providing for its citizens what they should be providing for themselves. /Mr L
Doug Badgero (16:08:50) : – you might want to check your figures for fully-costed nuclear power from a new power plant in the US. Here’s a link:
Jon:
New nuclear costs between $6,800 and $7,200 /kw. See
Other generation, $/kw installed (the capital costs):
New wind costs $1,208
Solar electric $4,751
Solar Thermal $3,149
“advanced” nuclear (does not commercially exist & same number predicted in 1986) $2,081
Facts are pesky things, Jon.
Mr Sowell,
I provided no figures to check. I referred you to an Energy Information Administration report that LarryD referenced. It shows quite clearly that all in costs for nuclear are competitive with other power sources. Especially when you consider future price uncertainty with coal and gas. That said, it would be foolish to build nuclear for anything but base load generation. They must operate at near full capacity to pay for their fixed capitol costs. That is the unavoidable fault of wind and solar. They cost a fortune to build but cannot operate above about a 35% capability factor. That is the mistake Mr Shearon makes for wind and solar – capitol costs must be adjusted for both capability factor AND the cost to build backup power sources for when the wind doesn’t blow and the sun doesn’t shine (probably gas). The EIA report does not make the capability adjustment mistake. However, it only mentions the non-dispatchable nature of wind and solar in passing.
Note that EIA estimates the all in cost of NEW nuclear generation at about 11cents per Kwh. It is very easy to play with these numbers by simply adjusting the cost of capitol (interest rate assumptions) or future predictions for the cost of coal and oil to make one source look better or worse than another. That is why different studies from different ideological viewpoints come to very different conclusions. There is risk associated with any choice.
openunatedgirl (19:05:59) wrote:
“To address the overall tone of this message board, I would like to say that I am completely depressed by the majority of your comments. You really want to challenge that we are ruining our environment? Really?”
It’s much easier to fault the other person’s tin gods than to admit that one’s own tin gods are melting. That would partially account for the Libertarian perspective of many commentators here at WUWT, since from that Weltanschauung, it’s not difficult to be skeptical about ‘problems’ that require Big Government as a ‘solution’.
Take AGW-abandonment . This particular kind of disillusionment is a much bigger step for Lefties, most of whom were educated to believe that truth is a linear combination of ‘expert’ opinions.
I agree that there are genuine environmental concerns–like overfishing in the world’s oceans. I also think that the mythology of the Flying CO2 Monster is a major distraction from this and other real problems. And I don’t view governmental regulations as bad in their own right, if there’s full public access to the data and reasoning–if any–behind them. Sometimes the Greenies get it right, and sometimes they don’t.
If you haven’t seen it already, please check out jennifermarohasy.com. Jennifer is a biologist and a proponent of evidence-based environmental policy, with an emphasis on issues that affect Australians. However she’s writing a novel at the moment, and there hasn’t been much current stuff on her blog for the last several months. When it was more active, I regarded Jennifer’s blog as the very best on environmental issues other than climate change, even though I’m not an Aussie.
Given your engineering background, I think that you can make a real contribution here. Please don’t feel like the Lone Ranger.
There is nothing mystical about doing levelized cost of electricity calculations. It is a rather straightforward formula.
I suspect that, as is the case with climate, ideology is getting in the way of understanding.
Taking into consideration the availability factors of the various forms of generation, and especially the intermittent forms, new nuclear (the kind you can actually buy today with commercial terms) is the most expensive form of base generation known to man. It is also, by the way, the most subsidized form of ANY kind of generation.
Comparing solar thermal to nuclear is appropriate because both can be base loaded. And solar thermal wins hands down by any metric.
People who try to compare wind or photovoltaics to nuclear are just shouting “I don’t know what I am talking about!” These are intermittent forms that today enter the grid when the power is produced. They compete with whatever other forms of generation are economic at the time they are produced (almost all grids do economic dispatch on at least an hourly basis- as demand rises more expensive units are called). Wind farms with storage – and this is going to happen within 2 to 3 years – using flow batteries or other technologies that are just about commercial will become very competitive as base load generation.
Finally, getting back to ideology, it mystifies me that the right is so pro-nuclear. Nuclear only works at very large scale and in centrally planned electricity grids. That’s why big coal and big nuclear plants are referred to as “central generation.” In fact, you can’t think of a better form of generation for a socialist society. We have huge problems today with the enormous inefficiencies in a grid network that was great for 1935 but makes no sense today. When you plop in a 1 GW nuclear unit in the transmission network it literally has no place to go unless you build a lot more lines. With central generation there are huge losses to get to the end user. Power reliability and quality suffers and gets worse as more customers are added at the distribution end. Distributed sources of power avoid all of these inefficiencies, increase quality and reliability, and put the power in the hands of the end users. The technologies are there, now.
The future US electric power generation will be based on Natural Gas.
Here you find some of the arguments.
For the price of five Nuclear power plant we can build the entire US future energy
requirements based on Natural Gas power plants!
That is if we let free market principles do their work in a free energy market!
Any other energy policies driven by Government grants, semi science and ideology are nothing more but a kind of robbery of the American consumer.
The ignorance, and dogma, on this thread are getting tiresome. Solar of any kind can not be base loaded – period. Go read the company website about how these plants work and then research what base loaded means. They generate power only when the sun is shining on the focusing mirrors. That means, by definition, they can not be dispatched OR base loaded.
You are correct, there is nothing mystical about levelized capitol cost calculations. However, if you assume a 12% weighted cost of capitol you get a very different result than if you assume a 6% cost of capitol. It’s math no mystery involved.
Finally, production subsidies by generation type are found here –:
solar and wind – 23-24 dollars per MwHr mostly direct tax credits
nuclear – $1.59 per MwHr mostly R&D
Subsidies for other generation sources are available at the same link and all of this data I have provided is EASILY verified in this report.
Good day
Legitimate reasons for saving energy:
Make best use of scarce resources
Reduce our dependence on foreign oil and gas
Save money on energy bills (for cheapskates like me).
Illegitimate reason:
Fight AGW.
Dear Doug:
As I said before, solar electric is not baseloaded and cannot be compared to nuclear. Neither can any other intermittently generating technology unless it has storage. Solar thermal, however, because it uses liquid heat storage, has an availability factor of 70% and, at the scale SCE is constructing (750 MWe per unit), is very much baseloaded.
You’re missing the following nuclear subsidies:
Price Anderson liability limit (anything accident over $1 B the feds cover- TMI cleanup was $1.6 B and was very minor)
The enrichment facilities were built with defense funds and are not paid for by commercial nuclear.’
Uranium mill tailings cleanup has been fully funded by the feds.
There is a measly fund to store nuclear wastes paid into by the utilities that is a pittance relating to what has been spent and will have to be spent to solve the problem.
All nuclear units are currently paying into a fund for decommissioning at the mandated total of $300 M per unit. Recently one of the original Yankee units was decommissioned – a unit that was about 250 kW – and it cost $600 M. Think of what the realistic costs of a 1200 MW unit will be. Who do you think pays that? Hint: It ain’t in the cost of power today!
Some nuclear fuel will come from dismantled weapons. This saves enrichment costs, but the buyer will not be paying the actual cost of those weapons in the first place.
An added thought: nuclear is a net negative energy generator.
The hallmark of agendas is making apples and oranges comparisons to those who do not understand the differences to support an argument.
Good Day!
PS. The second most subsidized form of energy is oil.
Another thought regarding efficiency.
There is a common fallacy in the anti-AGW dogma: the one that goes something like “investments in renewables and efficiency are only being done to get carbon credits because they are too expensive otherwise.” Or, “the only people who invest in clean energy plan to make a killing via carbon and thats why they support it.”
No one, and I say again, no one with any business sense develops a project because of carbon. It is icing on the cake if it ever happens, but these projects must stand alone economically. Carbon could be an additional revenue stream but it is way to small to tip the scales one way or the other.
Efficiency is far more cost effective than new generation, of any type. We could take out 20% inefficiency in the transmission grid alone. Think about that. the US generation base is around 1,000 GW. That’s 200 GW of waste. Or 200 large scale nuclear or coal plants. At far lower costs per kW. That’s where the priority needs to be, not on perpetuating a business and regulatory model that has been outdated since WWII.
“”" Ed Shearon (08:28:50) :
……..
I suspect that, as is the case with climate, ideology is getting in the way of understanding.
…..
Comparing solar thermal to nuclear is appropriate because both can be base loaded. And solar thermal wins hands down by any metric….
…..
Finally, getting back to ideology, it mystifies me that the right is so pro-nuclear. Nuclear only works at very large scale and in centrally planned electricity grids. “”"
“”" ideology is getting in the way of understanding. “”"
Having a problem reconciling these two statements; if “ideology is getting in the way of understanding.” then why bring it up, in relation to Nuclear energy ? Perhaps the answer lies in a corollary question:- Why is the left so anti-nuclear ?
Here of course I am using right and left in their usual street public debate connotations; without regard for who or what they actually refer to.
But I can think of some reason why some people (no idea whether they would be your right, or left, or something else) might be pro-nuclear.
It seems to me that “Sources” of energy; in so far as they are of interest to humans, can be separated into two categories.
The first category; which also happens to be the first energy available to “humans” is renewable energy sources. By that I mean that if I consume energy from such a source yesterday, today, or tomorrow (now), I can return (here) say a year from now, and find that source of energy is replaced.
An example of such would be figs from trees; which our ancestors spent a good part of their waking hours trying to get at. There are many others of course; but they all have one thing in common; such renewable energies are forms of solar renewable energy; without the sun’s radiation, they would not exist.
The same is true of proposed modern renewable energies; some of them Hi-tech. They too are sun sourced, and without sun energy, they would not exist.
The second category of energy sources can be loosely described as “Stored energy sources.”
Now arguably figs are also stored energy sources; but they have a finite life after which they are dissipated and become unavailable; which is why I referred to the idea of returning next year to find replacements.
Fossil fuels such as natural gas, petroleum, tar-sands, coal and the like, are stored energy sources. Let’s not quibble about whether coal and petroleum and natural gas are renewable on geologic time scales; that is of no use to our children and granchildren.
Intermediate between renewable and fossil might be things like wood, and peat; which are renewable on longer time scales but shorter than geologic; but also result from sun energy.
Thej “fossil fuels” are pretty much all “Stored Chemical energy sources.” The energy is essentially available only through chemical combustion with atmospheric Oxygen; producing the essentials for life; namely H2O and CO2, as by-products.
Renewable energy from the sun, of course is also available in the form of tidal or hydro-electric ; which are only available in relatively rare locations; with sometimes extreme environmental burdens, as to their usability.
The only thing missing from the list of stored energy sources, turns out to be Nuclear energy; although renewable energy can sometimes be stored by human action in the form of hydroi-electric facilities.
Stored energies have one great advantage over renewable energies. You flip a switch and the energy release process starts immediately. In the case of Hydro, this feature is achieved by using gravitational storage of solar energy to create an always available instant on energy source. With fossils of course you simply strike a match to get the energy.
So perhaps the interest (pro if you like) in Nuclear, stems from the fact that it is the only significant stored energy source available in considerable amounts, besides stored chemical energy.
Stored energy in any form is dangerous; and the greater the energy density the more dangerous it is; which makes nuclear energy quite dangerous. Yet more humans have been killed by hydro-electric energy sources than Nuclear; by far; most often as a result of broken dams; the hydro equivalent of a nuclear containment leak or core melt down. Don’t even start on Nuclear weapons; because “gunpowder” wins that race hands down.
Petroleum in the form of gasoline seems to be one of the safest high energy density stored energy sources available to us; and it puts electricity to shame for portable applications.
So I’m not sure what your point is in asking why the right; whoever that is, is so pro nuclear; maybe you can explain the counter position; because I certainly can’t.
Which gets us back to renewables starting from those figs, and on to today’s hi tech renewables from solar.
There’s that embarrassing 1 kW/m^2 availability rate that we don’t seem to have any practical solution to. Yes it is renewable; but the rate of renewal is just too damn slow.
Arguably, the fossil fuels are also stored sunlight; and it is claimed that we have just about exhausted, what has taken the sun some 4.5 billion years to store up for us. So fat chance that it can continue to supply us at the rate we can consume. Well yes there is plenty of solar energy arriving on earth; but it is so dispersed, that we pretty much would have to spend our every waking minute out trying to gather it up to use.
Seems like we were there once before ; up in those fig trees.
Ed,
You may continue to believe what you like about the SCE solar thermal plants. I have worked all my adult life in thermal power plants and the only difference between what solar thermal does and what coal, nuke, or nat gas do is in the heat source. When the heat source goes away so does the power output. Your 75% availability defies the laws of thermodynamics unless the turbine-generator is grossly undersized compared to the solar array.
The PA act liability pool currently stands at approximately 10 billion. This is the amount that has been funded by industry.
Commercial nuclear power plants pay for their fuel, although can’t own it but that is another issue, that is what pays for the current enrichment facilities.
We are idiots if in the long term we store high level waste – we should reprocess like the rest of the world does. In any case, much more has been paid into this fund than has been spent to solve the problem.
I would love to see your numbers supporting net negative energy generation.
What were my apples and what are your oranges?
Losses in the HV transmission network are closer to about 8-10%. Distributed generation will in part simply relocate those losses to the distribution network. If distributed generation can be made cost effective based on other issues.
Business men most assuredly agree to buy wind power in large part because of the 1.8cent per Kwhr tax credit – including the company I work for.
Doug:
Here’s the story on thermal storage at solar thermal plants:
Price Anderson Act limits commercial insurance coverage to $350 M, sets up a pool with a ceiling of $10.5 B administered by the government, and indemnifies owners from any claim exceeding $10.5 B, You have government artificially reducing the cost of risk management, providing insurance and limiting what people could sue for. That’s a pretty big subsidy. BTW, the Wikipedia discussion of PAA is not accurate.
Commercial nuclear plants pay for their fuel because they own it. Government ownership of fuel ended in 1968. When you buy U3O8 it is yours. After you convert it to UF6 title gets a little odd while it is in the hands of DOE for enrichment. But title is clearly yours once it comes out of enrichment and stays yours until you turn over title when the feds take custody for storage or disposal. You can put liens on nuclear fuel precisely because you have title, and it makes sense to borrow against it because it is in the pipeline for quite a while during processing.
We stopped reprocessing in 1975 under the Ford administration. You know why that happened in a Republican administration? Because even then reprocessing made no economic sense and people were looking for a bailout. The public reason was to mitigate nuclear proliferation. I know because I had contracts with the two reprocessors still in business: West Valley and Barnwell. It still makes no economic sense. No one in the world reprocesses to reuse fuel as MOX or to fuel breeders. MOX fuel is ridiculously expensive (not just to buy, but to keep secure from bad guys) and there are no commercial breeders. The Navy reprocesses highly enriched submarine reactor cores, but this is an organization that will fly a $2 part from Norfolk to Scotland to get a boat underway.
Net negative nuclear energy generatation:
Line losses in transmission are between 8% and 10 % but that’s only one very obvious inefficiency. They occur because of simple resistance in wires that span big distances. If they are eliminated they are NOT transferred to the distribution network, nor to they occur with distributed generation (since the path of the electrons is so much shorter, there is little resistance). A problem faced on the distribution side is harmonic distortions. These (and voltage sags and spikes) wrech havoc with computer systems and are endemic in areas with high growth and old infrastructure. Local generation solves that problem.
If you want to read about other efficiencies possible beyond simple line losses, go to and read some of the papers there.
The tax credits for wind and solar pale in comparison to those provided to nuclear. And regarding business judgments, there’s lots of people building wind and solar, but I only see one utility willing to risk the farm on nuclear, and that’s with all kinds of support and subsidies.
Ed,
This is my last post on this thread.
The first link is to a hypothetical plant. It is not the plant SCE is building. Nothing can overcome the limited energy density of solar. To get a continuous 750Mw you would need to install a 3000-4000Mw peak absorption system and store the peak to use at a later time – with loss of efficiency at every step.
The 10 billion provided by PA is industry funds. To date they have issued a total of 151 million, about half as a result of TMI. These federal insurance schemes are not unique they exist for flooding, agricultural catastrophes, financial failures and maritime accidents. To date it has cost little or nothing to the taxpayers. I do not disagree that like all insurance the protection after the first 10 billion has economic value but to date it has been revenue neutral to the taxpayer. Any value assigned is simply a ledger item. Some of the other federal systems cannot say the same, e.g. financial system failures have cost billions over the years.
What does France, etc do with their transuranic elements if not “reburn” them?
If local generation is both more efficient, more economic, and of better quality why do we not use it now? I could install a wind turbine at my house except it would cost about $40,000+ last I checked and never pay for itself. I suspect I will disagree with your answer. I am curious, what power source do you envision for your distributed generation? Wind and solar with storage? Micro-turbines? I do not disagree that distributed generation has the potential to be more efficient but that has always been the case. The downsides have, to date, outweighed this potential advantage.
I looked at your link regarding negative net energy. It looks like a rather unique calculation and I will have to spend more time reading it to fully understand the author’s assumptions. I did notice one statement describing how if we build out nuclear power plants eventually nuclear plants would have to load follow. This would make them uneconomic based on all of the idle capitol. This is, of course, correct but we would be fools to build out nukes to that point. Any economic asset that has a high capital cost must also have a high utilization. No one I know of is proposing such a plan. For instance, the EIA report assumes a 90 percent capacity factor. About what the industry average is now. Although much better than it was 20 years ago.
I consider your final paragraph simply unsupported by the facts unless some rather curious assumptions are made – such as those about PA.
Doug:
My last post as well, and I feel compelled to recite credentials. I received an MS in Nuclear Engineering in the late 70′s. I was in charge of a soup to nuts nuclear fuel procurement division for 3 reactors. We were the first utility to buy ore (even had a few geologists looking for new sources), and separately contract for all of the services necessary to deliver fabricated fuel. I worked for three nuclear organizations in my career with a total of 5 reactors. I have testified in rate proceedings on nuclear fuel cost and have also been in charge of a utility holding company strategic planning division, where we made decisions regarding new generation and transmission options. Currently I am involved in several alternative energy projects, including smart grid options.
Utilities pay commercial premiums for the first $350 M of an accident. They then pay the government a premium for the next $10.15 B. Under PAA no one can sue beyond $10.5 B in damages. So in the event of a PAA ceiling accident, the utility pays commercial rates on 3.3% of the loss and gets subsidized federal insurance for the other 96.7%. The max payout for any loss in the US was $300 M for TMI, not $151 M like Wikipedia says. The total cost of cleanup at TMI was $1.6 B and that was a) in incomplete job; and b) the core was removed, shipped and stored by the DOE at no cost to the utility. This was for what the NRC would call an “entombment” decommissioning option. Entombment is a generous term. The entire basement and much of the containment vessel concrete is embedded with a soup of isotopes to a depth of a few inches. I know, because I was there.
We don’t use local generation because we operate in a monopolistic regulatory environment. If you are a utility and your customers start putting in their own generation you have two problems: 1) that generation may be out of synch with you and you are both connected to the same network; adn 2) it amounts to a loss of revenue. Both are rather frightening things to utilities, so what you will see across the country are barriers to distributed generation. Economic barriers, such as silly buy back rates and additional interconnection fees that make local generation uneconomic. And regulatory barriers. In NM, for example, the second best solar resource in the country but a major gas and oil producer, it is illegal to install a solar PV array over 50 kW. That means that commercial sized installations don’t exist. There is a fight going on right now- the utility said it would allow up to a MW, but a month later filed another plea that it had to own all commercial scale solar. NM is 15th in overall solar capacity. Number one is New Jersey, with hundreds of MW.
Utilities make their money by getting a return on their capital investment. When you put in big wires, big substations, big generation, you add to the “rate base.” You put in a new substation, costing $25 M, sized to meet demand that occurs less than 1% of the year. The incentives are entirely skewed to large centrally planned and centrally operated utilities. Utilities number one core competency is not reliable operations or least cost operations, it is never allow the regulatory rules to change. And they are very good at it.
I’m afraid you are awash in a sea of what constitute urban myths about how energy works and is valued in this country.
Ed
As I understand it from several sources the actual amount paid out under PA ever is 151 million. Of this, about 75 million was paid out to various plaintiffs and lawyers as a result of TMI. In addition, the collective industry is obligated to pay the excess damages above the 300 million each utility must carry, up to 10 billion total. Paid as a little less than 100 million per reactor in installment payments of 10 million per year max. Again, this has never cost me as a taxpayer anything. I do not question your assumptions on the cost to put TMI into it’s current state but I suspect it was borne primarily by the utility.
Utilities are obligated to serve me but I am not obligated to buy from them. Again I ask what is the system you envision? It seems like from your discussion that you want to provide your own power but use the utilities assets to both sell excess at a rate you determine and probably buy from them when your own generation is insufficient to supply your own needs.
By the way:
I have a BSE in mechanical design and I am about half way done with an MSEE in power systems (I did not quit, I just started).
I held an operating license and senior operating license at a nuclear plant for 14 years.
On paper I guess you win on impressive qualifications but I am sure I could find someone with a PhD who agrees with me. I think we will simply have to agree to disagree.
Yes! I am so happy that you guys have been posting your credentials! I know it can kind of feel like a “my degree/background/opinion is more relevant/important/right than yours” but it can really help to explain some of the bias associated with each argument (not a bad think, just a fact of life :) ) I would really encourage everyone to post their educational and employment industry when making these types of posts, as it can give some great context to the discussions taking place. These discussions are so important to scientific topics, and I hope they continue to happen.
openunatedgirl
Thanks. You do have to look beyond that also though. My qualifications and experience can provide context but it can never be justification for an opinion by itself. I point this out only because this argument has been used so frequently in the AGW debate. It is possible to have an opinion that is not in your own self interest. For instance, it would be completely self serving of me to line up firmly behind the AGW hypothesis. I am definitely not there. | http://wattsupwiththat.com/2010/03/29/yale-to-greens-abandon-climate-change-focus-on-energy/ | CC-MAIN-2014-10 | refinedweb | 25,155 | 61.77 |
< ------------------------------------------------------ Liao Xuefeng learns Java ---------------------------------------- >
1. Multithreading Basics
- The computer calls a task a process, the browser is a process, and the video player is another process. Similarly, both the music player and Word are processes
- Subtasks in a process are called threads
- Relationship between process and thread: a process can contain one or more threads, but there will be at least one thread
- The minimum task unit scheduled by the operating system is thread. Commonly used operating systems such as Windows and Linux use preemptive multitasking. How to schedule threads is completely determined by the operating system. The program itself cannot decide when to execute and how long to execute
- The same application can have multiple processes or threads. There are several methods to realize multitasking:
1. Multi process mode (only one thread per process) 2. Multithreading mode (multiple threads in a process) 3. Multi process+Multithreading (multiple processes and each process can have one or more threads)
- Compared with multithreading, the disadvantages of multithreading are:
1. Creating a process is more expensive than creating a thread, especially in Windows On the system; 2. Inter process communication is slower than inter thread communication, because inter thread communication is to read and write the same variable, which is very fast.
- Compared with multithreading, the advantages of multithreading are:
The stability of multi process is higher than that of multi thread, because in the case of multi process, the collapse of one process will not affect other processes, while in the case of multi thread, the collapse of any thread will directly lead to the collapse of the whole process
- The Java language has built-in multithreading support: a java program is actually a JVM process. The JVM process uses a main thread to execute the main() method. Within the main() method, we can start multiple threads. In addition, the JVM has other worker threads responsible for garbage collection
2. Create multithreading
- To create a new thread, you just need to instantiate a Thread and call its **start() * method.
- How to assign tasks to threads:
Method 1: customize the Thread subclass and override the run method (the method body contains the code to be executed)
public class Main { public static void main(String[] args) { Thread t = new MyThread(); t.start(); // Start a new thread } } class MyThread extends Thread { @Override public void run() { System.out.println("start new thread!"); } }
Method 2: when creating a Thread instance, pass in a Runnable instance
public class Main { public static void main(String[] args) { Thread t = new Thread(new MyRunnable()); t.start(); // Start a new thread } } class MyRunnable implements Runnable { @Override public void run() { System.out.println("start new thread!"); } } //Or use the lambda syntax introduced in Java 8 to further simplify it as public class Main { public static void main(String[] args) { Thread t = new Thread(() -> { System.out.println("start new thread!"); }); t.start(); // Start a new thread } }
- Call Thread.sleep() to force the current thread to pause for a period of time; The parameter passed in by sleep() is milliseconds
- Calling the run() method of the Thread instance directly is invalid: it is equivalent to executing the run method of the Thread object in the main Thread, and no new Thread will be created
- A private native void start0() method is called inside the start() method. The native modifier indicates that this method is implemented by C code inside the JVM virtual machine, not Java code
- Set priority for threads. The method of setting priority is: Thread.setPriority(int n) // 1~10, the default value is 5
3. Thread status
- Java threads have the following states:
1. New: The newly created thread has not been executed; 2. Runnable: Running thread, executing run()Methodical Java code; 3. Blocked: A running thread is suspended because some operations are blocked; 4. Waiting: A running thread because some operations are waiting; 5. Timed Waiting: Running thread because of execution sleep()Method is timing and waiting; 6. Terminated: Thread terminated because run()Method execution completed.
- The reasons for thread termination are:
1. Normal thread termination: run()Method execution to return Statement return; 2. Thread terminated unexpectedly: run()Method causes the thread to terminate because of an uncapped exception; 3. To a thread Thread Instance call stop()Method force termination (strongly deprecated).
- A thread can wait for another thread (the current thread suspends execution) until the thread ends running: Thread.join() method
public class Main { public static void main(String[] args) throws InterruptedException { Thread t = new Thread(() -> { System.out.println("hello"); }); System.out.println("start"); t.start(); t.join(); System.out.println("end"); } }
- Get the current Thread: obtained through the static method of Thread class
Thread t = Thread.currentThread();
4. Interrupt thread
- Interrupting a thread means that other threads send a signal to the thread. After receiving the signal, the thread ends executing the run() method, so that its own thread can immediately end running
- In other threads, the interrupt() method is called on the target thread. The target thread needs to repeatedly detect whether the state is interrupted (calling the isInterrupted() method in the notification thread), if it is, it will terminate the operation immediately.
public class Main { public static void main(String[] args) throws InterruptedException { Thread t = new MyThread(); t.start(); Thread.sleep(1); // Pause for 1 ms t.interrupt(); // Interrupt t thread t.join(); // Wait for the t thread to end System.out.println("end"); } } class MyThread extends Thread { public void run() { int n = 0; while (! isInterrupted()) { n ++; System.out.println(n + " hello!"); } } }
Note: if the calling isInterrupted method is not displayed in the child thread, the thread will not stop even if another thread sends an interrupt notification
- If a thread is in the waiting state, for example, t.join() will make the main thread enter the waiting state. At this time, if interrupt() is called on the main thread, the join() method will immediately throw an InterruptedException. Therefore, as long as the target thread catches the InterruptedException thrown by the join() method, it indicates that other threads have called the interrupt() method, Normally, the thread should end immediately
public class MulThread_03 { public static void main(String[] args) throws InterruptedException { Thread t = new MyThread(); t.start(); Thread.sleep(1000); t.interrupt(); // Interrupt t thread t.join(); // Wait for the t thread to end System.out.println("end from main Thread"); } } class MyThread extends Thread { public void run() { Thread hello = new HelloThread(); hello.start(); // Start the hello thread try { hello.join(); // Wait for the hello thread to end } catch (InterruptedException e) { System.out.println("interrupted! from MyThread"); } hello.interrupt(); } } class HelloThread extends Thread { public void run() { int n = 0; while (!isInterrupted()) { n++; System.out.println(n + " hello!"); try { Thread.sleep(100); } catch (InterruptedException e) { System.out.println("!!!!"); break; } } } }
Note: under the combination of join and interrupt, the parent process will force the join method to report InterruptedException. This error is perceived by the child process, and the child process can configure different response methods
- Another common way to interrupt a thread is to set the flag bit. We usually use a running flag bit to identify whether the thread should continue to run. In the external thread, we can end the thread by setting HelloThread.running to false:
public class Main { public static void main(String[] args) throws InterruptedException { HelloThread t = new HelloThread(); t.start(); Thread.sleep(1); t.running = false; // Flag position is false } } class HelloThread extends Thread { public volatile boolean running = true; public void run() { int n = 0; while (running) { n ++; System.out.println(n + " hello!"); } System.out.println("end!"); } }
- Note that the flag boolean running is a variable shared between threads. Variables shared between threads need to be marked with volatile keyword to ensure that each thread can read the updated variable value
- Why declare variables shared between threads with the keyword volatile?
In the Java virtual machine, the value of the variable is saved in main memory, but when the thread accesses the variable, it will first obtain a copy and save it in its own working memory. If the thread modifies the value of the variable, the virtual opportunity will write the modified value back to the main memory at a certain time, but the time is uncertain! This will cause that if one thread updates a variable, the value read by another thread may still be the value before the update
volatile keyword solves the * * visibility problem * *: when a thread modifies the value of a shared variable, other threads can immediately see the modified value
5. Daemon thread
- Java program entry is that the JVM starts the main thread, and the main thread can start other threads. When all threads have finished running, the JVM exits and the process ends
- If a thread does not exit, the JVM process will not exit, so it is necessary to ensure that all threads can end execution
- There is a thread whose purpose is to loop indefinitely. For example, a thread that triggers a task regularly:
class TimerThread extends Thread { @Override public void run() { while (true) { System.out.println(LocalTime.now()); try { Thread.sleep(1000); } catch (InterruptedException e) { break; } } } }
- Who is responsible for ending this thread?
The answer is to use daemon threads. A Daemon Thread is a thread that serves other threads. In the JVM, after all non daemon threads are executed, the virtual machine will automatically exit whether there is a Daemon Thread or not.
- How to create a daemon thread?
Before calling the start() method, call setDaemon(true) to mark the thread as a daemon thread.
In the daemon thread, you should pay attention to when writing code: the daemon thread cannot hold any resources that need to be closed, such as opening files, because when the virtual machine exits, the daemon thread has no chance to close files, which will lead to data loss
6. Thread synchronization
- When multiple threads execute at the same time, there is a problem that does not exist under the single thread model: if multiple threads read and write shared variables at the same time, there will be data inconsistency
Data consistency problem!!
- Take the following pseudo code as an example:
main{ static int count = 0 addThread.start // This thread is responsible for adding shared variables 100 times subThread.start // The thread performs subtraction operation on the contribution variable for 100 times addThread.join subThread.join sout(count) // ? ? ? }
If there is no data consistency problem, the answer is obvious. The final output count is 0, but in fact, the output result always changes. Why?
First, supplement the basic knowledge. A simple add instruction (add = add + 1), in our opinion, is a single instruction, but for the bottom layer, the instruction will be decomposed into multiple instructions (load: load variables; add: execute add operations; store: store variable values); It should be noted that a thread may be replaced by the operating system after executing any instruction (when there are no atomic operations or other lock operations). In this case, the following situation may occur:
That is, an add instruction is replaced during execution, and its add operation has not been completed at this time; The subtraction thread has been executed for replacement. When it reads the shared variable value, because the last operation of adding thread has not been completed and the variable value has not been updated, it reads the last value, which leads to the problem of data inconsistency.
To ensure correct logic, when reading and writing shared variables, you must ensure that a group of instructions are executed atomically: that is, when a thread executes, other threads must wait:
By locking and unlocking, it can be ensured that three instructions are always executed by one thread, and no other thread will enter this instruction interval. Even if a thread is interrupted by the operating system during execution, other threads cannot enter this instruction interval because they cannot obtain a lock. Only after the execution thread releases the lock can other threads have the opportunity to obtain the lock and execute. This code block between locking and unlocking is called Critical Section. At most one thread in the Critical Section can execute at any time
Java programs use the synchronized keyword to lock an object: synchronized (object) {...}; Note: when entering the synchronized code block, obtain the lock of the specified object. When exiting the synchronized code block, the lock of the object will be released:
public class Main { public static void main(String[] args) throws Exception { var add = new AddThread(); var dec = new DecThread(); add.start(); dec.start(); add.join(); dec.join(); System.out.println(Counter.count); } } class Counter { public static final Object lock = new Object(); // Create a lock object public static int count = 0; } class AddThread extends Thread { public void run() { for (int i=0; i<10000; i++) { synchronized(Counter.lock) { Counter.count += 1; } } } } class DecThread extends Thread { public void run() { for (int i=0; i<10000; i++) { synchronized(Counter.lock) { Counter.count -= 1; } } } }
- Because it can only be run serially when passing through the synchronized statement block, synchronized will reduce the execution efficiency of the program
- Actions that do not require synchronized:
JVM The specification defines several atomic operations: Basic type( long and double (except) assignment, for example: int n = m; Reference type assignment, for example: List<String> list = anotherList. //Long and double are 64 bit data. The JVM does not specify whether the 64 bit assignment operation is an atomic operation. However, the JVM on x64 platform implements the assignment of long and double as atomic operations
Note: synchronized is not required for single line assignment statements to ensure data synchronization. However, in case of multi line assignment statements, it is still necessary to artificially ensure data consistency, but the assignment statements can be converted through certain methods to make them atomic:
class Pair { // Before transformation int first; int last; public void set(int first, int last) { synchronized(this) { this.first = first; this.last = last; } } } class Pair { // After transformation int[] pair; public void set(int first, int last) { int[] ps = new int[] { first, last }; this.pair = ps; } }
7. Synchronization method
- In the above example, we give the permission to obtain the lock to the thread (that is, the thread decides who gets the lock). This operation is complex and easy to cause logical confusion
- A better way is to encapsulate the synchronized logic (put the lock logic in the execution method of the operation object, and the thread does not need to actively obtain the lock permission):
public class Counter { private int count = 0; public void add(int n) { synchronized(this) { count += n; } } public void dec(int n) { synchronized(this) { count -= n; } } public int get() { return count; } }
- If a class is designed to allow multiple threads to access it correctly, we say that this class is * * thread safe**
- Some invariant classes, such as String, Integer and LocalDate, all their member variables are final. When multiple threads access at the same time, they can only read but not write. These invariant classes are also thread safe
- Classes like Math that only provide static methods without member variables are thread safe
- Unless otherwise specified, a class is non thread safe by default.
- When we lock this instance, we can actually modify this method with synchronized. The following two expressions are equivalent:
// Writing method I public void add(int n) { synchronized(this) { // Lock this count += n; } // Unlock } // Writing method 2 public synchronized void add(int n) { // Lock this count += n; } // Unlock
- The method modified with synchronized is the synchronous method, which means that the whole method must be locked with this instance
- Any Class has a Class instance automatically created by the JVM. Therefore, add synchronized to the static method to lock the Class instance of the Class, for example:
public synchronized static void test(int n) { ... } // Equivalent to ============================== > public class Counter { public static void test(int n) { synchronized(Counter.class) { ... } } }
8. Deadlock
- Java's thread lock is a reentrant lock: the JVM allows the same thread to acquire the same lock repeatedly. This lock that can be acquired repeatedly by the same thread is called a reentrant lock
- Because the thread lock of Java is a reentrant lock, when acquiring a lock, you should not only judge whether it is the first acquisition, but also record how many times it is acquired. Every time the lock is acquired, record + 1. Every time the synchronized block is exited, record - 1. When it is reduced to 0, the lock will be released
- When acquiring multiple locks, different threads acquire locks of multiple different objects, which may lead to deadlock. For example, in this case:
public void add(int m) { synchronized(lockA) { // Obtain lock of lockA this.value += m; synchronized(lockB) { // Obtain lock of lockB this.another += m; } // Release the lock of lockB } // Release the lock of lockA } public void dec(int m) { synchronized(lockB) { // Obtain lock of lockB this.another -= m; synchronized(lockA) { // Obtain lock of lockA this.value -= m; } // Release the lock of lockA } // Release the lock of lockB }
- After a deadlock occurs, there is no mechanism to release the deadlock, and the JVM process can only be forcibly terminated
9. Use wait and notify
- The principle of multi thread coordinated operation is: when the conditions are not met, the thread enters the waiting state; When the conditions are met, the thread is awakened and continues to execute the task
- wait() method:
1. wait()Method can only be used in synchronized(lock)Used in statement blocks 2. wait()Methods can only be called by lock objects, as described above lock.wait(),Another example this.wait()(If the locked object is this) 3. If it can be implemented wait(),It means that the current thread has obtained the specified lock object, and all other code blocks requiring the lock object cannot be executed 4. wait()The effect of the method is that the current thread abandons the lock object and enters the waiting state 5. wait()Method has no return value. Only when other threads release the lock of the object and "wake up" the thread can the thread get the lock object again and continue to execute 6. wait()The underlying implementation of the method is native Method( c Method)
- notify() method:
7. notify()Method can only be used in synchronized(lock)Used in statement blocks 8. notify()Methods can only be called by lock objects, such as lock.notify(),Another example this.notify() 9. notify()Method will wake up the thread in the waiting state due to the lock object and return the lock object to the waiting thread 10.If there is no thread waiting because of the lock object, there is no execution effect
- Example:
public class Main { public static void main(String[] args) throws InterruptedException { var q = new TaskQueue(); var ts = new ArrayList<Thread>(); for (int i=0; i<5; i++) { var t = new Thread() { public void run() { // Execute task: while (true) { try { String s = q.getTask(); System.out.println("execute task: " + s); } catch (InterruptedException e) { return; } } } }; t.start(); ts.add(t); } var add = new Thread(() -> { for (int i=0; i<10; i++) { // Put task: String s = "t-" + Math.random(); System.out.println("add task: " + s); q.addTask(s); try { Thread.sleep(100); } catch(InterruptedException e) {} } }); add.start(); add.join(); Thread.sleep(100); for (var t : ts) { t.interrupt(); } } } class TaskQueue { Queue<String> queue = new LinkedList<>(); public synchronized void addTask(String s) { this.queue.add(s); this.notifyAll(); } public synchronized String getTask() throws InterruptedException { while (queue.isEmpty()) { this.wait(); } return queue.remove(); } }
10. Use ReentrantLock
- Starting with Java 5, an advanced java.util.concurrent package is introduced to deal with concurrency. It provides a large number of more advanced concurrency functions, which can greatly simplify the writing of multithreaded programs
- The Java language directly provides the synchronized keyword for locking, but this kind of lock is very heavy. Second, you must wait all the time when obtaining it, and there is no additional attempt mechanism
- ReentrantLock provided by the java.util.concurrent.locks package is used to replace synchronized locking
- Code transformation: (realize the same function of synchronized based on ReentrantLock):
public class Counter { private final Lock lock = new ReentrantLock(); private int count; public void add(int n) { lock.lock(); try { count += n; } finally { lock.unlock(); } } }
- synchronized is the syntax provided at the Java language level, so we don't need to consider exceptions. ReentrantLock is the lock implemented by java code. We must first obtain the lock and then release the lock correctly in finally
- ReentrantLock is a reentrant lock. Like synchronized, a thread can acquire the same lock multiple times
- ReentrantLock can attempt to acquire a lock:
if (lock.tryLock(1, TimeUnit.SECONDS)) { //Parameter 1 indicates the maximum number of waiting time units, and parameter 2 indicates the length of time units try { ... } finally { lock.unlock(); } }
When the above code tries to obtain the lock, it can wait for 1 second at most. If the lock is not obtained after 1 second, tryLock() returns false, and the program can do some additional processing instead of waiting indefinitely
- Using ReentrantLock is safer than using synchronized directly. Threads will not cause deadlock when tryLock() fails
- A short test code is attached here. Those interested can view the corresponding results by modifying the waiting time:
public class MulThread_05 { public static ReentrantLock lock = new ReentrantLock(); // Create lock object public static void main(String[] args) throws InterruptedException { lock.lock(); // The main thread acquires the lock object System.out.println("main thread: I get the lock !!"); new MyThread_1().start(); Thread.sleep(3000); lock.unlock(); System.out.println("main thread: ok let it go !!"); System.out.println("main thread end !!"); } } class MyThread_1 extends Thread { @Override public void run() { try { if(MulThread_05.lock.tryLock(4, TimeUnit.SECONDS)) { try { System.out.println("this thread: I get the lock !!!"); }finally { MulThread_05.lock.unlock(); } }else { System.out.println("this thread: whatever I give it up !!"); } } catch (InterruptedException e) { e.printStackTrace(); } } }
11. Use Condition
- Condition object can cooperate with ReentrantLock to realize wait and notify functions
- When using Condition, the referenced Condition object must be returned from newCondition() of Lock instance to obtain a Condition instance bound to Lock instance. That is, a Condition object is bound to a Lock object. A Lock can create multiple Condition objects, but the Condition object must be attached to the Lock object
- The * * await(), signal(), signalAll() * * principles provided by Condition are consistent with the wait(), notify() and notifyAll() of synchronized lock objects, and their behaviors are the same:
1. await()It will release the current lock and enter the waiting state; 2. signal()Will wake up a waiting thread; 3. signalAll()Will wake up all waiting threads; 4. Wake up thread from await()After returning, you need to regain the lock.
- Similar to tryLock(), await() can wake itself up after waiting for a specified time if it has not been awakened by other threads through signal() or signalAll():
if (condition.await(1, TimeUnit.SECOND)) { // Wake up by another thread } else { // No other thread wakes up within the specified time }
12. Use ReadWriteLock
- In some cases, the protection of ReentrantLock is too radical: (only one thread is allowed to enter the critical area). In fact, the read method that will not modify the object content can not be protected. At this time, RenentrantLock cannot meet the use requirements
- What you want to achieve is: multiple threads are allowed to read at the same time, but as long as one thread is writing, other threads must wait. Using ReadWriteLock can solve this problem
- ReadWriteLock guarantees:
1. Only one thread is allowed to write (other threads can neither write nor read); 2. When there is no write, multiple threads are allowed to read at the same time (improve performance).
- The ReadWriteLock feature is easy to implement. We need to create a ReadWriteLock instance and obtain the read lock and write lock respectively:
public class Counter { private final ReadWriteLock rwlock = new ReentrantReadWriteLock(); private final Lock rlock = rwlock.readLock(); private final Lock wlock = rwlock.writeLock(); private int[] counts = new int[10]; public void inc(int index) { wlock.lock(); // Write lock try { counts[index] += 1; } finally { wlock.unlock(); // Release write lock } } public int[] get() { rlock.lock(); // Read lock try { return Arrays.copyOf(counts, counts.length); } finally { rlock.unlock(); // Release read lock } } }
- When using ReadWriteLock, the applicable condition is that the same data is read by a large number of threads, but only a few threads modify it
13. Use StampedLock
- There is a potential problem with ReadWriteLock: if a thread is reading, the write thread needs to wait for the read thread to release the lock before obtaining the write lock, that is, writing is not allowed during reading. This is a pessimistic read lock
- Java 8 introduces a new read-write lock: StampedLock
- Compared with ReadWriteLock, StampedLock is improved in that it also allows writing after obtaining the write lock during reading! In this way, the data we read may be inconsistent. Therefore, we need some additional code to judge whether there are writes in the process of reading. This kind of read lock is an optimistic lock
- Optimistic lock: it is optimistic to estimate that there will be no write in the process of reading. Pessimistic lock: write is rejected during reading, that is, write must wait. Obviously, optimistic locks have higher concurrency efficiency, but once a small probability of writing leads to inconsistent read data, it needs to be detected and re read
- Example:
public class Point { private final StampedLock stampedLock = new StampedLock(); private double x; private double y; public void move(double deltaX, double deltaY) { long stamp = stampedLock.writeLock(); // Get write lock try { x += deltaX; y += deltaY; } finally { stampedLock.unlockWrite(stamp); // Release write lock } } public double distanceFromOrigin() { long stamp = stampedLock.tryOptimisticRead(); // Get an optimistic read lock // Note that the following two lines of code are not atomic operations // Suppose x, y = (100200) double currentX = x; // x=100 has been read here, but x and Y may be modified to (300400) by the write thread double currentY = y; // y has been read here. If it is not written, the reading is correct (100200) // If there is a write, the read is wrong (100400) if (!stampedLock.validate(stamp)) { // Check whether there are other write locks after reading the lock stamp = stampedLock.readLock(); // Get a pessimistic read lock try { currentX = x; currentY = y; } finally { stampedLock.unlockRead(stamp); // Release read lock } } return Math.sqrt(currentX * currentX + currentY * currentY); } }
- Compared with ReadWriteLock, the locking of writing is exactly the same, but the difference is reading. Notice that first, we obtain an optimistic read lock through tryOptimisticRead() and return the version number (stamp). Then read. After reading, we verify the version number through validate(). If the version number is not written in the reading process, the version number remains unchanged, and the verification is successful, we can safely continue the follow-up operation. If there is a write during reading, the version number will change and the verification will fail. In case of failure, we read again by obtaining the pessimistic read lock. Because the probability of writing is not high, the program can obtain data through optimistic read lock in most cases, and pessimistic read lock in very few cases
- The cost of stampedlock: first, the code is more complex; second, stampedlock is a non reentrant lock, which cannot repeatedly obtain the same lock in a thread
- StampedLock also provides a more complex function of upgrading pessimistic read locks to write locks. It is mainly used in the if then update scenario: read first, return if the read data meets the conditions, and try to write if the read data does not meet the conditions
14. Use Concurrent set
- The java.util.concurrent package provides a variety of thread safe collections, such as ArrayBlockingQueue, List, Map, Set, Deque, etc
- The java.util.concurrent package also provides corresponding concurrent collection classes:
- Using these concurrent collections is exactly the same as using non thread safe collection classes
- The java.util.Collections tool class also provides an old thread safe collection converter to convert thread unsafe collections into thread safe collections, which can be used as follows:
Map unsafeMap = new HashMap(); Map threadSafeMap = Collections.synchronizedMap(unsafeMap);
In fact, it wraps a non thread safe Map with a wrapper class, and then locks all read and write methods with synchronized. In this way, the performance of the thread safe collection is much lower than that of the java.util.concurrent collection, so it is not recommended
15. Use Atomic
- The java.util.concurrent package of Java not only provides underlying locks and concurrent collections, but also provides a set of encapsulated classes for atomic operations, which are located in the java.util.concurrent.atomic package
- Take AtomicInteger as an example. Its main operations include:
1. Add value and return new value: int addAndGet(int delta) 2. Add 1 to return the new value: int incrementAndGet() 3. Get current value: int get() 4. use CAS Mode setting: int compareAndSet(int expect, int update)
- Atomic classes are thread safe access implemented in a lock free manner. Its main principle is to use CAS: compare and set (system support)
- Write incrementAndGet() by yourself through CAS, which is about as follows:
public int incrementAndGet(AtomicInteger var) { int prev, next; do { prev = var.get(); // Get current value next = prev + 1; // Get current value + 1 } while ( ! var.compareAndSet(prev, next)); // If the value of var is equal to prev, set the value of var to next and return true; //Otherwise, put back false and get the current value of VaR in the loop again (ensure the correctness of adding one to var) return next; }
CAS means that in this operation, if the current value of AtomicInteger is prev, it will be updated to next and return true. If the current value of AtomicInteger is not prev, it does nothing and returns false. Through CAS operation and do... While loop, even if other threads modify the value of AtomicInteger, the final result is correct
16. Use thread pool
- Although the Java language has built-in multithreading support, which is very convenient to start a new thread, creating a thread requires operating system resources (thread resources, stack space, etc.), and it takes a lot of time to create and destroy a large number of threads frequently
- If we can reuse a group of threads, we can let a group of threads execute many small tasks instead of one task corresponding to a new thread. This kind of thread pool can receive a large number of small tasks and distribute them
- Several threads are maintained in the thread pool. When there are no tasks, these threads are in a waiting state. If there is a new task, a free thread is assigned to execute it. If all threads are busy, the new task is either put into the queue or a new thread is added for processing
- The Java standard library provides the ExecutorService interface to represent the thread pool. Its typical usage is as follows:
// Create a fixed size thread pool: ExecutorService executor = Executors.newFixedThreadPool(3); // Submit task: executor.submit(task1); executor.submit(task2); executor.submit(task3); executor.submit(task4); executor.submit(task5);
- ExecutorService is just an interface. Several common implementation classes provided by the Java standard library are:
1. FixedThreadPool: A thread pool with a fixed number of threads; 2. CachedThreadPool: Thread pool whose number of threads is dynamically adjusted according to the task; 3. SingleThreadExecutor: Thread pool for single thread execution only.
The methods that create these thread pools are encapsulated in the Executors class
- Take FixedThreadPool as an example to see the execution logic of thread pool:
import java.util.concurrent.*; public class Main { public static void main(String[] args) { // Create a fixed size thread pool: ExecutorService es = Executors.newFixedThreadPool(4); for (int i = 0; i < 6; i++) { es.submit(new Task("" + i)); } // Close thread pool: es.shutdown(); } } class Task implements Runnable { private final String name; public Task(String name) { this.name = name; } @Override public void run() { System.out.println("start task " + name); try { Thread.sleep(1000); } catch (InterruptedException e) { } System.out.println("end task " + name); } }
Execution results:
start task 0 start task 1 start task 2 start task 3 end task 1 start task 4 end task 0 start task 5 end task 2 end task 3 end task 5 end task 4
- The thread pool is closed at the end of the program. When using the shutdown() method to close the thread pool, it will wait for the executing task to complete first and then close it. shutdownNow() will immediately stop the task being executed, and awaitTermination() will wait for the specified time to shut down the thread pool
- Create a dynamically adjusted thread pool with 4 ~ 10 threads:
// Executors.newCachedThreadPool() method source code public static ExecutorService newCachedThreadPool() { // What is actually returned is a ThreadPoolExecutor object return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); } // So we can create it this way: int min = 4; int max = 10; ExecutorService es = new ThreadPoolExecutor(min, max, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
- There is also a task that needs to be performed repeatedly on a regular basis, such as refreshing the securities price per second. This task itself is fixed and needs to be executed repeatedly. You can use ScheduledThreadPool. Tasks placed in the ScheduledThreadPool can be executed repeatedly on a regular basis
- Creating a ScheduledThreadPool is still through the Executors class:
ScheduledExecutorService ses = Executors.newScheduledThreadPool(4);
- Submit a one-time task, which will execute only once after the specified delay:
// Perform a one-time task in 1 second: ses.schedule(new Task("one-time"), 1, TimeUnit.SECONDS);
- The task is executed at a fixed rate of every 3 seconds:
// Start to execute the scheduled task after 2 seconds, and execute it every 3 seconds: ses.scheduleAtFixedRate(new Task("fixed-rate"), 2, 3, TimeUnit.SECONDS);
- The task is executed at a fixed interval of 3 seconds:
// Start to execute the scheduled task after 2 seconds and execute it at an interval of 3 seconds: ses.scheduleWithFixedDelay(new Task("fixed-delay"), 2, 3, TimeUnit.SECONDS);
The difference between FixedRate and FixedDelay: FixedRate means that a task is always triggered at a fixed time interval, no matter how long the task is executed; FixedDelay refers to waiting for a fixed time interval after the last task is executed before executing the next task
The Java standard library also provides a java.util.Timer class, which can also execute tasks regularly. However, a Timer corresponds to a Thread. Therefore, a Timer can only execute one task regularly. Multiple timers must be started for multiple scheduled tasks, and a ScheduledThreadPool can schedule multiple scheduled tasks, We can completely replace the old Timer with ScheduledThreadPool
Note: multi scheduling here means that a ScheduledThreadPool can create multiple execution queues, and the scheduled tasks in a queue are not executed concurrently (see the analysis in the next point for details)
Answer two questions:
Question 1: in the FixedRate mode, assuming that a task is triggered every second, if the execution time of a task exceeds 1 second, will subsequent tasks be executed concurrently?
A: it will not be executed concurrently
Question 2: if the task throws an exception, do the subsequent tasks continue to execute?
A: if the current task throws an exception, subsequent tasks will stop executing
The test code is as follows:
public class MulThread_08 { public static void main(String[] args) throws InterruptedException { ScheduledExecutorService ses = Executors.newScheduledThreadPool(4); // Create a thread pool of size 4 // Specify a fixed cycle task for the thread pool, that is, whether the current task is completed or not, start executing the next task after the specified period ses.scheduleAtFixedRate(new MyTask(), 1, 1, TimeUnit.SECONDS); ses.scheduleAtFixedRate(new MyTask2(), 1, 1, TimeUnit.SECONDS); boolean b = ses.awaitTermination(20, TimeUnit.SECONDS); } } class MyTask implements Runnable { @Override public void run() { try { int id = idGetter.get_id(); System.out.println("Thread " + id + " start !!"); Thread.sleep(5000); System.out.println("Thread " + id + " end !!"); } catch (InterruptedException e) { e.printStackTrace(); } } } class MyTask2 implements Runnable { @Override public void run() { try { System.out.println("Task2" + " start !!"); Thread.sleep(1); System.out.println("Task2" + " end !!"); } catch (InterruptedException e) { e.printStackTrace(); } } } class idGetter { static AtomicLong id = new AtomicLong(0); public static int get_id() { return (int) id.incrementAndGet(); } }
17. Use Future
- There is a problem with the Runnable interface. Its method has no return value. If a task needs a return result, it can only be saved to variables, and additional methods are provided to read, which is very inconvenient. Therefore, the Java standard library also provides a Callable interface, which has one more return value than the Runnable interface:
class Task implements Callable<String> { public String call() throws Exception { return longTimeCalculation(); } }
The Callable interface is a generic interface that can return results of a specified type
- How to get the result of asynchronous execution?
The ExecutorService.submit() method returns a Future type. An instance of Future type represents an object that can get results in the Future
ExecutorService executor = Executors.newFixedThreadPool(4); // Define tasks: Callable<String> task = new Task(); // Submit the task and get Future: Future<String> future = executor.submit(task); // Get the results returned by asynchronous execution from Future: String result = future.get(); // May block
- When we submit a Callable task, we will obtain a Future object at the same time. Then, we can call the get() method of the Future object at some time in the main thread to obtain the result of asynchronous execution. When we call get(), if the asynchronous task has been completed, we get the result directly. If the asynchronous task has not completed yet, get() will block and will not return the result until the task is completed
- A Future interface represents a result that may be returned in the Future. It defines the following methods:
get(): Get results (may wait) get(long timeout, TimeUnit unit): Obtain the result, but only wait for the specified time; cancel(boolean mayInterruptIfRunning): Cancel the current task; isDone(): Determine whether the task has been completed.
18. Use completable future
- When using Future to obtain asynchronous execution results, either call the blocking method get() or poll to see if isDone() is true. Both methods are not very good because the main thread will also be forced to wait
- Java 8 began to introduce completable Future, which is improved for the Future. You can pass in the callback object. When the asynchronous task is completed or an exception occurs, the callback method of the callback object will be called automatically
- Take the stock price as an example to see how to use completable future:
public class Main { public static void main(String[] args) throws Exception { // To create an asynchronous execution task: CompletableFuture<Double> cf = CompletableFuture.supplyAsync(Main::fetchPrice); // If successful: cf.thenAccept((result) -> { System.out.println("price: " + result); }); // If execution is abnormal: cf.exceptionally((e) -> { e.printStackTrace(); return null; }); // Do not end the main thread immediately, otherwise the thread pool used by completable future by default will be closed immediately: Thread.sleep(200); } static Double fetchPrice() { try { Thread.sleep(100); } catch (InterruptedException e) { } if (Math.random() < 0.3) { throw new RuntimeException("fetch price failed!"); } return 5 + Math.random() * 20; } }
- Creating a completabilefuture is implemented through completabilefuture. Supplyasync(). It requires an object that implements the Supplier interface:
public interface Supplier<T> { T get(); }
Here, the lambda syntax is used to simplify it and directly pass in Main::fetchPrice, because the signature of the static method of Main.fetchPrice() conforms to the definition of the Supplier interface (except for the method name)
- After the completable future is created, it has been submitted to the default thread pool for execution. We need to define the instances that need callback when completable future is completed and when exceptions occur
- When completed, completabilefuture calls the Consumer object:
public interface Consumer<T> { void accept(T t); }
- In case of exception, completabilefuture will call the Function object:
public interface Function<T, R> { R apply(T t); }
lambda syntax is used here to simplify the code
- The advantages of completable future are:
1. When the asynchronous task ends, it will automatically call back the method of an object; 2. When an asynchronous task makes an error, it will automatically call back the method of an object; 3. After setting the callback, the main thread no longer cares about the execution of asynchronous tasks.
- The more powerful function of completable future is that multiple completable futures can be executed serially. For example, two completable futures are defined. The first completable future queries the securities code according to the securities name, and the second completable future queries the securities price according to the securities code
public class Main { public static void main(String[] args) throws Exception { // First task: CompletableFuture<String> cfQuery = CompletableFuture.supplyAsync(() -> { return queryCode("PetroChina"); }); // cfQuery succeeds. Continue to the next task: CompletableFuture<Double> cfFetch = cfQuery.thenApplyAsync((code) -> { return fetchPrice(code); }); // cfFetch successfully prints the result: cfFetch.thenAccept((result) -> { System.out.println("price: " + result); }); // Do not end the main thread immediately, otherwise the thread pool used by completable future by default will be closed immediately: Thread.sleep(2000); } static String queryCode(String name) { try { Thread.sleep(100); } catch (InterruptedException e) { } return "601857"; } static Double fetchPrice(String code) { try { Thread.sleep(100); } catch (InterruptedException e) { } return 5 + Math.random() * 20; } }
- In addition to serial execution, multiple completable future can also be executed in parallel. For example, we consider a scenario where we query the securities code from Sina and Netease at the same time. As long as any one returns the result, we will query the price in the next step. As long as any one returns the result, we will complete the operation
public class Main { public static void main(String[] args) throws Exception { // Two completable future execute asynchronous queries: CompletableFuture<String> cfQueryFromSina = CompletableFuture.supplyAsync(() -> { return queryCode("PetroChina", ""); }); CompletableFuture<String> cfQueryFrom163 = CompletableFuture.supplyAsync(() -> { return queryCode("PetroChina", ""); }); // Merge anyOf into a new completable future: CompletableFuture<Object> cfQuery = CompletableFuture.anyOf(cfQueryFromSina, cfQueryFrom163); // Two completable future execute asynchronous queries: CompletableFuture<Double> cfFetchFromSina = cfQuery.thenApplyAsync((code) -> { return fetchPrice((String) code, ""); }); CompletableFuture<Double> cfFetchFrom163 = cfQuery.thenApplyAsync((code) -> { return fetchPrice((String) code, ""); }); // Merge anyOf into a new completable future: CompletableFuture<Object> cfFetch = CompletableFuture.anyOf(cfFetchFromSina, cfFetchFrom163); // Final result: cfFetch.thenAccept((result) -> { System.out.println("price: " + result); }); // Do not end the main thread immediately, otherwise the thread pool used by completable future by default will be closed immediately: Thread.sleep(200); } static String queryCode(String name, String url) { System.out.println("query code from " + url + "..."); try { Thread.sleep((long) (Math.random() * 100)); } catch (InterruptedException e) { } return "601857"; } static Double fetchPrice(String code, String url) { System.out.println("query price from " + url + "..."); try { Thread.sleep((long) (Math.random() * 100)); } catch (InterruptedException e) { } return 5 + Math.random() * 20; } }
- anyOf() can realize "any completable future needs only one success", allOf() can realize "all completable future must succeed", and these combined operations can realize very complex asynchronous process control
- Note the naming rules of completable future:
1. xxx(): Indicates that the method will continue to execute in the existing thread; 2. xxxAsync(): Indicates that asynchronous execution will be performed in the thread pool.
19. Use ForkJoin
- Java 7 began to introduce a new Fork/Join thread pool, which can perform a special task: breaking a large task into multiple small tasks for parallel execution
- Principle of Fork/Join task: judge whether a task is small enough. If so, calculate it directly. Otherwise, divide it into several small tasks and calculate them separately. This process can be repeatedly "fission" into a series of small tasks
- Example:
public class Main { public static void main(String[] args) throws Exception { // Create an array of 2000 random numbers: long[] array = new long[2000]; long expectedSum = 0; for (int i = 0; i < array.length; i++) { array[i] = random(); expectedSum += array[i]; } System.out.println("Expected sum: " + expectedSum); // fork/join: ForkJoinTask<Long> task = new SumTask(array, 0, array.length); long startTime = System.currentTimeMillis(); Long result = ForkJoinPool.commonPool().invoke(task); long endTime = System.currentTimeMillis(); System.out.println("Fork/join sum: " + result + " in " + (endTime - startTime) + " ms."); } static Random random = new Random(0); static long random() { return random.nextInt(10000); } } class SumTask extends RecursiveTask<Long> { static final int THRESHOLD = 500; long[] array; int start; int end; SumTask(long[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override protected Long compute() { if (end - start <= THRESHOLD) { // If the task is small enough, calculate directly: long sum = 0; for (int i = start; i < end; i++) { sum += this.array[i]; // Deliberately slow down the calculation speed: try { Thread.sleep(1); } catch (InterruptedException e) { } } return sum; } // The task is too big and divided into two:; } }
- Fork/Join thread pool is applied in Java standard library. The java.util.Arrays.parallelSort(array) provided by the Java standard library can perform parallel sorting. Its principle is to perform parallel sorting on large array splitting through Fork/Join internally, which can greatly improve the sorting speed on multi-core CPU s
20. Use ThreadLocal
- Background: in real business, based on the implementation method of multithreading, we will let a thread execute a main method. It can be imagined that when the business logic is complex, other format methods may be called in this method; One scheme is to directly assign the main method parameters to each word method during method call, but this method will cause a serious problem: the same data is "copied" many times, which is a serious waste
- In a thread, the objects that need to be passed across several method calls are usually called Context. It is a state, which can be user identity, task information, etc
- Adding a context parameter to each method is very troublesome, and sometimes, if the call chain has a third-party library that cannot modify the source code, the context cannot be transmitted
- The Java standard library provides a special ThreadLocal, which can pass the same object in a thread
- ThreadLocal instances are usually initialized with static fields as follows:
static ThreadLocal<User> threadLocalUser = new ThreadLocal<>();
- Typical usage is as follows:
void processUser(user) { try { threadLocalUser.set(user); step1(); step2(); } finally { threadLocalUser.remove(); } }
By setting a User instance to be associated with ThreadLocal, all methods can get the User instance at any time before removal:
void step1() { User u = threadLocalUser.get(); log(); printUser(); } void log() { User u = threadLocalUser.get(); println(u.name); } void step2() { User u = threadLocalUser.get(); checkUser(u.id); }
Note that ordinary method calls must be executed by the same thread. Therefore, the User object obtained by threadLocalUser.get() in step 1 (), step 2 () and log() methods is the same instance
- ThreadLocal can be regarded as a global map < Thread, Object >: when each Thread obtains the ThreadLocal variable, it always uses the Thread itself as the key:
Object threadLocalValue = threadLocalMap.get(Thread.currentThread());
ThreadLocal is equivalent to opening up an independent storage space for each thread, and the instances associated with ThreadLocal of each thread do not interfere with each other (only one ThreadLocal object is required, and the same ThreadLocal object can store context for multiple threads, which is a one to many relationship)
Note that ThreadLocal must be cleared in finally
Because the current thread is likely to be put back into the thread pool after executing relevant codes. If ThreadLocal is not cleared, the thread will bring in the last state when executing other codes.
In order to ensure that the ThreadLocal associated instance can be released, we can use the autoclosable interface with the try (resource) {...} structure to let the compiler close automatically for us. For example, a ThreadLocal that stores the current user name can be encapsulated as a UserContext object:
public class UserContext implements AutoCloseable { static final ThreadLocal<String> ctx = new ThreadLocal<>(); public UserContext(String user) { ctx.set(user); } public static String currentUser() { return ctx.get(); } @Override public void close() { ctx.remove(); } }
When using, we use the try (resource) {...} structure to write:
try (var ctx = new UserContext("Bob")) { // UserContext.currentUser() can be called arbitrarily: String currentUser = UserContext.currentUser(); } // Here, the UserContext.close() method is automatically called to release the ThreadLocal associated object
In this way, ThreadLocal is completely encapsulated in UserContext. External code can call UserContext.currentUser() to obtain the user name bound by the current thread at any time inside try (resource) {...} | https://programmer.group/summary-of-java-multithreading-basics.html | CC-MAIN-2021-49 | refinedweb | 8,023 | 52.9 |
How to: Build a Multifile Assembly
This article explains how to create a multifile assembly and provides code that illustrates each step in the procedure.
To create a multifile assembly
Compile all files that contain namespaces referenced by other modules in the assembly into code modules. The default extension for code modules is .netmodule.
For example, let's say the Stringer file has a namespace called myStringer, which includes.
Compile all other modules, using the necessary compiler options to indicate the other modules that are referenced in the code. This step uses the /addmodule compiler option.
In the following example, a code module called Client has an entry point Main method that references a method in the Stringer.dll module created in step 1.
using System; using myStringer; //The namespace created in Stringer.netmodule. class MainClientApp { // Static method Main is the entry point method. public static void Main() { Stringer myStringInstance = new Stringer(); Console.WriteLine("Client code executes");.
Use the Assembly Linker (Al.exe) to create the output file that contains the assembly manifest. This file contains reference information for all modules or resources that are part of the assembly.. | http://msdn.microsoft.com/en-us/library/226t7yxe(v=vs.120).aspx | CC-MAIN-2014-15 | refinedweb | 189 | 50.63 |
igo alternatives and similar packages
Based on the "Go Tools" category.
Alternatively, view igo alternatives based on common mentions on social networks and blogs.
OctoLinker9.2 9.2 L5 igo VS OctoLinkerOctoLinker — Links together, what belongs together
go-callvis8.9 1.9 igo VS go-callvisVisualize call graph of a Go program using Graphviz
JSON-to-Go8.9 2.3 igo VS JSON-to-GoTranslates JSON into a Go type in your browser instantly (original)
-
kube-prompt8.1 2.7 igo VS kube-promptAn interactive kubernetes client featuring auto-complete.
go-critic7.6 7.3 igo VS go-criticThe most opinionated Go source code linter for code audit.
The Go Play Space7.2 0.1 igo VS The Go Play SpaceAdvanced Go Playground frontend written in Go, with syntax highlighting, turtle graphics mode, and more
depth7.0 0.0 igo VS depthVisualize Go Dependency Trees
richgo6.7 4.2 igo VS richgoEnrich `go test` outputs with text decorations.
golang-tutorials6.0 0.0 igo VS golang-tutorialsGolang Tutorials. Learn Golang from Scratch with simple examples.
rts5.3 0.0 igo VS rtsRTS: request to struct. Generates Go structs from JSON server responses.
typex4.6 0.8 igo VS typex[TOOL, CLI] - Filter and examine Go type structures, interfaces and their transitive dependencies and relationships. Export structural types as TypeScript value object or bare type representations.
colorgo4.6 0.0 igo VS colorgoColorize (highlight) `go build` command output
xdg-go4.4 7.3 igo VS xdg-goGo implementation of the XDG Base Directory Specification and XDG user directories
-
gothanks4.2 0.0 igo VS gothanksGoThanks automatically stars Go's official repository and your go.mod github dependencies, providing a simple way to say thanks to the maintainers of the modules you use and the contributors of Go itself.
terminal-Task3.7 0.0 igo VS terminal-TaskTerminal tasks todo with reminder tool for geek
An exit strategy for go routines.An exit strategy for go routines
roumon3.2 6.1 igo VS roumonUniversal goroutine monitor using pprof and termui
generator-go-lang3.1 0.6 igo VS generator-go-langA Yeoman generator to get new Go projects started.
go-pkg-complete2.9 0.0 igo VS go-pkg-completebash completion for go and wgo
go-james2.8 2.2 igo VS go-jamesJames is your butler and helps you to create, build, debug, test and run your Go projects
go-lock2.7 2.9 igo VS go-lockgo-lock is a lock library implementing read-write mutex and read-write trylock without starvation
gomodrun1.9 1.3 igo VS gomodrunThe forgotten go tool that executes and caches binaries included in go.mod files.
Proofable1.9 4.5 igo VS ProofableGeneral purpose proving framework for certifying digital assets to public blockchains
PDF to Image Converter Using GolangThis project will help you to convert PDF file to IMAGE using golang.
try1.5 0.0 igo VS tryA go package that offers a try/catch statement block.
MessageBus implementation for CQRS projectsCQRS Implementation for Golang language
Crypt1.3 2.6 igo VS CryptCrypt implementation in pure Go
go-sanitize1.3 2.3 igo VS go-sanitize:bathtub: Golang library of simple to use sanitation functions
go-whatsonchain1.3 1.0 igo VS go-whatsonchain:link: Unofficial golang implementation for the WhatsOnChain API
go-slices1.2 0.0 igo VS go-slicesHelper functions for the manipulation of slices of all types in Go
golang-ifood-sdk1.1 8.7 igo VS golang-ifood-sdkGolang Ifood API SDK
go-preev1.0 2.3 igo VS go-preev:link: Unofficial golang implementation for the Preev API
docs0.9 8.0 igo VS docsAutomatically generate RESTful API documentation for GO projects - aligned with Open API Specification standard
go-pipl0.8 2.6 igo VS go-pipl:family_man_woman_boy: Unofficial golang implementation for the pipl.com search API
stl0.7 0.0 igo VS stlSTL reader and writer written in Go (mirror from GitLab)
go-bitindex0.5 1.4 igo VS go-bitindex:minidisc: Unofficial golang implementation for the BitIndex API
lcache0.4 3.5 igo VS lcacheLightweight LRU cache implementation
go-mattercloud0.4 0.0 igo VS go-mattercloud:cloud: Unofficial Go implementation for the MatterCloud API
go-polynym0.4 2.5 igo VS go-polynym:performing_arts: Unofficial golang implementation for the Polynym.io API
MrZ's go-cache0.4 6.6 igo VS MrZ's go-cache:bookmark_tabs: Cache dependency management on-top of the famous redigo package
go-api-router0.3 0.0 igo VS go-api-router:globe_with_meridians: A lightweight API middleware for Julien Schmidt's router: cors, logging, and standardized error handling
Golla0.3 0.0 igo VS GollaGo depencencies for dummies
vim-gos0.3 0.0 igo VS vim-gosVim commands to help you with GXML files.
gilbertBuild system and task runner for Go projects.
Peanut- 8.0 igo VS Peanut🐺 Deploy Databases and Services Easily for Development and Testing Pipelines. igo or a related project?
Popular Comparisons
README
Improved Go (igo)
Everyone knows that Go is a very verbose language. It takes numerous lines of code to do what a few lines of code can do in other languages. This is a deliberate design decision by the Go Authors.
The igo project provides various syntactical sugar to make your code simpler and easier to read. It works by allowing you to program in
*.igo files with the fancy new syntax. You then run
igo build to transpile your
igo files to standard
go files which you can then build as per normal.
- Address Operator (&)
- Constants and Functions
- Defers for for-loops
fordeferguarantees to run prior to the loop's current iteration exiting.
- Defer go
- Run defer statements in a goroutine
- must function
- Negative slice indices
NOTE: igo is pronounced ee-gohr
⭐ the project to show your appreciation.
What is included
- igofmt (auto format code)
- igo transpiler (generate standard go code)
Installation
Transpiler
go get -u github.com/rocketlaunchr/igo
Use
go install to install the executable.
Formatter
go get -u github.com/rocketlaunchr/igo/igofmt
Inspiration
Most professional front-end developers are fed up with standard JavaScript. They program using Typescript and then transpile the code to standard ES5 JavaScript. igo adds the same step to the build process.
Examples
Address Operator
The Address Operator allows you to use more visually pleasing syntax. There is no need for a temporary variable. It can be used with
string,
bool,
int,
float64 and function calls where the function returns 1 return value.
func main() { message := &"igo is so convenient" display(message) display(&`inline string`) display(&defaultMessage()) } func display(m *string) { if m == nil { fmt.Print("no message") } else { fmt.Print(*m) } } func defaultMessage() string { return "default message" }
Fordefer
See Blog post on why this is an improvement. It can be especially helpful in unit tests.
for { row, err := db.Query("SELECT ...") if err != nil { panic(err) } fordefer row.Close() }
Defer go
This feature makes Go's language syntax more internally consistent. There is no reason why
defer and
go should not work together.
mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { start := time.Now() // Transmit how long the request took to serve without delaying response to client. defer go transmitRequestStats(start) fmt.Fprintf(w, "Welcome to the home page!") })
Must builtin function
must is a "builtin" function that converts a multi-return value function (
"fn") into a single-return value function.
fn's final return value is expected to be of type
error.
must will panic upon
fn returning an error.
It is useful in scenarios where you know that no error will actually be returned by
fn and you just want to use the function inline. Alternatively, you may want to catch the error during local development because no error should be produced in production.
must also accepts an optional second argument of type
func(error) error.
import "database/sql" db := must(sql.Open("mysql", "host"))
LIMITATIONS
- Currently, it only works when
fnreturns two return values.
- It doesn't work when used outside of functions (i.e. initializing package variables).
- It works perfectly in simple cases. For more complex cases, peruse the generated code.
- A PR would be appreciated by an expert in the
go/typespackage. It is possible to create a truly generics-compatible
mustthat resolves the limitations above.
- Unlike real "builtin" functions,
mustis a reserved keyword.
Negative slice indices
You can use negative indices to refer to items in a slice starting from the back. It only works with constants and not variables.
x := []int{0, 1, 2, 3, 4} x[-3] // x[len(x)-3] x[-3:-1] // x[len(x)-3:len(x)-1]
How to use
Transpile
igo can accept numerous directories or igo files. The generated go files are saved alongside the igo files.
igo build [igo files...]
Format Code
igofmt will format your code to the standard form. It understands igo syntax.
igofmt [-s] [igo files...]
Configure your IDE to run
igofmt upon saving a
*.igo file.
-s will attempt to simplify the code by running
gofmt -s.
Design Decisions and Limitations
Pull-Requests are requested for the below deficiencies.
- For
fordefer:
gotostatements inside a for-loop that jump outside the for-loop is not implemented. Use
github.com/rocketlaunchr/igo/stackpackage manually in such cases.
goimportsequivalent has not been made.
- Address Operator for constants currently only supports
string,
bool,
float64and
int. The other int types are not supported. This can be fixed by using go/types package.
- Address Operator feature assumes you have not attempted to redefine
trueand
falseto something/anything else.
Tips & Advice
- Store the
igoand generated
gofiles in your git repository.
- Configure your IDE to run
igofmtupon saving a
*.igofile.
Legal Information
The license is a modified MIT license. Refer to the
LICENSE file for more details.
© 2018-20 PJ Engineering and Business Solutions Pty. Ltd.
Final Notes
Feel free to enhance features by issuing pull-requests.
*Note that all licence references and agreements mentioned in the igo README section above are relevant to that project's source code only. | https://go.libhunt.com/igo-alternatives | CC-MAIN-2021-31 | refinedweb | 1,667 | 51.44 |
Firedrop2: The Python Blog Client
Contents
Manual for the Firedrop plugin system. This includes using plugins,
writing plugins, and brief docs for the standard plugins.
Firedrop2 is the blog client tool for discerning Python programmers. It now
has a powerful mechanism for adding 'plugins' to it. This enables you to
add new features like spell checking, email, etc. to Firedrop2.
Firedrop2 comes with several plugins as standard. You might need to enable them
before you can use them, though. See Installing Plugins.
When you've done this, running Firedrop will show the 'plugin toolbar' with
several buttons on it - I recommend starting with InteractiveGUI and
SpellCheck. Clicking on their buttons will launch the respective plugin.
Configuring Firedrop2 to use plugins is very simple. You can either
configure plugins to be available all the time, or just for individual
blogs.
First of all the plugin files must be put in the 'plugins' directory. This is
in the main firedrop2 directory.
Next you need to configure Firedrop2 to use the plugin. This is done in
either the 'build.ini' for each site, or in a file called 'firedrop.ini'
in the main firedrop2 directory. Both of these recognise a plugins
keyword, which should be a list of all the plugins to use.
The name to use for the plugin is the name of the main filename minus the
'.py'. For example, two of the standard plugin files are
'InteractiveGUI.py' and 'FireSpell.py'. The line to include in the config
file is :
plugins = 'InteractiveGUI', 'FireSpell'
And that's all there is to it. If your distribution of Firedrop doesn't have a
'firedrop.ini', then just create one with any text editor. There may be
additional steps for individual plugins of course. For example, FireSpell, the
spell checker, needs a recent version of PyEnchant [1] to be installed.
This section briefly describes using the standard plugins that come with
Firedrop.
ROT13 and Hello are simple example plugins by Hans Nowak. They
illustrate creating plugins, and accessing mainframe attributes through them.
FireSpell is a spell checker for Firedrop2. It uses the PyEnchant module
by Ryan Kelly. It needs version 1.1.2 or more recent.
FireSpell probably comes enabled by default. In case it doesn't, see
Installing Plugins for the steps to install it. Even if your version of
Firedrop comes with the FireSpell files, you may need to add the following
line to either 'firedrop.ini' or 'build.ini' :
To use FireSpell, select the entry you want to spell check and hit the
SpellCheck button. This activates FireSpell, which should be
straightforward to use. Any words you Add to Dict will be saved in a
plain text file called 'pwl.txt' in the plugins directory.
PyEnchant comes with dictionaries for several languages. The default is 'en_US',
meaning US English. You can choose any of the alternatives from the drop down
list on FireSpell. Choosing a new language will cause this language to be the
default next time FireSpell is started. For more dictionaries, follow the
instructions for PyEnchant.
Hint
If you are a non-native English speaker, you may be interested in the
alternative set of dictionaries available for FireSpell. You can find these
at :.
The dictionary file needs to go in the myspell folder in your PyEnchant
distribution. On windows this would typically be at
C:\Python24\Lib\site-packages\enchant\share\enchant\myspell (or similar).
FireMail is a plugin that allows you to email your current post. This is a
feature of Blogger that I missed [2], so I've implemented it as a plugin. It
is capable of sending HTML emails or text. When sent as HTML the text version
of the post is also embedded so that people who don't like (or can't receive)
HTML emails will see the text version.
FireMail generates the HTML using a file called 'firemail_template.html'. The
mail server configuration should be done in a file called 'firemail.ini'. It
first looks for these files in the site directory, if it doesn't find them
there it looks in the plugin directory. This allows you to have different
settings for each blog, or one setting that applies to all your blogs.
Editing the config file causes the changes to be saved. You will need to give
it the name of your mail server. If you need to log in, it will need your
username and password.
The 'to address' can be a single email address, or a comma separated list.
Some email servers won't allow you to send email if you don't supply a 'from'
address.
The template file uses the normal Firedrop2 template system. If you correctly
set <base href=".... in the head of your template, then local references
in the generated HTML ought to be resolved correctly when the email is
received.
InteractiveGUI is a plugin for programmers. It gives you an interactive
shell into Firedrop2.
This means that all the attributes of mainframe are available as local
variables. The mainframe itself is present as self.
A useful value to inspect is active_entry, which is the currently
selected entry [3]. You can access the main editor pane as editor.
It's fully dynamic - try changing entry and watch editor.Value change.
It's particularly useful when creating new plugins.
Another plugin is called 'OutBox'. It's aimed at
programmers. It is only useful for Windows users who run firedrop.pyw.;
it will run on Mac OS X, but only for displaying errors (see below).
Once activated, it displays output from sys.stdout and sys.stderr (that
would normally be lost) in a display box. This is useful for debugging - you
can still see the output of print statements without having to have a console
box hanging around.
Once activated for the first time it caches all output, even when closed.
It's not enabled by default, of course.
Note that if you enable it, you should always put it last in the list of plugins :
plugins = 'InteractiveGUI', 'FireSpell', 'OutBox'
That's because if you have turned on debugging, as soon as OutBox is
activated it will grab all of the debug print statements you would normally see.
New in Firedrop2 version 0.2.2 is the Themes plugin. This provide a choice of
several different looks for your site. It's useful for new users who don't have a
detailed knowledge of CSS stylesheets, or templates, but still would
like to be able to vary the look of their site.
Each theme lives in the Themes folder inside the Firedrop folder. Each theme is comprised of a
stylesheet and some templates, as described above. To select a Theme, click on the Themes
plug-in button on the lower toolbar. You'll get the following dialog (as seen in Ubuntu Linux).
If you click on the name of a theme in the pull-down list, you'll see the description for that theme,
and below it, a screen capture of a blog page using the theme.
When you select a theme, a couple of things happen :
you will be prompted as to whether you want to proceed. This is your last chance to change your mind.
will be overwritten.
Item List, or Weblog, with the latter being most common.
The appropriate templates for your site type will be copied into your site folder. If all went well, you'll get a confirmation
of success:
invoke the Themes plugin again and choose a different look. Or go back to the default whitey-whites look.
Note
At the present, only the weblog type has stylesheets applied to its templates. If you'd like to help by extending the
themes to the other site types (article collection & item lists), please jump in!
If you would like to add a theme to the Firedrop project, by all means make a submission. Here's how :
Creating new plugins is not too difficult. You'll need a basic understanding of
Wax [4]. Thankfully this is very easy to learn and use. For help on learning
Wax, or coding plugins for Firedrop, join the Wax Mailing List.
Every plugin must have a plugin class, which will be imported by Firedrop2.
This class should be named pluginnamePlugin. 'pluginname' is the plugin
filename without the '.py', and the same name that should appear in
build.ini/firedrop.ini for Firedrop2 to use the plugin.
This class should have an OnClick method, which will be called when the
plugin button is used. OnClick receives one argument in addition to the usual
self - this is mainframe which is actually the main Firedrop instance.
Through this you (as a programmer) have access to all the entries and functions
in the currently opened Firedrop.
This is easily illustrated with a basic example :
class SillyExamplePlugin:
button_text = 'Silly Example'
def OnClick(self, mainframe):
print mainframe.editor.Value
Save the above code as SillyExample.py, put it in the plugin directory, and
add 'SillyExample' to your 'firedrop.ini'. When you run Firedrop you'll
see a new button 'Silly Example' on the plugin toolbar. Pressing this
causes the contents of the main editor window to be dumped on stdout [5].
You'll notice the 'magic' class variable button_text. If this is
present then its value is used for the plugin button.
Beyond this, writing plugins is simply a case of knowing the attributes of
mainframe. You probably also want to know Wax : both to understand the
methods available for elements of mainframe, and to construct a GUI for
your plugin.
Attributes of mainframe include :
See the InteractiveGUI Manual for a way to explore these objects live.
mainframe.editor in particular is the wax TextBox that forms the main
display. You can get and set its value through mainframe.editor.Value =
'something' and this_entry = mainframe.editor.Value. Note that
setting Value directly like this won't mark the entry as modified. If
the user navigates away from this entry without saving, the changes will be
lost. You'll need to call mainframe.editor.Modified = True to do this.
Most plugins (but not all) will have their own GUIs. It makes sense to do this
using Wax, with mainframe as the parent frame.
There are basically three possible techniques :
It's perfectly possible that your plugin doesn't need a GUI. It may just
transform text. Pressing the plugin button causes an action on the entry, but
doesn't launch a new window. See the example ROT13 plugin.
Code like this is probably better implemented as a method of
textmanipulator and added as a menu option. There's no reason it shouldn't
be done with a plugin though. You could use mainframe.fd2manager.getter()
and mainframe.fd2manager.setter(new_text) to work with the currently
selected text, or alternatively use the whole current entry.
If you want your plugin to launch as a child window you can create a subclass
of Frame in the usual way. mainframe is the parent window. This can run
alongside the main program, or you can set 'stay_on_top'.
See the InteractiveGUI plugin for a plugin that runs alongside Firedrop2. This
plugin includes code that checks to make sure you only have one InteractiveGUI
launched at a time. If there is already one open, pressing the plugin button
just sets the focus to that window.
In practice this is likely to be the most common way of writing plugins. Create
your plugin as a dialog and call ShowModal. Firedrop2 will freeze until
your plugin has returned. If you do this, with mainframe as the parent,
you can access the attributes of mainframe through self.Parent.
See FireSpell for an example of this behaviour. In this case FireSpell is a
subclass of CustomDialog which is the most flexible dialog to build on.
When the plugin returns, the OnClick of the pluginnamePlugin class will
have to make permanent any changes to the entry. One way to do that is for the
plugin to directly set editor.Value. In this case you will need to do
something like self.Parent.editor.Modified = True, so that Firedrop knows
the editor pane has been changed.
Return to Top
Part of the Firedrop2 Docs
Page last modified Sat Jun 03 23:48:04 2006.
Planet Firedrop | http://www.voidspace.org.uk/python/firedrop2/plugins.html | CC-MAIN-2018-51 | refinedweb | 2,040 | 67.76 |
Thursday, May 31, 2012 * Hardening Build Flags #552688 ** [ACTION] rra to close bug #552688 as resolved * node ↔ nodejs conflict #614907 ** [ACTION] vorlon to write up a resolution + for bug #614907 + based on (attached) * python maintainer #573745 ** [ACTION] vorlon to Wordsmith option ** Include option(s) originally proposed ** Remaining disputes with regards to python helpers? * Next meeting date -d @1340902800 * Constitutional Changes ** Supermajority ** Public/Private discussions
09:59:25 * rra is here. 10:00:02 * zack waves, I've proposed to the -ctte the idea of IRC meetings to periodically review pending issues, and in particular suggested to have this 1st meeting 10:00:13 <zack> beside that, I'm here mostly as a lurker, or in case my input is desired 10:01:05 <Ganneff> are "outsiders" supposed to speak or shutup? 10:01:49 -!- vorlon [~vorlon@becquer.dodds.net] has joined #debian-ctte 10:01:51 * vorlon waves 10:01:55 <Diziet> Hi all. 10:02:00 <dondelelcaro> I guess if they have something useful to say, it should be a problem... but if it becomes one, we make things more authoritarian 10:02:06 * rra waves. 10:02:07 <zack> Ganneff: I guess that if we outsiders shut up, unless asked otherwise, it will make it things simpler 10:02:16 <dondelelcaro> s/should/shouldn't/ 10:02:28 <vorlon> so do we have an agenda? :) 10:02:32 <dondelelcaro> bdale: did you manage to make things work? 10:02:37 -!- Topic for #debian-ctte: Next meeting May 31st 1700 UTC (date -d @1338483600) | Open issues: #614907: node <-> nodejs conflict, #573745: python maintainer; #636783: super-majority conflict; #552688: hardening build flags 10:02:37 -!- Topic set by dondelelcaro [~don@hemlock.ucr.edu] [Thu May 31 09:40:25 2012] 10:02:40 <rra> The channel topic is probably not a bad agenda. 10:03:04 <rra> I'd like to start by taking five minutes to dispose of #552688. 10:03:15 <dondelelcaro> sounds good to me 10:03:23 <Diziet> rra: Go ahead. 10:03:48 -!- mhy [~mark@gw.mhy.org.uk] has joined #debian-ctte 10:04:10 <rra> The hardening build flags have basically been resolved; I think the only question is whether we should just close the bug or whether we should hold a vote on it for the record. I'm happy to call for the vote, and I sent mail explaining why it made sense to me to vote on it, but the more I thought about it, the more I wasn't sure that logic was right. 10:04:23 <rra> So I wanted to poll people here: should we vote on it for the record, or should we just close it? 10:05:00 <dondelelcaro> it doesn't matter to me; since the outcome is acceptable, I think we can just close it unless someone disagrees 10:05:07 <Diziet> In general I would be happy just to close it. It has often been the case that TC members' intervention has got things sorted without making a formal resolution and we generally haven't recorded those either. 10:05:41 <Diziet> If we want it for `PR purposes' if you like, then perhaps we should start a new list of `issues resolved after they were brought to the TC but without the need for a formal vote'. 10:05:53 <Diziet> But I don't feel strongly. 10:06:29 <rra> I think that might not be a bad idea, but it's way down in my priority list and I should probably use those resources to catch up on Policy or whatnot. So if someone wanted to track that, I have no objections, but I'm not volunteering. :) 10:06:44 <vorlon> I found the argument to vote on it for the record persuasive, but maybe I haven't thought about it as much as you yet 10:07:27 <vorlon> but as it seems there's no strong feeling either way, I guess it's better to close the issue out rather than spending the energy on a formal vote 10:08:08 <rra> If anyone involved wanted whatever authoritative blessing a formal vote would convey, I think my argument would be stronger, but in this case I don't think that's the case. 10:08:22 <Diziet> Indeed. If anyone involved wanted it then we should do it. 10:08:34 <vorlon> rra: you'll close the bug as resolved, then? 10:08:39 <rra> Okay. Well, closing is reversible in case anyone who isn't here wants to do something different, so I'll just close it after this meeting. 10:08:47 <dondelelcaro> cool 10:08:50 <rra> We can always re-open if someone objects. 10:08:50 <vorlon> [ACTION] rra to close bug #552688 as resolved 10:09:01 <Diziet> OK 10:09:08 -!- dondelelcaro changed the topic of #debian-ctte to: Next meeting May 31st 1700 UTC (date -d @1338483600) | Open issues: #614907: node <-> nodejs conflict, #573745: python maintainer; #636783: super-majority conflict; #552688: hardening build flags [rra will close as resolved] 10:09:09 * vorlon wants a meetingbot ;) 10:09:17 <Ganneff> (hint: for the future meetings you should invite meetbot) 10:09:24 <Ganneff> talk to "darst" 10:09:43 <Diziet> Shall we do `node' next ? 10:09:51 <dondelelcaro> sure 10:09:52 <vorlon> sure 10:09:54 <rra> Works for me. 10:10:16 <Diziet> OK. So we had a plan that would involve allowing the ax25 version to leave a symlink behind to avoid breaking existing systems. 10:10:39 <Diziet> If we do that then new installs of ax25 wouldn't have `node' and of course nodejs wouldn't have it either. 10:11:13 <vorlon> FYI, my mail to the nodejs author requesting an upstream rename has gone unanswered 10:11:17 <Diziet> That seems to have been the last concrete thing proposed; there's been a lot of moral theorising too if I can put it like that. 10:11:26 <Diziet> vorlon: I can't say I'm surprised. 10:11:34 <rra> It sounded like Patrick Ouellette was basically okay with that, although there was a lot of conflict in that mail thread, so I'm not certain. 10:11:36 <vorlon> so we don't have a solution that both satisfies policy and avoids breaking upstream expectations / documentation 10:11:44 <rra> Basically okay with the ax25 renaming, that is. 10:12:06 <Diziet> So the question is: do we need to discuss any further ? 10:12:10 <Diziet> Do we need any more information ? 10:12:22 <bdale> hi 10:12:25 * bdale is at a car dealership with his wife, multitasking 10:12:26 <Diziet> There is a concrete option, as I describe above, which I could write up as a proposal. 10:12:30 <Diziet> Hi. 10:12:30 <bdale> as a long time ham radio guy and former user of the ax25 code, it seems to me that changing the ham flavor makes sense, though I agree with Diziet's concern about letting folks just show up and grab name space 10:12:36 <rra> Realistically, I think that Node.js should at least have an option to be /usr/bin/node via some mechanism other than manual intervention by the local sysadmin, not because I want to reward upstream behavior here, but because I think that's best for our users. 10:13:00 <rra> I'm happy for that option to not be the default. 10:13:01 <Diziet> rra: A low-priority debconf question ? 10:13:07 <rra> But I think it's going to be surprising if it's not available. 10:13:12 <dondelelcaro> yeah 10:13:23 <Diziet> We should set the maximum priority. 10:13:55 <rra> Yeah, debconf would be okay. From a user perspective, I'm not sure low makes sense. The goal is to keep people from being confused, and having the question be suppressed in most installations isn't really helpful there. 10:13:58 <Diziet> `best for our users'> I hate this phrase. It's tendentious. Because the moral hazard is bad for all our users in the future. 10:14:10 <rra> Good point. 10:14:33 <Diziet> Also we should be using our weight to help stop upstreams doing crap like this. 10:14:38 <dondelelcaro> wasn't the option proposed that nodejs would get /usr/bin/node IFF node wasn't installed, that both should use a different name for the binary, and that node should use /usr/bin/node IFF nodejs wasn't installed, and if both were installed, they should have a coordinating debconf question or something? 10:14:40 <rra> What I'm trying to say is that people who just want to use Debian to get something done are going to be surprised by Node.js being available but not called what it's called elsewhere, and I'm not sure that we gain anything by not providing that. 10:14:51 <Diziet> See also how the KDE licence fiasco was `bad for our users' but big projects don't make that kind of mistake nowadays. 10:14:52 <bdale> Diziet: right, but I suspect we're already to the point where node.js users outnumber users of the ax25 code, and probably trending hard in that direction 10:14:54 <vorlon> so regardless of other mitigation, if we decide nodejs will be /usr/bin/nodejs and not /usr/bin/node by default, I think someone on the TC should communicate this to the upstream mailing list 10:15:17 <rra> Debian refusing to call Node.js node is more likely to just cause upstream to call us bad names or ignore our other concerns than it is to actually change anyone's behavior, IMO. 10:15:34 <Diziet> rra: If they call us bad names in public so much the better. 10:15:37 <vorlon> upstream has already staunchly ignored our concerns 10:15:47 <vorlon> so I'm not sure there's much to be lost there 10:15:58 <vorlon> (and not just our concerns, but other distributions' as well) 10:16:02 <Diziet> It's the _next upstream_ who is thinking of doing the same thing. 10:16:04 <bdale> rra: sadly, you're probably right. it's one of the reasons that I really hate it when we fail to address name space conflicts quickly when they first show up. 10:16:09 <Diziet> And it's not `everywhere else' since AIUI Fedora have decided to rename too. 10:16:23 <rra> Diziet: I think those are unofficial Fedora packages, not actually Fedora proper. 10:16:34 <rra> They ironically even seemed to be from Node.js upstream. 10:16:40 <vorlon> bdale: my understanding is that efforts were made to address this upstream, to no avail 10:16:47 <Diziet> rra: Lots of stuff in the rpmish universe is unofficial packages; that's just how they do things there. 10:16:59 <bdale> I think requiring that both have something other than 'node' as a primary name makes sense .. having it be easy for the node.js variant to also be /usr/bin/node seems to meet both concerns? 10:17:02 <rra> Right, I'm just saying that I don't think we can accurately say that "Fedora" decided to do something. 10:17:12 <rra> bdale: That's where I'm at, yes. 10:17:40 <Diziet> That is, I accept that there will this pain for node.js users. But I hope that if this turns into a big deal and lots of complaints from upstream, that it might help next time an upstream is being <censored> 10:18:12 <bdale> Diziet: I wish that were true, I have little faith that it will work out usefully that way 10:18:25 <vorlon> if we're going to make it easy to be /usr/bin/node, what is the argument for not making it the default? 10:18:38 <Diziet> `Act as if the guiding principle etc. etc. universal law etc. etc.' 10:18:42 <bdale> the ax25 version is in /usr/sbin, right? 10:18:47 <vorlon> yes 10:18:57 <rra> Carsten had a pretty extensive analysis of the possible options here. Let me go dig that up again. 10:19:00 <bdale> so there's no actual conflict, just potential confusion? 10:19:05 <Diziet> vorlon: We want to encourage the world to make software which works with #!/usr/bin/nodejs 10:19:09 <rra> bdale: There's a conflict with unqualified binaries. 10:19:19 <rra> If you run "node" and have /usr/sbin first in your path, you're probably unhappy. 10:19:29 <rra> And what you get changes randomly based on your PATH. 10:19:36 <vorlon> Diziet: and we'll do that even if upstream doesn't provide that path? 10:19:44 <vorlon> do we expect this to be successful? :) 10:19:49 <Diziet> vorlon: Yes. It might well be. 10:19:53 <bdale> sorry, as I said I'm in a weird physical space atm and multitasking 10:19:54 <bdale> rra: sure .. I get that .. I always have sbin dirs in my path 10:20:01 <dondelelcaro> vorlon: (issues with the "fedora supplied node") 10:20:23 <dondelelcaro> so it looks at least like people are writing stuff use nodejs instead of node on fedora 10:20:35 <Diziet> vorlon: Because upstream don't control distros and distros will see the same issues as we do. 10:21:04 -!- jcristau [~jcristau@irc.cristau.org] has joined #debian-ctte 10:21:08 * vorlon nods 10:21:18 <dondelelcaro> from my perspective, it seems clear that nodejs needs to provide /usr/bin/nodejs; the only question then is what to do with /usr/bin/node 10:21:21 <Diziet> It wouldn't be the first time distros had decided to do something which an upstream didn't like. 10:21:29 <rra> I think Carsten's message was only in debian-devel. 10:21:37 <rra> dondelelcaro: Agreed. 10:21:43 <Diziet> dondelelcaro: Yes. 10:21:58 <Diziet> I would like it not to be provided by default. 10:22:03 <vorlon> anyone have a pointer to the message that describes what we think we want to endorse? 10:22:43 <Diziet> <mXe7vGcXEYO.A.hdB.dKZpPB@bendel> 10:22:52 <Diziet> Sent to debian-ctte. 10:22:58 <Diziet> Is relevant but not the definitive proposal. 10:23:02 <Diziet> We don't need to dig that out though. 10:23:07 <vorlon> <20120506172918.GC32011@virgil.dodds.net> was my position, fwiw 10:23:10 <Diziet> Not in this meeting anyway. 10:23:12 <rra> Carsten had a concrete proposal but it only went to debian-devel. I'm trying to find it. 10:23:34 <bdale> Diziet: when you say not be default, what's your feeling on a debconf question to add the link? 10:24:24 <Diziet> I want it not to be the default to add the link, and the question should be of low enough priority that most installs don't see it (since node.js might well turn out to be a dependency for things and those things' users don't want to be asked lots of questions). 10:24:29 <vorlon> is a debconf question better than a compat package? (I think it's worse) 10:24:34 <rra> I think there are two options for the link: a debconf package, and a separate package. Fedora did a compat package. 10:24:40 <rra> I think a compat package may make somewhat more sense. 10:24:41 <Diziet> I don't mind whether it's a package or a question. 10:25:02 <rra> I'm not sure where Carsten's message went now, since I can't find it in debian-devel either. 10:25:03 <vorlon> we could stipulate that no packages in Debian are allowed to depend on the compat package or reference /usr/bin/node 10:25:11 <Diziet> If it's a package then nodejs shouldn't even Suggest it. 10:25:15 <bdale> ok, I agree that /usr/bin/nodejs should be the name provided by the package. I'm personally ok if there's no automatic provision of /usr/bin/node at all. 10:25:15 <rra> Yeah, and that's an easy thing for Lintian to check for. 10:25:23 <Diziet> vorlon: Yes. 10:25:47 <bdale> yes, a lintian rule that flags /usr/bin/node as probably wrong sounds like a great idea 10:25:57 <rra> I concur on the concern about asking Debconf questions when the package is pulled in via a dependency. 10:25:59 <Diziet> bdale: I would also be happy with no automatic provision but I get the impression that that's a minority view. 10:26:04 <vorlon> rra: yeah, I didn't remember/find a complete proposal from Carsten; I only saw 10:26:17 <rra> vorlon: I think he may have only sent it to me. 10:26:21 <vorlon> ok 10:26:22 <Diziet> lintian> /usr/dict/words ? :-) 10:27:08 <bdale> Diziet: I'm not sure we need to be prescriptive about how /usr/bin/node might be linked. if we declare that the canonical name in the package should be /usr/bin/nodejs, isn't the rest simply a matter of choosing whatever approach users/admins/package maintainers want that's within policy? 10:27:21 <Diziet> I don't really see why the ax25 compat symlink needs a whole package. It could just be left as cruft during upgrade. 10:27:21 <vorlon> it might be useful to write up the current proposal on a whiteboard of some kind - shall I throw together a wiki page? 10:27:35 <rra> Part of the complexity here is to figure out how to handle the compatibility symlink for ax25's node during upgrades with a compat package in cases where you might install and remove the compat package. Other edge cases like that. It's probably not worth talking about here as opposed to just asking someone to write something up in mail. 10:27:49 <Diziet> rra: Right. 10:28:11 <Diziet> rra: I think the rules re ax25 are: Old installations should get the symlink. New installations should not. 10:28:16 <dondelelcaro> 10:28:20 <dondelelcaro> vorlon: ^^ 10:28:44 <rra> Diziet: I think one of the concerns was that installing and then removing the nodejs compat package would blow away the symlink for the ax25 node package, and a question is whether we're okay with that. 10:29:01 <Diziet> rra: I think I'm unhappy with it. 10:29:12 <bdale> why would it do that, if the path to the two links would be different? 10:29:13 <Diziet> That's an argument for compat packages for both or neither. 10:29:21 <rra> bdale: Oh, right, good point. 10:29:32 <Diziet> But it might break your system while you had nodejs-node installed ? 10:29:45 <Diziet> (and stop you fixing it for aforementioned connectivity reasons) 10:29:46 <bdale> I'm back to the 'there's no real conflict, just potential confusion' thing 10:30:53 <vorlon> So it sounds like we're moving in the direction of <87aa1nnl0b.fsf@poker.hands.com> 10:31:03 <bdale> to break a system, it requires an unqualified use of 'node' and a path that puts the wrong one first, right? 10:31:05 <bdale> that feels low probability to me, but I agree that if we can get it right so that it doesn't happen that's a good plan 10:31:48 <Diziet> So if we want either both or neither to have compat packages our options are (a) compat packages for both (b) manual symlink for both. 10:31:54 <bdale> is there an easy way to dereference a message-id online? I don't have that msg on my notebook. 10:32:02 <rra> bdale: Yeah, that's correct. And one concern from the ham community was that apparently the existing node isn't only run from inetd or the equivalent, but may also be run from complex local scripts. 10:32:02 <jcristau> lists.debian.org/$m-id 10:32:08 <dondelelcaro> bdale: 10:32:16 <bdale> dondelelcaro: thanks 10:32:27 <bdale> jcristau: thanks, I didn't know that 10:32:34 <Diziet> Since both sides have to do the same thing and they're arguing I think we need to choose between compat packages or manual symlinks. 10:32:34 <jcristau> (or mid.gmane.org/$m-id) 10:32:43 <rra> vorlon: Yes, that's the basic proposal that I remember, and that seems reasonable to me on first glance. I think Carsten had some improvements for edge cases. 10:32:56 <vorlon> ok, has a concrete layout for the compat packages 10:32:57 <Diziet> I would prefer manual symlinks (with perhaps a debconf question on the nodejs side). 10:33:06 <vorlon> do those look sensible? 10:33:18 <bdale> looking 10:33:19 <rra> I don't want to force the ax25 folks to create a manual symlink; we should transparently handle their upgrade. 10:33:41 <Diziet> rra: OK. And doing that transparency with a diversion in the preinst is hideous. OK. 10:33:47 <Diziet> So we're into compat packages. 10:34:12 <rra> I think supporting upgrades from the existing node package is very important. That's a committment that we try to make as a project: we don't break people's stuff on upgrades unless we have no other options. 10:34:20 <Diziet> rra: I agree. 10:35:03 <rra> Yup, the proposal on the whiteboard looks good to me. 10:35:16 <Diziet> We also need to specify that the priority of nodejs-legacy is extra. 10:35:50 <Diziet> And it's not in tasks etc. 10:35:50 <rra> Yup. 10:35:54 <vorlon> ok 10:35:55 <bdale> and having node conflict on nodejs-legacy is to prevent the unqualified name confusion? 10:35:59 <vorlon> bdale: yes 10:36:04 <bdale> ok 10:36:18 <bdale> I'm good with what's on the wb 10:36:18 <vorlon> since it's still a namespace collision on the path, even if not on the filesystem 10:36:27 <bdale> vorlon: agreed 10:36:29 <vorlon> any objections / further refinements to what's there now? 10:36:44 <bdale> just making sure I'm actually awake 10:36:51 <vorlon> if not, I'm happy to take the action to write it up for a vote 10:36:58 <rra> Works for me. 10:37:00 <Diziet> Looks good to me. 10:37:01 <Diziet> Thanks. 10:37:05 <dondelelcaro> sounds good to me too; thanks 10:37:07 <rra> We can hammer out further edge cases over email. 10:37:14 <rra> If any come up. 10:37:18 <vorlon> [ACTION] vorlon to write up a resolution for bug #614907 based on 10:37:38 <rra> Okay, we have a little more than 20 minutes left; if we're going to talk about Python, we should probably do that now. 10:37] 10:37:40 <bdale> vorlon: please make it a simple vote between this resolution and further discussion 10:37:44 <vorlon> bdale: ack 10:38:27 <bdale> rra: ok .. where do we stand? 10:38:32 <Diziet> Can I briefly mention parallel now ? 10:38:39 <Diziet> I think it's shorter than the other two. 10:38:50 <bdale> Diziet: ok 10:38:55 <Diziet> Based on the emails I'm seeing I think there's still some conflict going on. 10:39:04 -!- Mithrandir [~tfheen@vuizook.err.no] has joined #debian-ctte 10:39:08 <Diziet> At least some people are unhappy with what each other are doing. 10:39:09 <rra> Diziet: Sure, go for it; we took it off the agenda since you'd closed it, but it sounds like it's not entirely at rest? 10:39:10 <Diziet> Hi. 10:39:23 <Diziet> rra: Unfortunately not. 10:39:25 <rra> The --tollef flag thing annoys me. 10:39:30 <Diziet> Mmm. 10:39:40 <rra> Admittedly, I'm not Tollef, so it's really up to him whether to be annoyed, but. 10:39:46 <Diziet> It's not entirely clear to me what to do about all this but I think a starting point would be for us to offer to mediate. 10:39:59 <rra> Naming things after people is almost always a horrible idea. 10:40:06 <Diziet> sgt-puzzles 10:40:07 <Mithrandir> I'm not sure if I'm amused or annoyed, and it should really be --Tollef if it's referring to me. 10:40:13 <Mithrandir> but yeah, not a good name 10:40:32 <Diziet> But we can't do mediation without a private list since mediation means the sides talk to us and we translate/interpret/negotiate/etc. 10:41:02 <rra> Well, is the mediation necessarily a tech-ctte thing, or is there just a need for mediation in general? 10:41:15 <Diziet> So I guess what I'm saying is 1. can we please make a private list (or perhaps make our existing private list work) and 2. actually invite everyone to use it for mediation. 10:41:21 <rra> It's not really clear to me whether we currently have "jurisdiction" here. 10:41:25 <vorlon> is there still an existing private list? 10:41:32 <vorlon> cf. my recent private mails to everyone by name 10:41:40 <Diziet> rra: The advantage of having the TC do the mediation is that then if it comes down to `people can't agree', the TC have all the information to make a decision. 10:41:42 <rra> But regardless, I'm personally convinced of the need for a private list given the number of interpersonal conflicts we're asked to handle. 10:41:46 <Diziet> Otherwise you have to go through the argument _again_ 10:41:54 <rra> Point. 10:42:11 <vorlon> private list - +1 10:42:14 <Diziet> OK. 10:42:20 <Diziet> I will try to get that sorted out. 10:42:27 <vorlon> do we think we have the authority to set up that list on our own say-so? 10:42:36 <Diziet> Yes. 10:42:40 <vorlon> there was a question raised at last UDS about whether the constitution required us to have discussions in public 10:42:41 <dondelelcaro> vorlon: I don't believe any other listmasters will disagree 10:42:43 <rra> We arguably have a constitutional issue. 10:42:56 <Diziet> rra: I think we should regularise it, yes, but afterwards. 10:43:01 <vorlon> ack 10:43:13 <bdale> I'm not up to speed on this, and it's not clear that trying to get up to speed right this instant is the best use of our collective time. is there a proposal here, or just a sense that maybe we should interject ourselves? 10:43:18 <Diziet> I admit that's playing a bit fast and loose but _in practice_ we've been having lots of people emailing us as individuals anyway. 10:43:38 <Diziet> bdale: It's not clear what we may need to do but people are quite cross in my email and trying to persuade me of their point of view. 10:43:46 <Diziet> It's not clear exactly what they want me to do ... 10:43:51 <Diziet> And why they're sending to just me. 10:43:57 <vorlon> bdale: the bug was closed, the moreutils maintainer raised an additional objection following Diziet's bug closure 10:44:16 <vorlon> ah, and apparently there's further private follow-up that I'm not privvy to ;) 10:44:18 <zack> if I may, the constitution explicitly mentions that the tech-ctte is allowed to use private list for discussing membership appointment; so at least a reasonable doubt that it is not allowed to to so for other matters exists 10:44:48 <Diziet> How about after we set up a private list that works someone (not me since I probably look like I've taken sides) emails everyone involved with this to please contact us with their concerns (in public or private as they choose) and we will try to help. 10:45:01 <bdale> I'm ok with a private list in principle, in practice it hasn't worked well in the past 10:45:05 <rra> Yeah, but 6.3.3 is pretty explicit. We have a set of amendments to the constitution that we want to talk about anyway; we should probably do something about 6.3.3 as part of that. 10:45:06 <Diziet> vorlon: There have been emails to what looks like a random CC list. 10:45:10 <vorlon> heh 10:45:14 <Diziet> rra: Indeed. 10:45:41 <Diziet> vorlon: I don't really feel very comfortable about that obv. - it's definitely worse than the TC officially talking about things with people in private. 10:45:50 <Diziet> If we need to make any decisions they will be made in public. 10:46:07 <rra> I think mediating privately is fine. 10:46:10 <bdale> ugh .. lag 10:46:21 <rra> Mediating isn't really discussing decisions. I think we have enough wiggle room there. 10:46:29 <Diziet> Would anyone care to volunteer to send the invitation to mediation then ? 10:46:30 <rra> If the mediation breaks down, we need to take the discussion public. 10:46:45 <Diziet> rra: Right. 10:46:50 * rra ENOTIME at present, unfortunately. :/ 10:47:00 <zack> sorry (again), but have you actually been asked to mediate in the --tollef issue? it looks like the main issue there is technical: --tollef is not compatible with moreutils behavior, so the implemented "solution" is broken 10:47:19 <Diziet> zack: We haven't been asked to mediate. 10:47:27 <Diziet> What we have is some angry emails. 10:47:31 <vorlon> [ACTION] Diziet to sort out a private mailing list for the TC via lists.debian.org 10:47:40 <Diziet> In response to us maybe making a decison or maybe in response to something the parallel maintainer or upstream did. 10:47:54 <vorlon> Diziet: who are the parties to the dispute? moreutils and parallel maintainers? 10:48:00 <vorlon> or are you getting angry mails from others? 10:48:03 <Diziet> vorlon: I'm not sure exactly who everyone is. 10:48:15 <bdale> ok, so this turns out to seem anything but simple/quick .. if the action we can take today is delegate getting a private list set up, so be it. 10:48:29 <Diziet> Eg who is Ian Zimmerman. 10:48:40 <Diziet> Ole Tange is upstream ? 10:48:43 * rra hates to cut this short, but I really do want to get to Python. 10:48:46 <Diziet> For GNU parallel. 10:48:50 <bdale> rra: me too 10:49:11 <vorlon> so I didn't see anyone volunteering to invite mediation for parallel 10:49:14 <dondelelcaro> yeah... can we agree to come back to this via e-mail in a future meeting? 10:49:21 <Diziet> OK. 10:49:26 <dondelelcaro> s/in a/& or/ 10:49:39 <Diziet> Let's do Python then. 10:49:55 <rra> Okay, where I think we currently are: 10:49:58 <Diziet> I confess I haven't been following the latest ins and outs. 10:50:05 <vorlon> did everyone receive and have a chance to read the last private mail I sent on the subject? 10:50:29 <dondelelcaro> yes 10:50:37 <rra> The packaging helpers seem to have largely been resolved to everyone's satisfaction. Apart from some worries that there might be future conflicts, no one seems to feel like the packaging helper side of things currently has problems, and there's a maintenance team for those packages. 10:50:38 <Diziet> Date: Sat, 28 Apr 2012 18:51:53 -0700 10:50:39 <Diziet> ? 10:50:42 <rra> So they seem to be off the table. 10:50:52 <vorlon> Diziet: no, May - let me grab the message-id 10:50:58 <rra> What's left here is the Python interpretor itself. 10:51:08 <vorlon> Diziet: <20120518052629.GA25212@virgil.dodds.net> 10:51:15 <vorlon> Date: Thu, 17 May 2012 22:26:29 -0700 10:51:26 <Diziet> I don't have that at all. 10:51:29 <rra> zack polled debian-python to see who was actually interested in volunteering to help maintain Python. I found the results highly surprising. 10:51:34 <vorlon> Diziet: email address I should try re-sending to? 10:51:43 <vorlon> (previously sent to ian@davenant.greenend.org.uk) 10:51:47 <Diziet> ijackson@chiark.greenend.org.uk 10:51:50 <Diziet> Oh. 10:52:06 <Diziet> That's an out of date address for me. I really need to fix the last few packages with that in their Maintainer... 10:52:24 <Diziet> got it ta 10:52:29 <vorlon> ah, heh. I copy-pasted that one, apparently several of these private mails have been misaddressed 10:52:45 <bdale> vorlon: yes, I've read your private msg .. no real surprises 10:53:06 <rra> The results from the polling of debian-python appear to be: morph is still very much interested in putting together a maintenance team, but it's not clear that the other people volunteering to help wanted to be part of that team (although Barry seems generally open to help anyone). Jakub Wilk is willing to maintain the packages by himself but doesn't seem very interested in forming a team. 10:53:16 <rra> Not a lot of people responded to volunteer. 10:54:00 <bdale> so the question at this point is what? whether we force a change in maint of the interpreter package, and if so who the team is? 10:54:04 <rra> Yes. 10:54:44 <rra> There were also multiple responses in debian-python saying that people were opposed to forcibly replacing Matthias, expressed with varying degrees of strength. 10:54:51 <Diziet> It doesn't sound like we have a team we would be happy replacing Matthias with, even if we take a very downbeat view of Matthias. 10:54:53 <vorlon> rra: right; and there's the point from ScottK that having a maintenance team for the metapackages that's at odds with the team for the interpreter packages is not a healthy outcome 10:55:05 <bdale> I find this difficult while doko remains both usefully active and unwilling to participate in public discussion of the bug filed with the TC 10:55:07 <rra> Diziet: That's my opinion as well. 10:55:14 <rra> bdale: Yes. 10:55:33 <rra> I think it's unarguable that there's a real communication problem here. Not enough is said publicly about what's going on with Python maintenance. 10:56:04 <vorlon> I certainly find it difficult, but I also think there's only one right decision for the technical maintenance of python 10:56:12 <rra> This is something that in general doko struggles with (the gcc 4.7 timing also wasn't very smooth). Also, doko is wearing a lot of hats at the moment without a lot of team backup. Both of those things concern me a lot. 10:56:14 <Diziet> The only thing we could do would orphan it but we'd have to declare that the people who have been making Matthias's life miserable shouldn't get it either. 10:56:15 <vorlon> i.e. from the set of options we have available to us 10:56:28 <rra> However. The alternative options we have here are not clearly better. 10:56:58 <bdale> I talked to him at UDS .. vorlon's private message has content substantially similar to my discussion with him 10:57:04 <bdale> I agree 10:57:12 <rra> And when Barry, Jakub, and Scott all explicitly say that replacing Matthias is a bad idea, that really gives me pause. 10:57:30 <vorlon> Diziet: orphan> right - and given that we've already surveyed debian-python for likely adopters, I don't see the value in that 10:57:31 <Diziet> How about this: we'll make a formal decision that doko keeps it BUT say that this is despite the lack of public communication and is primarily due to the lack of an alternative team with which we'd be happy. 10:58:03 <vorlon> Diziet: that's not quite the rationale I would give 10:58:12 <vorlon> I'm happy to wordsmith something that reflects all of our views 10:58:37 <vorlon> (I think your wording implies we would prefer to have an alternative team that doko is not part of... which is not my position) 10:58:39 <rra> I would really like Matthias to add a comaintainer, particularly someone who's willing to do a bunch of communicating and coordination, since that's Matthias's weak point IMO. 10:58:44 <Diziet> vorlon: Please do. I think it's important to make it clear that if things change we may change our mind. 10:58:55 <Diziet> rra: That would be a good thing to put in our resolution. 10:59:12 <vorlon> rra: do you think this is still an issue, given that there are comaintainers to the python-defaults and python3-defaults packages? 10:59:25 <rra> Yes, because of the communication issues. 10:59:26 <vorlon> doko makes it clear he thinks this is a non-issue now in practice 10:59:27 <jcristau> rra: how would that person communicate with doko? 10:59:31 <Diziet> vorlon: I think he either needs to start communicating publicly, or have a co-maintainer who does. 10:59:32 <zack> a summary of the outcome of my poll is at in case you want to review the options, fwiw one of them did include a co-maintainer (not saying it should be preferred or anything of course, just a data point) 10:59:59 <vorlon> Diziet, rra: why and how do the comaintainers of the python-defaults packages not already fulfill that function? 10:59:59 <rra> I don't think there's a need for a *technical* comaintainer to do the packaging, particularly, but the communication issues are ongoing. Someone needs to coordinate when new versions are added and dropped and make sure everyone is on the same page and that is currently not happening as well as it should. 11:00:30 <rra> If the python-defaults comaintainers feel like they have enough influence and say over what happens with versions of the interpretors to fill that function, that's sufficient, I think. 11:00:50 <vorlon> the defaults packages decide which are the supported and default versions of python in the archive 11:00:58 <bdale> rra: yes 11:00:58 <bdale> a co-maintainer who communicates would be a great addition 11:00:58 <bdale> sorry, I'm clearly facing variable lag 11:00:59 <rra> jcristau: That's the key. *Someone* has to both know what's going on and be able to communicate it and to be able to coordinate (including changing the timing if needed). 11:01:07 <rra> I don't really care how that's done. 11:01:12 <vorlon> the only part doko can actually block as a solo interpreter maintainer is the initial upload of a new version to unstable 11:01:16 <rra> Whether it's done by convincing Matthias or taking independent action. 11:01:37 <rra> vorlon: Or stop supporting older versions, but I guess anyone could do that anyway, and that isn't really the issue. 11:01:41 <vorlon> and while this *was* the point of contention in the not-so-distant past, it was also before the python-defaults packages had comaintainers 11:02:14 <vorlon> rra: right, well, the maintainer could request the ftpmasters to remove the package without coordinating with python-defaults first, but I don't think that's actually a realistic scenario 11:03:07 <rra> zack: The comaintainer option is Matthias and Barry. Given that Matthias could already just name Barry as a comaintainer, I'm a bit dubious about that as an option. It feels like either it is already possible without the TC doing anything or it wouldn't work. But maybe it's more nuanced than that. 11:03:16 <bdale> vorlon: good points, all 11:03:21 <bdale> vorlon: I think it would make sense for our resolution to encourage but not require that doko take on a co-maintainer for the interpreter package(s), otherwise I think you writing up a proposed resolution draft that we can review and/or vote on in email is fine 11:03:52 <rra> You're right; the python-defaults change does take a lot of the pressure off the primary concern, which was the communication around transitions. And the other primary concern as I recall was the Python packaging standards and helpers, and that seems to have been more or less resolved. 11:04:14 <dondelelcaro> sounds good 11:04:17 <vorlon> given that this issue remains contentious in the wider community, I think we do want a full array of ballot options here... I'm certainly happy to help wordsmith the "primary" ballot option 11:04:48 <vorlon> rra: I feel I should note here that the one major hold-out from consensus regarding the deprecation of python-support is morph 11:04:57 <bdale> vorlon: ok .. I'd like a shorter rather than longer list of options, but if you're willing to write up a longer list so that we explicitly vote the other options down, that's ok with me 11:05:05 -!- OdyX [~OdyX@cl-229.gva-01.ch.sixxs.net] has joined #debian-ctte 11:05:09 <Diziet> Is there anyone on the TC who would support any other ballot option other than the kind of thing we're discussing (which is basically `doko keeps the package; we have some requests/advice/opinions') ? 11:05:10 <rra> Yes, I think we should explicitly list the option that we had presented to us originally. 11:05:28 <bdale> rra: good point 11:05:31 <rra> Even if no one on the committee is supporting it, it just feels weird to me to not even list it. 11:05:33 <Diziet> rra: OK. Yes. That would be fine on the ballot even if no-one supports it. 11:05:40 <vorlon> ok 11:05:44 <morph_laptop> vorlon: (since you named me) also jwilk, to be fair 11:06:05 <vorlon> morph_laptop: ah, indeed? sorry, I was unaware 11:06:09 <morph_laptop> np 11:06:16 <vorlon> let's just say I've seen you being more vocal about it ;) 11:06:22 <rra> morph: A question there, then: *is* the packaging helpers situation resolved to your satisfaction? I had the impression that everyone was more or less happy, but if that's not the case, then that's new information. 11:06:27 -!-:06:27 -!- Topic set by dondelelcaro [~don@hemlock.ucr.edu] [Thu May 31 10:37:39 2012] 11:06:37 <rra> I unfortunately haven't been following debian-python, which would have been helpful. 11:06:49 <rra> I read some selected threads and then trusted what people said in those threads, which isn't a great research method. 11:07:23 <vorlon> are the other TC members pressed for time? 11:07:29 <dondelelcaro> I'm ok 11:07:30 <vorlon> I can hang around to continue discussing 11:07:33 <bdale> I'm not pressed for time 11:07:35 <rra> My 11am was cancelled, so I can stay. 11:07:37 <dondelelcaro> ok 11:07:39 <Diziet> I'm OK for time. 11:07:41 <morph_laptop> rra: well, the dh_python3 is good, but dh_python2 still has several bugs that needs to be fixed to be an-pair with my idea; one of the bigges nuiance is the need to rebuild to support a new python verison, but it will eb resolved removing 2.6 (since py3k support more versions in the same dir) 11:08:01 <vorlon> right 11:08:07 <Diziet> We have a bit of a backlog so this meeting being long won't set too much of a precedent I hope. 11:08:14 <dondelelcaro> yeah 11:08:19 <vorlon> python2 helpers each have different trade-offs to work around a different set of upstream bugs/misfeatures 11:08:25 * rra will generally want to keep it to an hour, but the first one is always special. 11:08:28 <zack> rra: on that front, now both the old helpers are deprecated; that is at least an indication that the helper issue is more or less solved, I can dig it up the relevant threads if you want 11:08:33 <dondelelcaro> I'd also like to schedule the next meeting before we get too far along [I probably should have done that first...] 11:08:46 <vorlon> the long-term solution is that python3 is supposed to make things better for distributions 11:09:02 <Diziet> vorlon: python2 is going to be around for years. 11:09:05 <vorlon> (and I believe it does - thanks in no small part to barry's upstream work) 11:09:07 <rra> morph_laptop: Okay. So what I'm hearing from that is that it's not completely resolved, but Python 3 fixes things, and the Python 2 issues are, if not great, livable. Is that accurate? 11:09:09 <bdale> fwiw, I put an item in penta for a tech ctte mtg at debconf for those who will be there 11:09:26 <morph_laptop> rra: sounds fine for me 11:09:30 <vorlon> Diziet: certainly... and so we're saddled with having to make tradeoffs for python2 11:09:33 <bdale> as a bof 11:09:46 <vorlon> now, the python-defaults team have made their decision about what they think the right tradeoff is 11:09:55 <vorlon> and some python module maintainers have rejected that in favor of another 11:10:24 <rra> vorlon: Is that a place where we need to do something, or is it going to sort itself out over time? 11:10:39 <vorlon> and unfortunately, the lack of making a consistent set of tradeoffs introduces yet another set of bugs that we wouldn't have if we'd all agreed on one or the other 11:11:00 <vorlon> rra: if it's going to sort itself out over time, it seems to be geological time 11:11:14 <rra> Okay. So it's causing some amount of bugginess ongoing. 11:11:16 <vorlon> i.e.: it solves itself when python2 goes away, which as Diziet says is long in the future 11:11:30 <Diziet> vorlon: I'm not sure where this conversation is going TBH. Are you trying to discover if there is still an underlying dispute about the helpers ? 11:11:34 <vorlon> (though as a data point, Ubuntu is pushing to support only python3 applications for 14.04) 11:11:49 <rra> Diziet: That's what I'm trying to determine. I'm trying to figure out what the remaining dispute is. 11:11:54 <vorlon> Diziet: I'm saying that there is an underlying dispute about the helpers, in response to rra's question 11:12:17 <rra> I know Python transitions were a huge problem. python-defaults maintainership seems to be a way to resolve that, although I'm not yet clear on whether everyone agrees it's resolved. 11:12:48 <jcristau> rra: that's kind of resolved by python upstream not releasing new versions 11:12:54 <rra> I know that the way Python add-ons were packaged was another large dispute, with two competing helper suites and a lot of upsetness on both sides about the decisions made by the others. I was hoping that was resolved; it sounds like it isn't entirely. 11:13:17 <rra> jcristau: Python 2.7 came out during this release cycle, didn't it? 11:13:23 <jcristau> yeah, i mean after 2.7 11:13:28 <vorlon> it's /formally/ resolved by the deprecation of both python-central and python-support by the respective authors, in favor of dh_python2 11:13:36 <bdale> ok, well, it sounds like we have enough info to write up a ballot and vote it? 11:13:38 <rra> Was the python2.7 transition handled okay, or was it another problem? 11:13:54 <rra> Actually, that's not really the question I have. 11:14:11 <rra> The real question I have is that I'm not sure of the timing of this: was the python-defaults comaintainership before or after python2.7? 11:14:37 <jcristau> before 11:14:44 <rra> The contention is that having python-defaults be comaintained addresses that part of the problem. I guess what I'm asking is have we actually tested that with a new release of Python? If so, how did it work? 11:15:25 <zack> if I may, it looks to me that the ctte has been asked to solve the _maintenance_ issue; while I agree that in the past the helper issue was intertwined with that, arguably nowadays that issue is "solved enough" to be separate 11:15:34 <vorlon> rra: from a quick google search: 11:15:44 <zack> so, hopefully, the ctte doesn't _need_ to rule anymore on the helper issue 11:15:49 <rra> bdale: So far, if I had to vote on something right now, I'd be confused about why the TC was even being asked to change things. Given that clearly the TC is still being asked, I want to understand why people are still upset. 11:16:05 <vorlon> zack: yes, I definitely agree that it's out of scope for us to decide on helpers 11:16:21 <rra> Okay. Then I'll stop worrying about the helpers. :) 11:16:27 <zack> \o/ :) 11:16:45 <jcristau> the 2.7 transition at least wasn't stalled for a year for unclear reasons. 11:16:50 <bdale> rra: my take all along has been that the core issue is doko's communication style, or lack thereof 11:17:12 <Diziet> Right. Does that mean we're ready now to draft a resolution on python ? vorlon, do you need anything else ? 11:17:36 <rra> bdale: Agreed. But if that communication style doesn't really affect the broader Python community in Debian any more due to doko not being involved as much in helpers, Python 3 removing some of the pressure, and python-defaults being maintained by other people, then it's not clear that we have to have an opinion on his communication style. 11:17:38 <bdale> right, 2.7 seemed from a distance to go more or less well 11:18:06 -!-:18:06 -!- Topic set by dondelelcaro [~don@hemlock.ucr.edu] [Thu May 31 10:37:39 2012] 11:19:04 <bdale> zack: by the way, so I don't forget later, thank you very much for all your effort on this in recent times 11:19:05 <Diziet> rra: More to the point we don't have any useful /options/ to do anything about his communication style. 11:19:10 <OdyX> 3.2.3 is still not in it's final version though. 11:19:18 <vorlon> Diziet: I gather that none of the above discussion has changed the consensus about what I should be writing, so I don't need anything else 11:19:25 <Diziet> vorlon: Good :-). 11:19:29 <Diziet> Are we done on this topic then ? 11:19:39 <zack> bdale: cheers, the potential bugfix ratio of this meeting is more than a reward for that :) 11:19:40 <dondelelcaro> ok; so as I understand it, vorlon will be writing up the primary option, with other options to be present 11:19:47 <bdale> rra: I agree. which is why I think we're to the point where we can write a ballot and vote on it at this point, as many of the points of contention even within the TC itself have been resolved in the time this has been on our plate 11:19:50 <rra> I mean, I know there are other things that annoy people, such as new versions of Python being uploaded to Ubuntu before Debian and whatnot, but it's just not clear to me that this rises to the level of requiring the TC to do something. 11:20:02 <vorlon> [ACTION] vorlon to write up a proposed ballot option for bug #636783 11:20:32 <Diziet> rra: It's not something we could do anything about other than by firing doko and if we don't have a team we would prefer to replace doko with then that's that. 11:20:44 <rra> Yeah. 11:20:56 <dondelelcaro> vorlon: it's #573745, but you'd figure that out. ;-) 11:21:01 -!-:21:01 -!- Topic set by dondelelcaro [~don@hemlock.ucr.edu] [Thu May 31 10:37:39 2012] 11:21:04 <vorlon> ah, heh 11:21:04 <rra> Certainly, I personally am not interested in replacing doko with any other single maintainer. 11:21:19 <Diziet> If we're done with Python, shall we do date of next meeting ? 11:21:21:47 <rra> Diziet: Sounds good to me. 11:21:53 <dondelelcaro> yeah; lets get that set in case people have to leave 11:21:56 <Diziet> I guess this time of the week works for most people ? 11:22:06 <Diziet> (We're not going to hear `no' from people who aren't here perhaps...) 11:22:13 <bdale> yes 11:22:14 <bdale> wow .. ping times exceeding 40 seconds from here now 11:22:16 <Diziet> But they can object in email. 11:22:20 <dondelelcaro> right 11:22:23 <vorlon> yeah, this slot is clear for me weekly 11:22:30 <Diziet> 1 month from now would be 28th of June. 11:22:34 <rra> I normally have a meeting that starts 22 minutes ago, but if we use this time and keep it to an hour, it works for me. 11:22:36 <Diziet> Is that too soon ? 11:22:44 <rra> No. 11:22:45 <vorlon> did aba ack/nack this time slot? 11:22:53 <dondelelcaro> vorlon: I think he ack'ed it 11:22:56 <vorlon> ok 11:22:56 <rra> I'd rather have a meeting and say we don't have much to discuss than not have enough meetings. 11:22:57 <dondelelcaro> I /msg'ed him 11:23:14 <rra> Once a month seems reasonable to me. 11:23:18 <vorlon> fine with me 11:23:28 * zack hugs you all for the enthusiasm in this meeting and in already scheduling next one 11:23:29 <dondelelcaro> ok; this slot on the 28th? 11:23:31 <bdale> monthly is good, an hour is good, this time works for me 11:23:32 <Diziet> OK, I will send an email saying: that's when it will be unless anyone objects. 11:23:44 <Diziet> [ACTION] Diziet to send notice of next meeting 11:23:46 <vorlon> fwiw there are a couple of things from recent Debian list discussions that I would like it if the TC could take up and drive to conclusion 11:23:57 <vorlon> but I'm going to avoid getting into those right now :) 11:24:08 <rra> There are a couple of things from recent Debian list discussions that I'd personally like to drive off a cliff. ;) 11:24:14 <vorlon> bdale: you mean you're not going to be on a car lot a month from now? :P 11:24:15 <Diziet> *snerk* 11:24:25 <Diziet> vorlon: Bring them up by email ? 11:24:42 <vorlon> potentially 11:24:53 <vorlon> but I might not get to it until next month regardless, as I seem to have taken a few action items :) 11:24:25:00 <Diziet> Heh. 11:25:21 <Diziet> The thing left is the constitution. Should we do that now or have we gone on long enough ? 11:25:29 <rra> So, the one item we have left is that we have a bunch of constitutional fiddling that we would like to do. 11:25:32 * rra is good to talk about it. 11:25:44 <dondelelcaro> I'm ok too; though aba was the one who proposed it 11:25:45 <bdale> vorlon: anything we need to talk about now, or is email good? 11:25:48 <rra> I think the supermajority fix is uncontroversial. 11:25:51 <vorlon> bdale: nah, nothing urgent 11:26:24 <Diziet> I still think we should try to do all of our proposed changes in parallel. So we need to decide roughly what they are. 11:26:32 <rra> I think we should allow private discussions with some pretty strict limits around that allowance. At the very least, all votes and rationales need to be public. 11:26:32 <Diziet> We have a clear proposal for supermajority. 11:27:01 <Diziet> 11:27:05 <rra> I kind of want to say that we should try to say something about allowing private discussion of personality conflict issues but not of technical issues, but I'm not sure how to phrase it. 11:27:05 <Diziet> rra: ^ how about that wording ? 11:27:16 <Diziet> rra: They merge into each other anyway,. 11:27:22 <rra> Yeah, I know. 11:27:36 <Diziet> I think it would be useful to be able to have a private conversation if two people are shouting at each other over whether something is a bug. 11:27:59 <rra> I'm not horribly happy with just removing discussion from the list of things we do in public without saying anything more. 11:28:05 <rra> I do think all discussion should be public by default. 11:28:34 <vorlon> I think that's probably a useful way to word it, and then spell out the cases when it's acceptable to go private? 11:28:44 <rra> I want to give us the freedom to take things private when discussing it in public isn't productive, but I don't want it to be the default. 11:29:59 <rra> vorlon: Yeah, that feels better to me. 11:30:34 <Diziet> vorlon: I don't want a list of specific permissions to go private which we'll have to argue about each time. 11:30:49 <Diziet> Whether to be public or private is a matter of judgement and I would like to have the freedom to exercise it. 11:30:59 <vorlon> certainly 11:31:23 <rra> Something like "Technical committee discussions are normally public. However, members may discuss issues privately provided that all draft resolutions, amendments, and votes are made public." 11:31:24 <vorlon> I think it should be possible to balance both concerns in the wording? 11:31:33 <dondelelcaro> though I suppose, even if we exercise judgement, we'll still argue about it... 11:31:37 <vorlon> heh 11:31:57 <Diziet> `normally' would be false if we decided to take on a routine mediation role (which is something we should imo try) 11:32:15 <rra> I dunno, I'm not very enthused about the tech-ctte becoming mediators. 11:32:24 <rra> That's for a couple of reasons. 11:32:40 <Diziet> How about `Discussions are held in public unless that would make it difficult to talk freely and productively' 11:32:43 <rra> One is that mediation takes a ton of time, and it's not like most of us have a surfeit of time already. I'm not sure we should commit to doing something even more. 11:32:53 <vorlon> 2) because too much mediation makes rra angry, and we wouldn't like him when he's angry 11:32:54 <Diziet> rra: OK fine we don't need to have that argument. 11:33:05 <Diziet> I want however the TC to have the _permission_ in the TC to become mediators if we want to. 11:33:10 <zack> I'm about to leave, but I've one last meta-topic: could you please post the irc logs somewhere (e.g. on the tech-ctte list) when you're done? The meeting was public anyhow and I would be useful to have it both for future ref and in the interim between now and the implementation of [ACTION]s 11:33:22 <zack> (yes, if the next time you use meetbot, that could be automated) 11:33:33 <Diziet> Does anyone have a log easily to hand ? If not I can c&p. 11:33:41 <rra> The other is that I think there's a bit of a conflict between being a mediator and being on the TC in that having a mediator who has considerable power to decide the results of whatever is being mediated sometimes doesn't go well. It can add an element of pressure and authority that isn't helpful. 11:33:42 <vorlon> who wants to take the action to follow up on meetbot with Darst? :) 11:33:52 <zack> I have the log and could post them, if you want me to 11:34:05 <zack> (I'll leave, but leave an irc proxy running) 11:34:05 <dondelelcaro> Diziet: yeah, I have the log too 11:34:09 <rra> Diziet: I'm not sure why we would need permission? 11:34:28 <bdale> vorlon: if my wife needs another new car a month from now, I have bigger problems than meeting timing... 11:34:30 <Diziet> rra: We need the rule about private discussion not to say that it's `abnormal' since for mediation it's not. 11:34:32 * zack waves and thanks all participants 11:34:39 <rra> I don't see anything in the constitution that says we can't mediate other than the public discussion part. If you just mean letting us have private discussions so that we can mediate... ah, okay, I see. Yeah, that's fine. 11:34:43 <rra> I get your point now. 11:35:03 <Diziet> What did you think about my phrasing re `freely and productively' ? 11:35:23 <rra> I'm worried it's going to provoke arguments over whether that criteria applies. :) 11:35:50 <Diziet> rra: Well if you want to avoid _all_ such arguments then we should say nothing in the constitution like my draft in says 11:35:53 <rra> Basically, I want to be clearer that the public/private decision is at the discretion of the TC, but the TC is formally encouraged to be public by default. 11:36:24 <rra> (And yeah, that's different than what I said about five minutes ago, but I realized that what I was saying earlier doesn't work.) 11:36:34 <Diziet> Right. 11:36:59 <Diziet> OK. We could have a non-normative statement `The TC is encouraged to hold discussions in public'. 11:37:05 <rra> So... hm. I guess I agree with your change but would add one more sentence like that. Yes. 11:37:11 <Diziet> Right. 11:37:19 <bdale> ok, I need to move .. thanks all for today, will be back online in a couple hours 11:37:25 <vorlon> thanks, bdale! 11:37:30 <Diziet> Thanks. 11:37:32 <rra> Thanks! 11:37:48 <dondelelcaro> thanks 11:37:51 <Diziet> Shall we close it there ? We aren't done with the constitution but we're leaking people (I think zack's input on that would be useful) 11:38:17 <Diziet> Just quickly one thing re that though: is it just me that thinks we should increase the max size ? If so I'll drop it. 11:38:23 <rra> Real quickly: for maximum size, meh... I think 8 people is already a lot, particularly when we try to schedule meetings. I wonder if we would gain the benefits there by being a little more aggressive (read: doing this at all) about asking people who haven't had much time whether they're really still active. 11:38:34 <dondelelcaro> yeah 11:39:06 <Diziet> I'm not getting a great deal of support here :-). OK we can drop that. 11:39:29 <Diziet> We need to have the discussion re an advisory GR about overruling too but I think that needs more time and people. 11:39:39 <rra> yeah, agreed. I was just about to say that too. 11:39:52 <Diziet> Then I guess we're into AOB ? 11:39:40:26 <Diziet> Noone has any AOB then. I guess we're done. 11:40:32 <vorlon> sounds good to me 11:40:38 <Diziet> I will c&p the log since no-one has said they have it in a disk file. 11:40:47 <rra> Agreed. And yeah, I wasn't smart and didn't log. 11:40:47 <dondelelcaro> Diziet: I've got it on a disk file if you want it 11:41:06 <Diziet> dondelelcaro: Oh good. Please email the whole thing to the TC list then. 11:41:27 <dondelelcaro> will do; it's actually the equivalent of C&P, but I'll start really logging 11:42:11 <rra> dondelelcaro: Thank you for coordinating! 11:43:02 <dondelelcaro> rra: np 11:43:14 <Diziet> dondelelcaro: Thanks, indeed. 11:43:18 <dondelelcaro> glad everyone was able to meet 11:43:24 <dondelelcaro> and that it was useful 11:43:49 <vorlon> yes, thanks dondelelcaro for organizing, and to everyone for making the time
= Draft solution = 1. nodejs is to provide /usr/bin/nodejs 1. ax25-node to provide /usr/sbin/ax25-node Based on <87aa1nnl0b.fsf@poker.hands.com>: Package: node Depends: ax25-node Conflicts: nodejs-legacy -- /usr/sbin/node -> /usr/sbin/ax25-node Package: ax25-node -- /usr/sbin/ax25-node Package: nodejs -- /usr/bin/nodejs Package: nodejs-legacy Priority: extra Depends: nodejs Conflicts: node -- /usr/bin/node -> /usr/bin/nodejs 1. No package may depend/recommend/suggest on nodejs-legacy, or reference /usr/bin/node. 1. The upgrade is asymmetric: users of the 'node' package get the compat symlink by default, users of the 'nodejs' package do not. This is by design. 1. The nodejs package should declare a Breaks: against any existing packages in the archive which reference /usr/bin/node. 1. The priority of nodejs-legacy is extra and it should not be part of any task or automatic installation set. | https://lists.debian.org/debian-ctte/2012/05/msg00072.html | CC-MAIN-2017-26 | refinedweb | 11,267 | 69.21 |
Today's lab looks at nested loops and indefinite loops from Chapter 8 and more on finding errors.
Today, we are going to write a simple game where the user tries to find our mystery point in the graphics window. Lets first go through the program section by section:
# Mystery point game for Lab 9 # Lehman College, CUNY, Fall 2012 from graphics import * from math import * from random import *
# Reuse the distance function we wrote for Lab 8: def dist(p1,p2): dist = sqrt((p1.getX()-p2.getX())**2 + (p1.getY() - p2.getY())**2) return dist
def main(): w = GraphWin("Target Practice",500,500) w.setCoords(-250,-250,250,250)
#Generate a mystery point (at a random location): x = randrange(-200,200) y = randrange(-200,200) print("x and y are:",x,y) mysteryPoint = Point(x,y)
#Text to tell the user what's happening: t = Text(Point(0,-210), "Click on the mystery point") t.setSize(16) t.draw(w)
#Get the point: p = w.getMouse() p.draw(w) d = dist(mysteryPoint, p) print("distance from mystery point is:", d)
#Keep going until they click close to the point: while d > 20: t.setText("Missed! Please click again!") p = w.getMouse() p.draw(w) d = dist(mysteryPoint, p) print("distance from mystery point is:", d)
t.setText("Congratulations! You found the mystery point!") #keep the window up until the user clicks w.getMouse() w.close() main()
Try running the program. How easy is it to win?
Could you find the point without peeking at the IDLE shell? To make the game a bit easier, we will add hints. The first hint will be to tell the user if they need to click more to the left (or right) to find the point. Here is the pseudocode:
if point clicked is to the left of mystery point give message "Too far left" else give message "Too far right"How can you tell if the point clicked is to the left of the mystery point? The x-coordinate tells how far left or right a point is, so, we compare the x-coordinates of the two points:
if p.getX() < mysteryPoint.getX(): t.setText("Click again! You were too far left") else: t.setText("Click again! You were too far right")
Now, add in the code that will give a hint to move up (or down) depending on where they clicked with respect to the mystery point. Your completed program should have a "left/right" hint and an "low/high" hint to make the game possible to do without looking at our diagonostics on the python shell.
Hint: Before the loop, set up another Text object, t2 to display the message about being too low or too high:
t2 = Text(Point(0,-230), "") t2.setSize(16) t2.draw(w)
In Lab 6, we looked at some common syntax errors and how to fix them. Most of those errors were missing punctuation (such at colons, quotes, or plus signs). Let's look at a few more errors that occur when using conditionals, loops, and functions:
# errors2.py-- modified from Zelle # recursions.py # A collection of simple recursive functions from Zelle, 2nd Edition # (Some also include looping counterparts). def fact(n) # returns factorial of n if n == 0: return 1 else return n * fact(n-1 def reverse(s): # returns reverse of string s if s == "": return s elif: return reverse(s[1:]) + s[0] def anagrams(s): # returns a list of all anagrams of string s if s == "": return [s] else: ans = [] for w in anagrams(s[1:]): for pos in range(len(w)+1): ans.append(w[:pos]+s[0]+w[pos:]) return ans def loopFib(n): # returns the nth Fibonacci number curr = 1 prev = 1 for i in range(n-2): curr, prev = curr+prev, curr return curr def main(): n = eval(input("Enter a number: ")) s = input("Enter a string: ") print(n+"!= ", fact(n), "or, loopFig(n)) print(s, "reversed is: ", reverse(s)) print("\n anagrams: ", anagrams(s)) main()
Load the program into IDLE and run the program. A dialog box pops up and says "invalid syntax":
We have seen this one before, it's a missing colon (":") at the end of the function definition. Add it in and run again.
Again, we get an invalid syntax. What's wrong here? (Hint: same as the last one). Fix the error, and let's run the program again:
This one is different. IDLE has highlighted the word def, and yet that seems to spelled correctly. A general rule to follow: if you do not see an error on the current line, look above (usually for missing quotes or closing parenthesis). On the previous line, the function call to fact() is missing the closing parenthesis. Add it, and run the program again:
This one is a bit harder-- all the keywords are spelled correctly and there's no missing colons, parenthesis, or quotes. What's wrong? Python expected the word else (elif is only used when you need multiple tests in multi-way decision). Replace elif with else and try again:
The message says: unexpected indent. The line does seem to be indented for no reason (i.e. it's not part of a block of code in a loop or decision construct). Remove the extra indent and continue:
This is a common error. In plain English, it means that the end of the line ("EOL") was reached before the string finished. In other words, the string is missing its ending quotes. Add it in (right after the word or) and run the program again.
It now compiles! But we need to test it to make sure no run-time errors remain:
When reading the traceback message (all the red text), go to the very last line and see what it says. The message says we cannot use + for 'int' and 'string'. We only used + once in the line to concatenate n to a string. Since we want n to eventually be a string and printed to the screen, let's change it to a string (by using the str() function):
print(str(n)+"!= ", fact(n), "or", loopFig(n))
Running it again, a new run-time errors appears:
The message says that IDLE cannot find loopFig(). Scanning through the file, it looks we misspelled it! The function is called loopFib(). Fix the misspelling in the main() and try again...
Success! The program accepted input, processed it, and outputted it to the screen. Try with a couple of different inputs to test how it works.
If you finish early, you may work on the programming problems. | https://stjohn.github.io/teaching/cmp/cmp230/f14/lab10.html | CC-MAIN-2022-27 | refinedweb | 1,104 | 80.21 |
Int the new features you’ll find in Scala Plugin 2017.3.
Highlighting of implicit usages
Most likely you are already familiar with this highlighting feature (it uses violet in the Default Theme), which usages of the symbol under the caret across the opened file. Starting with this release, it also highlights places where the target is used implicitly:
Build, Run, and Test processes do not depend on indexing anymore
IntelliJ IDEA performs indexing to power many of its features such as code highlighting, inspections, etc. In theory, indexing should not be required for processes like building or running tests. Nevertheless, previous versions had a number of dependencies that forced you to wait until the indexing finished. We have completely separated that logic, so you can run your existing run_configurations (application, tests …) in parallel with indexing. It’s very helpful in big projects where indexing takes considerable time.
Automatic suggestion to import SBT library
Now, if you add an import with unresolved packages that IntelliJ IDEA cannot find in your project’s External dependencies, the plugin suggests finding it in a local Ivy cache. If it finds the correct library, it adds the corresponding dependency to build.sbt (you can select the location).
Ammonite scripts support
The Scala plugin in 2017.3 also provides support for Ammonite scripts. We’ve added:
- Accurate highlighting and navigation that respects ammonite syntax;
- Run configuration with a gutter icon for launching scripts;
- Ammonite annotations;
- An action for importing
$ivy.dependencies. This may be required for proper resolution in the Editor.
As Ammonite is an external tool, there are some prerequisites for its usage:
- Ammonite must be installed in your OS.
- IntelliJ IDEA needs to knows where the Ammonite executable is located. You can:
- add a symlink to already accessible places like usr/bin;
- modify the $path variable;
- specify the path to the Ammonite executable in Default Ammonite Run Configuration, using the “Amm executable” field.
- Your project must have appropriate dependencies on Ammonite libraries. This is required for code processing in the Editor. If you use sbt in your project, you can add an sbt dependency. If your project is just a set of scripts, please get libraries from Maven repository and add them in the Project Structure settings. Usually, “ammonite_2.*.jar” and “ammonite-ops_2.*.jar” are enough, but for some specific operations you may need “…-repl”, “…-runtime”, “…-compiler” or another libraries.
- Finally, .sc files have to be treated as Ammonite files (by default IntelliJ IDEA treats them as Worksheets). You can define this in File | Settings | Languages & Frameworks | Scala | Worksheet.
A wizard for Lightbend Tech Hub templates
As you may already know, Lightbend Activator was EOL-ed on May 24, 2017. It was substituted with another technology: the “project starter” service. Following these changes, the Scala plugin replaces its New Activator Project Wizard with Lightbend Project Starter Wizard.
Additionally, the release brings lots of other improvements, such as better Shapeless and Play2 support in the Editor.
Your feedback is always very welcome. And please do report bugs / ideas you find to our issue tracker. Thanks!
Happy developing!
15 Responses to IntelliJ IDEA Scala Plugin 2017.3: Lightbend project starter, Ammonite support, Parallel indexing, and more
Tristan Lohman says:December 1, 2017
Can you elaborate on “better Shapeless” please?
mutcianm says:December 4, 2017
Support for `Generic`, `DefaultSymbolicLabelling` and `shapeless.ops.record.Selector` macro for now.
More macro implementations are coming soon.
Alex says:December 3, 2017
Thank you for Ammonite support!
Nikolay says:December 3, 2017
Ammonite support is cool, thanks!
Mikołak says:December 5, 2017
What are the plans on using the new compile server to provide correct compile error/warning feedback in the IDE? I see there is a tracking issue (SCL-11079, actually predating the current LSP-based implementation), but it hasn’t been updated in a while.
In the meantime, with the advent of sbt 1.1RC, there is now a prototype plugin for VCS (of all things) that does just that. When are you planning on IDEA to provide this kind of improved compile information flow?
Justin Kaeser says:December 5, 2017
This is planned for the 2018.1 release, approximately March 2018
Mikołak says:December 5, 2017
Awesome, thanks!
Maciek says:December 5, 2017
Ammonite support is great! It works really nice. But there seems to be no support (syntax highliting) for imported libraries. The code compiles and executes correctly, but the syntax errors are reported. Is there any workaround or planned fix?
kubukoz says:July 11, 2018
You probably didn’t mean syntax errors, as these would depend on invalid parsing (whereas this case looks like unknown symbol errors), but there’s a workaround – have a build.sbt file in the same project as the one you’re holding your scripts in, and add each dependency to that sbt file as well as the script. The IDE will know the symbols from the sbt file, the script will know the symbols from imports. Hope it helps 😉
David Pérez says:December 11, 2017
For me, the biggest feature is Ammonite support. Thanks.
Fruzenshtein says:December 27, 2017
Hey Scala Plugin team,
What I’m doing wrong?
Marcin says:January 23, 2018
Ammonite support is really super cool! Thanks!
Please just add shebang syntax support at the beginning of script:
—
#!/usr/bin/env amm
import ammonite.ops._
import ammonite.ops.ImplicitWd._
—
Currently Intellij highlights it in red, although it should not do it. It is correct syntax and Ammonite works with it. Because of this simple line you can start Ammonite scripts just like bash scripts:
./start.sc
Denys says:September 29, 2018
Can you please guys also add WSL support for ammonite ?
Bye bye Mongo, Hello Postgres | Digital blog | Info – Google Site Search says:December 23, 2018
[…] Although Ammonite allowed us to use a familiar language there were downsides. Whilst Intellij now supports Ammonite, at the time it did not, which meant we lost autocomplete and automatic imports. It was also not […]
Миграция с Mongo на Postgres: опыт газеты The Guardian – CHEPA website says:January 17, 2019
[…] нем мы обнаружили несколько недостатков. Сейчас Intellij поддерживает Ammonite, но во время нашей миграции он этого не делал — и […] | https://blog.jetbrains.com/scala/2017/11/28/intellij-idea-scala-plugin-2017-3-lightbend-project-starter-ammonite-support-parallel-indexing-and-more/ | CC-MAIN-2021-04 | refinedweb | 1,030 | 56.66 |
So as I transition from the world of C# to Ruby due to a change in employment (And that I have grown to hate C#), I’ve been spending time getting used to certain concepts I’ve used heavily in C# done in Ruby. One big one is the ability to pass anonymous methods into other methods. So something like this in C#:
public void LambdaHolder() { MethodThatUsesTheLambda(x => { Console.WriteLine(x +1)); } public void MethodThatUsesTheLambda(Action<int> passedInMethod) { foreach(var item in Enumerable.Range(0, 10) { passedInMethod(item); } }
When done in Ruby it looks like this:
def lambda_holder method_that_uses_the_lambda (lambda {|x| puts x +1}) end def method_that_uses_the_lambda (passed_in_method) (1...10).each &passed_in_method end
The main thing is the & character. This allows the each method to recognize passed_in_method as an expression it can call and pass an argument to. Essential the same as:
def method_that_uses_the_lambda (passed_in_method) (1...10).each {|x| passed_in_method.call(x)} end
Why would you want to do that? Readability if nothing else.
def method_that_uses_the_lambda (will_output_a_number) (1...10).each &will_output_a_number end
Compared to:
def method_that_uses_the_lambda (will_output_a_number) (1...10).each {|x| will_output_a_number.call(x)} end
Yeah… so there it is… I got nothin’ else… this is really awkward. | http://byatool.com/tag/functional-programming/ | CC-MAIN-2017-22 | refinedweb | 198 | 59.6 |
Your question does not describe at all what you are trying to do and what
problem you are trying to solve in doing so, so my only suggestion is:
Don't use a Web Browser control, but use an HTTP client like HttpClient or
HttpWebRequest and access their API.
There's even have a .NET library for that.
If you use System.Windows.Controls.WebBrowser control then this should
work, however it works on assumption that you only have one CODE tag:
var myTagValue = (wbBrowser.Document as mshtml.HTMLDocument)
.getElementsByTagName("CODE")
.OfType<mshtml.IHTMLElement>()
.First()
.innerText
You'll need to reference Internet Explorer's COM library: Microsoft HTML
Object Library. getElementsByTagName returns you list of all matching tags,
no matter where they are in HTML
I am not sure this will work or not.
But you can call JavaScript functions inside a page from C# using Web
Browser control
and in JavaScript you can set the cookie. To call JavaScript functions of
Web Browser controls see the link below.
webBrowser1.Document.InvokeScript(jsfunctionname, parameters);.
In order for any PHP script to work on a web browser, it must be enabled on
your server, which could be an actual server or your computer. If it isn't
configured properly, or at all, then you will always see the script you
wrote instead of it performing its task.
There are many tutorials online about how to setup a local server using
your computer provided you have the permissions set to do so.
Hope this helped, good luck!
(Sorry for not using comments for this, as its not really an answer but at
this point I don't have enough rep to post a comment...)
Oh what a nice question! I'm thinking of it right now. My approach is a
little difference:
With old MVC fashion, you consider the V(iew) layer is the rendered HTML
page with Javascript CSS and many other things, and M and C will run on the
server. And one day, I met Mr.AngularJS, I realized: Wow, some basic things
may change:
AngularJS considers the View ( or the thing I believed is view ) is not
actually view. AngularJS gave me Controllers, Data resources and even View
templates in that "View", in another word: Client side itself can be a real
Application. So now my approach is:
Server do the "server job" like: read and write data , sends data to the
client, receive data from client ect....
And client do the "client job": interact with user, do the logic processes
of data BEFORE IT WAS SE
As far as I remember in WinForms, the WebBrowser version was the same as
the version of IE installed on that machine, I'm assuming it's still the
same in WPF. And no, you can't change the default control to use Chrome.
There is however, a .NET implementation of Chromium which according to its
documentation supports HTML5 as well.
According to this thread. It's not possible.
Because it's a Windows only framework.
Edit: This one might also help you.
This is most definitely possible if you are building a native iOS
application.
1) You can communicate with cookies with the NSHTTPCookieStorage APIs.
2) You can send network requests and process their data on a background
queue, after which you can then set the HTML content of the UIWebView (on
the main queue.)
3) Your "tabs" can simply be sibling view controllers which each contain a
UIWebView.
I managed to solve it by injecting the alert blocker on the ProgressChanged
event instead of DocumentCompleted.
private void webBrowser1_ProgressChanged(object sender,
WebBrowserProgressChangedEventArgs e)
{
InjectAlertBlocker();
}
I'm using ObjectForScripting to do these kind of things. It allows
JavaScript to call a C#-Method. Let JavaScript react on events, thats much
easier and you don't need MSHTML. It's nicely explained here. Youl'll need
using System.Runtime.InteropServices; for it to work, so that the app knows
the ComVisible-Annotation.
You don't have to be a JavaScript-pro to use this. For example: Just add a
button like this:
<button
onclick="javascript:window.external.showPpt('test.ppt');">Click
me</button>
which will call a method named showPpt in the ObjectForScripting. Remember:
You may create the HTML using C# too. This way you can store information in
the document. Here is a full example:
public partial class frmBrowser : Form
{
HtmlDocument doc;
[ComVisible(true)]
publ
You could try downloading the image separately from the web browser
control. As access can't do this natively, have a look at this...
To set scroll position in IE, try:
document.body.scrollTop = 150;
There are some good notes in Mozilla's documentation for cross-browser
support:
Edit:
I read on MSDN that scrollTop works in standards mode and for quirks mode
you may neeed to use doScroll():
Browser("Qtp").Page("Quick Test
Professional").Object.body.doScroll("scrollbarPageLeft")
Sorry, no QTP to try on myself.
[EDITED]
What I said below was incorrect. Your syntax is correct,
webBrowser2.Document.InvokeScript("TestClick") should do the same job as
webBrowser2.InvokeScript("TestClick"). I'll try your code and get back
here.
I think the correct syntax should be this:
webBrowser2.Document.InvokeScript("TestClick()");
Note () after TestClick.
Or you could rather do:
webBrowser2.InvokeScript("TestClick");
[EDITED]
There's something wrong with the HTML originally loaded into the WB, maybe
you should include it with your question. The following is just a copy of
your code (besides this.webBrowser2.DocumentText) and it does work,
TestClick gets invoked.
private void Form1_Load(object sender, EventArgs e)
{
this.webBrowser2.DocumentText = "<body><div
id=flls><
Navigate
Loads the document at the specified Uniform Resource Locator (URL) into
the WebBrowser control, replacing the previous document.
Refresh
Reloads the document currently displayed in the WebBrowser control.
A document refresh simply reloads the current page, so the Navigating,
Navigated, and DocumentCompleted events do not occur when you call the
Refresh method.
Note: Links are for webbrowser control but I presume their information is
valid
Putting the form inside an iframe will cause Firefox at least to associate
any stored passwords with the domain of the iframe instead of that of the
Just have the iframe catch the form submit event, serialise the content of
the form, and send it to the main window via postMessage; then the main
window can grab the content of the form from the message and handle it
using Javascript.
Of course, even in simple cases this is a fairly ugly hack, and if there
are complicated interactions between content in the iframe and content or
code in the main page, then trying to handle them all properly via
postMessage may result in a quick descent into pain and spaghetti. If the
value of having cross-domain password autocompletion is lo
Check next post You may experience resource limitations in the Graphics
Device Interface (GDI) when you use the Microsoft Web Browser control. That
post is related to the WinXP or Server 2003 computer that is running
Microsoft Office XP or Microsoft Office 2003.
One more to look is FEATURE_IVIEWOBJECTDRAW_DMLT9_WITH_GDI
Internet Explorer 9. By default, the WebBrowser Control uses Microsoft
DirectX to render webpages, which might cause problems for applications
that use the Draw method to create bitmaps from certain webpages.
The below link was useful in understand the concept.
If the HTTP Response contains the etag entry, the conditional request will
always be made. ETag is a cache validator tag. The client will always send
the etag to the server to see if the element has been modified.
You could generate a temp HTML file to embed the desired PDF:
<body>
<object
classid="clsid:ca8a9780-280d-11cf-a24d-444553540000" id="pdf1"
type="application/pdf"
data="test.pdf"
style="width: 100%; height: 100%">
<param name="src" "value"="test.pdf"></param>
</object>
</body>
What's interesting, to make it work with a local (file://) PDF document, I
had to specify both data attribute and src param. When it was served via
http from localhost, the data alone was just enough.
UPDATE: I could not tell why this doesn't work for the OP, so I've cooked
up a very basic C# WebBrowser project demo'ing this. It works quite
reliably in my environment (Win8, IE10, Acrobat Reader 11.0.3).
UPDATE: I think I understand why this is happening. Your pro
Some one please provide me crisp and working solution for my
implementation.
I wouldn't count on that, especially if you're asking for a source code
solution.
Single sign-on assumes that you still have an authentication server
somewhere, something like Google OAuth. From your question, it isn't quite
clear to me if that's what your looking for. If you just need to supply
custom credentials to WebBrowser control, that's still possible, but that
solution is for WinForms version of WebBrowser control. The WPF version is
sealed from customization, so you may have better luck hosting the WinForms
WebBrowser in your WPF project, using WindowsFormsHost.
Lets say the ActiveSheet is Sheet1
Goto Object Browser > check for Class sheet1 under classes > Look for
Members of Sheet1
("WebBrowser1" should be there as a property)
Now Search for Class WebBrowser under Classes > Look for Members of
WebBrowser
(Check if Visible property is there. If yes (Sheet1.WebBrowser1.Visible =
True) should work for you.
Else navigate through the property and identify which other property can be
used to hide
(you may guess it by name))
It seems that the children of div.mejs-controls overflowed when scaling the
page, but it isn't a CSS case. The size of div.mejs-time-rail is generated
by Javascript dynamically.
()
I found a trick that can simply solve the problem, which is to decrease the
width of div.mejs-time-rail by 1px.
So here I got a quick fix. In mep-player.js, line
845(),
modify following
total.width(railWidth - (total.outerWidth(true) - total.width()));
to
total.width(railWidth - (total.outerWidth(true) - total.width()) - 1);
You can simply use the Print() method of WebBrowser if you put it into the
DocumentCompleted event:
private void webBrowser1_DocumentCompleted(object sender,
WebBrowserDocumentCompletedEventArgs e)
{
webBrowser1.Print();
}
After the print you can pass to the next page to print:
private void webBrowser1_DocumentCompleted(object sender,
WebBrowserDocumentCompletedEventArgs e)
{
webBrowser1.Print();
webBrowser1.Navigate(nextPage());
}
The only thing you need now is to make the WebBrowser navigate to the first
page (you can set it on the constructor of the form)
I would recommend making the page look correct in browsers that follow web
standards first (Firefox, Chrome). Then fix up for IE later. There is no
way to do what you're suggesting. Those meta tags are for making later
versions of IE behave like earlier versions.
One method is to reload the page. I guess.. Using the following method..
var js = "window.location.reload(true);";
wbcontent.InvokeScript("eval", js);
But what i really do want to know is why the audio continues to play even
after i have exited the web browser control.
This example works for me you may try this.
public function getOwnlist(){
$images =
User::with('images.category')->find(Auth::getUser()->getAttribute('id'));
return Response::json($images, 200, array('Access-Control-Allow-Origin'
=> '*'));
}
Also, I highly recommend setting those on the constructor of your
Controller Base instead of setting the headers in each response. Or you can
create one only to serve API and extend from it.
Should be something like:
protected $response; // This is a global variable on you BaseController
// This goes on your BaseController constructor
$this->response = Response::make();
$this->response->headers->add(array('Access-Control-Allow-Origin',
'*');
I found some issues with Cross Domain AJAX while using jQuery, it only
works
Did);
(1) No. There no possible cross-browser way to control browser
functionality with javascript/jquery.
(2) Banking sites do not restrict or control the browser functionality.
They only ask users to desist. At most they attempt to detect some actions
and then show errors. But, they don't try to control the browser.
(3) This is a bad idea.
You'll have to use a responsive layout to resize the image according to the
screen size.
Example of responsive layout rule:
@media screen and (max-device-width: 480px) {
.column {
float: none;
}
}
You can always search "responsive design" at any web search engine to get
great references.
I have worked around this by adding action="javascript:void(0);" to you
form (see updated fiddle).
I do not know if this is good enough but action="javascript:void(0);" is in
fact part of a solution given to a similar question.
<form method="post" action="javascript:void(0);">
<input type="text" name="field1" value="some msg" />
<input type="text" name="field2" value="some msg" />
<input type="submit" />
</form>
Probably what you meant was simply:
var uri = '/viewer/loaddrawing/';
document.getElementById('iframetitle').src = uri + '?key=' + value;
There is no JSON involved, so the iframe will get a PDF directly. However,
notice that the client must have a PDF-viewer plugin, otherwise the browser
will ask for a download prompt.
I have been using this as a workaround (opening an inappbrowser instance):
// Image zoom
$('#container').on('tap', '#content.cmscontent img', function() {
var browser = window.open((navigator.userAgent.indexOf('Android') != -1
? '' : '') + encodeURI($(this).attr('src')),
'_blank',
'location=no,toolbar=yes,enableViewportScale=yes,transitionstyle=crossdissolve');
});
See I added (navigator.userAgent.indexOf('Android') != -1 ?
'' : '') as a prefix before the url. Now it
detects when you're app is on Android and adds the local URL in front of
it.
Modified another code snippet for it to work properly on browser. The code
snippet, I modified is mentioned at the link below.
Preview an image before it is uploaded
Below is the code snippet which work properly on both desktop browser as
well as mobile browser.
<!DOCTYPE html>
<html>
<head>
<title>File API- FileReader as Data URL</title>
</head>
<body>
<input type='file' id="imgInp" />
<img id="myImage" src="#" alt="your image" />
</body>
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementById('myImage').src=e.target.result;
}
reader.readAsDataURL(inpu
I don't understand your problem clearly but may this help you:
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse((String)
i.getExtras().get("url")));
startActivity(browserIntent);
where "url" is the URL to which you want to go in your browser.
And i is an INTENT that holds the "url" from another activity.
Can this help you?
You cannot reclaim the session-id as such, but you can certainly restore
some of the predictable part of the session state. If you are using forms
authentication, then just read the forms-auth cookie in global.asax session
start and re-populate the session objects.
You can control the expiration of forms-authentication cookie manually by
creating a persistent cookie by using:
FormsAuthentication.SetAuthCookie(userName, true)
Alternatively, you can fine-tune the expiration by manually changing the
cookie:
Dim authCookie As HttpCookie = FormsAuthentication.GetAuthCookie(userName)
Dim authTicket As FormsAuthenticationTicket =
FormsAuthentication.Decrypt(authCookie.Value)
Dim newAuthTicket As New FormsAuthenticationTicket(authTicket.Version,
authTicket.Name, authTicket.IssueDate, expireDa
The pdf will not get render as android webview does not support rendering
pdf and the childbrowser uses android webview.
Instead you can use some third party sdks for rendering in Android.
Most of them require license(like quoppa,pdfViewer).
I have not seen any opensource but you can look into the follwing link
For ios you can use pspdfkit.They are providing a cordova plugin also.
go through the following link.
Try adding user-scalable=yes to your viewport meta tag
<meta name="viewport" id="view" content="width=device-width
minimum-scale=1, maximum-scale=1" />
to give you
<meta name="viewport" id="view" content="width=device-width
minimum-scale=1, maximum-scale=1", , user-scalable=no />
And I would move your Meta tage up near the top with the rest. | http://www.w3hello.com/questions/-Help-using-Web-Browser-control-in-ASP-NET- | CC-MAIN-2018-17 | refinedweb | 2,644 | 56.45 |
Areas in MVC is a way to segregate or partite a large application into small business groups so that it may be easier to manage. In this article I will demonstrate about Area in MVC.
One of the reason for popularity of MVC design pattern is logical separation of Model, View and Controller. We can see this logical separation physically in project structure also. This structure is very helpful in maintaining project as we can separately put our views, controllers and models in their associated folders.But when we work in a large project where there is a possibility to have a large number of controllers and views then this structure looks like unmanageable. In this case we need something else. To accommodate such projects, we can use MVC feature to segregate Web application into smaller units that are referred to as areas.
Areas provide a way to separate a large MVC Web application into smaller groups so that it can be managed in a proper way.
We can create number of Areas we required in an application.
I think, this makes a clear picture about Area. Let's see how can we create and use Areas in our application with a small example.
Adding areas into project is very simple. Follow the below steps and you can add your area.
Right Click on project > Click Add > Area
A popup will open. Name your area and you can see in project structure under Areas folder.
I created two areas in my example- for Sale and Purchase. Once added area, you can see Area Registration for the same. In this class route will be defined automatically for that area. Below is the code for my Sale area I defined.
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Sale_default",
"Sale/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
Once you are done with area, you can find folders for Controller, Views and Model in your area with an AreaRegistration class which defines routing for your area. In my example as I said, I created two areas-Sales and Purchase just for better understanding and in both the areas I created an ExampleController, Model and related view. Let's see one by one. I will show for Sales area. Purchase area is same as Sales area.
In sales area I am creating a model class and naming it as SalesModel.cs. Below is the code for my model.
namespace DotNetConceptSampleAreaInMVCExample.Areas.Sale.Models
{
public class SalesModel
{
public int Id { get; set; }
public string ProductName { get; set; }
public string BatchName { get; set; }
public int Quantity { get; set; }
public double Price { get; set; }
}
}
Once I am done with my model, let's create a controller. I am naming it as ExampleController.cs and creating a list of model. Here is the code for the same.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DotNetConceptSampleAreaInMVCExample.Areas.Sale.Models;
namespace DotNetConceptSampleAreaInMVCExample.Areas.Sale.Controllers
{
public class ExampleController : Controller
{
public ActionResult Index()
{
var model = CreateModel();
return View(model);
}
List<SalesModel> CreateModel()
{
List<SalesModel> lst= new List<SalesModel>(){
new SalesModel{Id=1,ProductName="Laptop",BatchName="LAP001",Price=40000, Quantity=1},
new SalesModel{Id=2,ProductName="Laptop",BatchName="LAP002",Price=42000, Quantity=1},
new SalesModel{Id=3,ProductName="Laptop",BatchName="LAP003",Price=42500, Quantity=1},
new SalesModel{Id=4,ProductName="Desktop",BatchName="DES004",Price=36000, Quantity=2},
new SalesModel{Id=5,ProductName="Laptop",BatchName="LAP005",Price=40000, Quantity=1}
};
return lst;
}
}
}
After controller now it is time to create a view to show my content. Let's create a view. I am creating a grid to show the list I created in my controller above.
@model IEnumerable<DotNetConceptSampleAreaInMVCExample.Areas.Sale.Models.SalesModel>
@{
ViewBag.Title = "Sales";
}
<h2>Welcome to Sales:</h2>
<a href="~/Home/Index">Home</a> | <a href="~/Purchase/Example/Index">Click for Purchase</a>
<hr />
@{
var grid1 = new WebGrid(source: Model, ajaxUpdateContainerId: "divGrid");
<div id="divGrid">
@grid1.GetHtml(tableStyle:"webGrid",
columns:grid1.Columns(
grid1.Column("ID"),
grid1.Column("ProductName"),
grid1.Column("BatchName"),
grid1.Column("Price"),
grid1.Column("Quantity")))
</div>
}
I am almost done. Now to show navigation I am creating links for these areas in my main view.
<h2>Please click below for Area navigation:</h2>
<br />
<a href="~/Sale/Example/Index">Click for Sales</a> | <a href="~/Purchase/Example/Index">Click for Purchase</a>
<br />
And I am done. Output will be something like this.
Hope now you are clear on Areas. So try yourself and use in your code. | http://dotnet-concept.com/Articles/2014/1/1/Using-Areas-in-MVC | CC-MAIN-2018-13 | refinedweb | 752 | 50.02 |
Powering Publish And Subscribe Functionality With Native jQuery Event Management
Let's face it - jQuery's native event management is straight-up awesome! Between multi-type binding, name-spaced events, proxied callbacks, and function-specific unbinding, there's not much that it can't do (and do well, for that matter). Without a doubt, it's better than any event management that I could write. As such, I wondered if I could use the native jQuery event management to power publish and subscribe (pub/sub) functionality within my Javascript applications.
While you can use jQuery to bind and trigger events on non-DOM-node Javascript objects, it's not yet clear as to whether or not this functionality is officially supported by the jQuery project. In my experience, there's also too much node-specific logic being used to make this a reliable approach. But, what if we used actual DOM nodes to power eventing within the domain model?
Last week, I confirmed that jQuery could bind and trigger events on detached DOM nodes. This means that we could theoretically use detached DOM nodes as event proxies within our domain objects. In other words, our domain objects could present a bind/unbind/trigger API that actually wrapped around an underlying, detached DOM node.
To explore this concept, I've defined the following Javascript class, Girl. The Girl's prototype (class methods) contains methods for bind(), unbind(), and trigger(). When you look at the logic of these methods, however, you'll notice that they simply pass execution off to an encapsulated, custom DOM node, "beacon."
- <!DOCTYPE html>
- <html>
- <head>
- <title>Creating Publish/Subscribe With jQuery Event Bindings</title>
- <script type="text/javascript" src="./jquery-1.4.2.js"></script>
- <script type="text/javascript">
- // Define the girl class.
- function Girl(name){
- this.name = name;
- // Internally, we are going to keep a free-standing DOM
- // node to power our publish / subscribe event mechanism
- // using jQuery's bind/trigger functionality.
- //
- // NOTE: We are using a custom node type here so that we
- // don't have any unexpected event behavior based on the
- // node type.
- this.eventBeacon = $(
- document.createElement( "beacon" )
- );
- // Create a help collection of bound event types.
- this.eventBeacon.data( "preTrigger", {} );
- }
- // Define proxy bind method.
- Girl.prototype.bind = function( eventType, callback ){
- // Check to see this event type has a pre-trigger
- // interceptor yet. Since event handlers are triggered
- // in the order in which they were bound, we can be sure
- // that our preTrigger goes first.
- if (!this.eventBeacon.data( "preTrigger" )[ eventType ]){
- // We need to bind the pre-trigger first so it can
- // change the target appropriatly before any other
- // event handlers get triggered.
- this.eventBeacon.bind(
- eventType,
- jQuery.proxy( this.preTrigger, this )
- );
- // Keep track fo the event type so we don't re-bind
- // this prehandler.
- this.eventBeacon.data( "preTrigger" )[ eventType ] = true;
- }
- // Replace the callback function with a proxied callback
- // that will execute in the context of this Girl object.
- arguments[ arguments.length - 1 ] = jQuery.proxy(
- arguments[ arguments.length - 1 ],
- this
- );
- // Now, when passing the execution off to bind(), we will
- // apply the arguments; this way, we can use the optional
- // data argument if it is provided.
- jQuery.fn.bind.apply( this.eventBeacon, arguments );
- // Return this object reference for method chaining.
- return( this );
- };
- // Define proxy unbind method.
- Girl.prototype.unbind = function( eventType, callback ){
- // Pass the unbind() request onto the event beacon.
- this.eventBeacon.unbind( eventType, callback );
- // Return this object reference for method chaining.
- return( this );
- };
- // Define proxy trigger method.
- Girl.prototype.trigger = function( eventType, data ){
- // Pass the trigger() request onto the event beacon.
- this.eventBeacon.trigger( eventType, data );
- // Return this object reference for method chaining.
- return( this );
- };
- // I am the first handler to be bound on this object for any
- // event-type. I change the Target property to be the Girl
- // instance, not the DOM node.
- Girl.prototype.preTrigger = function( event ){
- // Mutate the event to point to the right target.
- event.target = this;
- };
- // -------------------------------------------------- //
- // -------------------------------------------------- //
- // -------------------------------------------------- //
- // -------------------------------------------------- //
- // Create a new girl instance.
- var tricia = new Girl( "Tricia" );
- // Define some function references which we can use later
- // when we unbind the event handlers.
- var normalHandler = null;
- var hormonalHandler = null;
- // Bind to any mood changes that are normal.
- tricia.bind(
- "moodChange.normal",
- {
- handlerType: "normal"
- },
- normalHandler = function( event, oldMood, newMood ){
- console.log( "Target: ", event.target );
- console.log( event.data.handlerType );
- console.log( this.name + ", hey there " + newMood + "-pants!" );
- }
- );
- // Bind to any mood changes that are hormonal.
- tricia.bind(
- "moodChange.hormonal",
- {
- handlerType: "hormonal"
- },
- hormonalHandler = function( event, oldMood, newMood ){
- console.log( "Target: ", event.target );
- console.log( event.data.handlerType );
- console.log( this.name + ", do you need some time?" );
- }
- );
- // -------------------------------------------------- //
- console.log( "--------------------------------------" );
- // -------------------------------------------------- //
- // Trigger a normal change.
- tricia.trigger(
- "moodChange.normal",
- [ "relaxed", "sassy" ]
- );
- // Trigger a hormonal change.
- tricia.trigger(
- "moodChange.hormonal",
- [ "happy", "truculant" ]
- );
- // -------------------------------------------------- //
- console.log( "--------------------------------------" );
- // -------------------------------------------------- //
- // Unbind the hormonal mood change handler. Now, only
- // normal and non-namespaced events will be handled.
- tricia.unbind( "moodChange", hormonalHandler );
- // Trigger non-namespaced change (this will trigger invoke
- // the only remaining event handler - normalHandler).
- tricia.trigger(
- "moodChange",
- [ "sad", "happy" ]
- );
- </script>
- </head>
- <body>
- <!-- Intentionally left blank. -->
- </body>
- </html>
If you look at the Girl's class constructor, you can see that I'm creating an internal jQuery collection that contains a single free-standing DOM node, "beacon." I chose to use a custom DOM node to make sure that none of the internal logic of the jQuery event mechanism would be altered by a more traditional node type (ie. <a>).
Within the Girl's event API, I am passing execution of the event functionality off to the "beacon" node where jQuery can work its magic. For the event handlers, however, you'll notice that I am using the proxy() method such that they will execute in the context of the Girl instance. By using the proxy() method, the original callback references can still be used to unbind a specific event handler (proxy is so badass!).
Notice that when I bind and trigger events on the Girl instance, I am making use of most of the jQuery event handling features (ie. bind-time data, name-spaces, trigger-time data, unbinding). When I run the above code, I get the following console output:
--------------------------------------
Target: Object { name="Tricia", more...}
normal
Tricia, hey there sassy-pants!
Target: Object { name="Tricia", more...}
hormonal
Tricia, do you need some time?
--------------------------------------
Target: Object { name="Tricia", more...}
normal
Tricia, hey there happy-pants!
As you can see, this worked perfectly; not only did the event binding and triggering work, the handlers executed in the context of the Girl instance, the event types were successfully name-spaced, and, thanks the use of proxy(), the "hormonal" event handler could be unbound using the original callback reference.
The biggest stumbling block that I encountered when using this approach was the event's "target" property; no matter how I triggered the event, the target property always pointed to the encapsulated "beacon" DOM node, not to the Girl instance. While this might seem like an insignificant problem, when you consider that event handlers are often proxied, the only way to reference the original Girl instance is to use the event's "target" property.
In order to get around this, I bound a pre-trigger event handler to every event type that was being bound to this Girl. Because jQuery guarantees that it will trigger handlers in the order in which they were bound, I know that I can inject my internal handler as the very first one to be invoked. The job of this pre-trigger event handler is simply to change the event's "target" as the event object begins to propagate.
This target-property workaround is definitely sloppy and leaves something to be desired. I am considering this a proof-of-concept, so I'm not going to worry too much about the fact that these pre-trigger handlers are never unbound and can lead to small duplications in effort.
In order to create a Javascript application that has decoupled modules, it is essential that the domain model contains a robust publication and subscription event mechanism. jQuery already has this kind of functionality; so, rather than building my own sub-par event mechanism, I figured it would be really cool to proxy the existing jQuery event architecture by encapsulating free-standing, detached DOM nodes.
Looking For A New Job?
- Senior Application Developer (Coldfusion) at American Access Casualty Company
- Front end engineer - AngularJS focus at Corbis
- Senior Web Application Developer at SiteVision, Inc.
- ColdFusion Developer Needed at AutoConX Systems
Reader Comments
Very interresting approach to manage events (Class based), and more like an Prototype.js way. I've already used a similar technics (2 years ago...) for jquery with lowPro (), and it was very efficient.
Thanks.
@Romain,
LowPro looks interesting. If I read it correctly, you're attaching an object instance to an element in order to provide a multitude of behaviors?
Where I see class-based event management in shining is when we start to create class-based View-controllers that have to announce events or subscribe to events within a thick-client application.
jquery certainly has excellent event support and is a fantastic javascript library for managing your DOM interactions, however I think using it for pub/sub application framework is inappropriate, in fact all of the common JS DOM libraries fail in this regard, YUI, protoype, and dojo. They all provide great widgets, however they were not originally intended to be anything more than a better layer to interact with the DOM.
the KVO binding model of Sproutcore is the most powerful I've used hands down.
@Erick,
Can I ask you what make the Sproutcore event binding model so powerful? If nothing else, I'd love to play around with rolling that kind of functionality into other frameworks.
Personally, I use this to add jQuery events to non-DOM objects:
It always seemed to work fine so far and the brevity of the code seems so elegant, but I have a bad gut feeling about "$({})": is it using document internally (which would lead to leaks as far as I've read on some forums) ?
@Thera,
Ah, sorry about the mismatched strong tag.
(I wish there was an edit button :/ )
I forgot in the code snipplet that of course, for firing an event, you would use:
I think I'll just replace
by
then I don't have to wonder if it uses document or not :)
@Ben,
Hi Ben,
(let's hope this post all comes out OK)
Sorry for the (way) late reply - Thera's comment stream grabbed my attention back to this article.
Let me preface this all by saying read the docs, they'll do better than I will at explaining this:
Also let me make clear I won't even try to scratch the surface on Sproutcores actual model, view, or controller layer. This is just an overview of one very high level core concept.
Sproutcore is an entire MVC javascript application framework built closely to model after Apple's Cocoa framework. In fact it is so closely modeled that somewhere around 2008/2009ish Apple decided to adopt the Sproutcore platform as their platform for mobileme and continues to commit to it quite frequently.
Sproutcore's big win is the property binding pattern () that is built directly into the parent object of all Sproutcore objects, SC.Object, so the key-value observing is inherent throughout the entire object hierarchy. Next they have a very easy to use/understand object inheritance model that is built on Crockford's beget scheme, with a bit of OOP flair layered on top. There are 3 main inheritance functions, +mixin+, +extend+, and +create+. Mixin adds properties to the receiver object. Extend uses mixin but makes the receiver object the prototype of the receiver. Create is the initializer function that sets up the prototype chain and +mixins+ any parameters to the initialized object. Finally, there is an extremely advanced run loop written entirely in javascript that manages all event propagation (these aren't native events) in order to assure that bindings fire and avoid browser timeouts in the case of long running code.
So... to put it all together:
As you can see all the core eventing glue is done and inherent in the framework. The KVO pattern is built entirely around the +get+ and +set+ functions which act as smart accessor/mutator functions. The +set+ function in particular is particularly interesting and I haven't really highlighted it's power here at all, nor did I even scratch the surface on computed properties.
There is a TON more to sproutcore than this but it's all built off the core concept of these bindings. The next place to dig into Sproutcores power is in it's advance model layer architecture (the data store):
Enjoy,
EJ
there's a few typos in that code i realize - but i hope you get the gist
@Thera,
You *can* use the jQuery wrapper on Javascript objects, but it is/was a bit buggy depending on the type of event you are trying to trigger and whether or not the JS object has a "lenght" property. I have been told that Javascript objects are officially supported; but, I have not confirmed this and from what I recall, the documentation on it seems to be a little non-committal. But, please please please take that with a grain of salt.
Using "span" is probably a bit safer. I tried to use this approach in my post, creating a new "beacon" DOM object.
People seem to think that using a manually created internal queue is probably the most effective, especially if you don't need the event-canceling kind of stuff.
@Erick,
For starters,
Apple decided to adopt the Sproutcore platform as their platform for mobileme and continues to commit to it quite frequently.
... that is badass!! Talk about a "testimonial"!
I sooorta understand what you're doing there; though without a SproutCore background, it's just a bunch of assumptions. It looks like there is a serious amount of data-binding going on behind the scenes.
I believe that SproutCore has some video tutorials on their site. I looked at them a long time ago, but it's probably a time to check them out again now that I have a bit more experience with architecture.
@Ben,
I sooorta understand what you're doing there; though without a SproutCore background, it's just a bunch of assumptions. It looks like there is a serious amount of data-binding going on behind the scenes.
There is definitely a bunch going on behind the scenes. What I wrote is merely a topic example. Something I never would have been able to write w/o having previously constructed an application on the 0.9.x branch and currently working on version 2 of my app on the SC 1.4.x branch.
The latest version of SC has made huge strides but it is a huge undertaking to go understand what is going on down deep... it's worth the journey though there is some really cool stuff in there.
Cheers,
EJ
@Erick,
Ugg - why do I have to do all this "client" work :) Can't I just sit and play with Javascript all day??? | http://www.bennadel.com/blog/2000-powering-publish-and-subscribe-functionality-with-native-jquery-event-management.htm | CC-MAIN-2015-22 | refinedweb | 2,524 | 53.71 |
21 September 2002 17:55, Martin J. Bligh wrote:
> > - Each process has a homenode assigned to it at creation time
> > (initial load balancing). Memory will be allocated from this node.
=2E..
> #ifdef CONFIG_NUMA
> +#ifdef CONFIG_NUMA_SCHED
> +#define numa_node_id() (current->node)
> +#else
> #define numa_node_id() _cpu_to_node(smp_processor_id())
> +#endif
> #endif /* CONFIG_NUMA */
>
> I'm not convinced it's a good idea to modify this generic function,
> which was meant to tell you what node you're running on. I can't
> see it being used anywhere else right now, but wouldn't it be better
> to just modify alloc_pages instead to use current->node, and leave
> this macro as intended? Or make a process_node_id or something?
OK, I see your point and I agree that numa_node_is() should be similar to
smp_processor_id(). I'll change the alloc_pages instead.
Do you think it makes sense to get memory from the homenode only for
user processes? Many kernel threads have currently the wrong homenode,
for some of them it's unclear which homenode they should have...
There is an alternative idea (we discussed this at OLS with Andrea, maybe
you remember): allocate memory from the current node and keep statistics
on where it is allocated. Determine the homenode from this (from time to
time) and schedule accordingly. This eliminates the initial load balancin=
g
and leaves it all to the scheduler, but has the drawback that memory can
be somewhat scattered across the nodes. Any comments? | https://sourceforge.net/p/lse/mailman/message/9107232/ | CC-MAIN-2017-34 | refinedweb | 238 | 62.17 |
Jupyter notebooks are a great way to write and run Python code. Jupyter notebooks can produce text output, plots, and animations. Static Jupyter notebooks can be shared on GitHub.com and nbviewer. Another way to share Jupyter notebooks is a great Python package called Voila. Voila turns Jupyter notebooks into deployable web apps. In this post, you'll learn how to deploy a Jupyter notebook as a cloud-based web app with Voila and the cloud hosting service Heroku.
Prerequisites
This tutorial assumes you have Python installed on your local computer. I recommend installing the Anaconda distribution of Python Version 3.7, but you can also install Python from Python.org or the Windows Store. It is also assumed that you either have Windows Subsystem for Linux (WSL) installed or you are using MacOS or Linux itself. I recommend Ubuntu 18.04 LTS for your Linux distribution. You should also be able to bring up a terminal in your preferred operating system and be able to use some basic terminal commands such as
cd to change directories,
mkdir to make a new directory
pwd to list the contents of a directory and
cd .. to go back a directory.
- Prerequisites
- Voila
- Install Voila and Jupyter
- Create a Jupyter notebook with Widgets
- Test Voila locally
- Deploy Voila App on Heroku
- View the Web App Online
- Summary
Voila
What is Voila? Voila is a Python package that turns Jupyter notebooks into working web sites. It is pretty amazing. Another Python package called Streamlit turns .py-files into websites. Voila does the same that Streamlit does to .py-files, except for Jupyter notebooks.
Link to the Voila documentation:
Any Jupyter notebook can be turned into a website with Voila. Voila is specifically useful for turning Jupyter notebooks with embedded widgets into working websites.
Install Voila and Jupyter
Before we start writing any code, we need to install Voila and Jupyter. These packages can be installed using a terminal. In our example, we are also going to use NumPy and Matplotlib. The commands below show a virtual environment created with Python's built-in venv module. You could also create a virtual environment with conda if you are using the Anaconda distribution of Python. Note the command
source venv/bin/activate will only work on MacOS, Linux, or WSL (Windows Subsystem for Linux). On Windows 10, use
venv\Scripts\activate.bat instead.
mkdir voila cd voila python -m venv venv source venv/bin/activate pip install voila pip install jupyter numpy matplotlib
Next, open a Jupyter notebook.
jupyter notebook
Create a Jupyter notebook with Widgets
Before we can deploy our Jupyter notebook as a cloud-based web app, we need to write a few cells in our Jupyter notebook. Any markdown cells in our Jupyter notebook will become text on our website. Any plots or widgets will also become part of the website. Code cells can be used on our website, but the code cells will not be seen by our website's visitors.
Save the new Jupyter notebook as
app.ipynb. Jupyter notebooks can be re-named by clicking on the notebook name in the upper left-hand corner. Note that you do not include the
.ipynb file extension when renaming a Jupyter notebook.
Our Jupyter notebook needs to start with a couple of import lines. Note that we don't need to import Volia into the notebook that will become the website. We just need to install Voila into the environment that will deploy the website.
At the top of the Jupyter notebook, enter some header text into a markdown cell.
# Voila Web App ## A website built out of a Jupyter notebook using Voila
Below the markdown cell in the notebook, enter the import lines below into a code cell. These lines of code import NumPy, Matplotlib and Jupyter notebook widgets.
import numpy as np import matplotlib.pyplot as plt from ipywidgets import interactive %matplotlib inline
After the imports, enter the code below into a code cell. The code creates an interactive plot of the sine function using Jupyter notebook widgets, NumPy and Matplotlib.
def plot_func(a, f): plt.figure(2) x = np.linspace(0, 2*np.pi, num=1000) y = a*np.sin(1/f*x) plt.plot(x,y) plt.ylim(-1.1, 1.1) plt.title('a sin(f)') plt.show() interactive_plot = interactive(plot_func, a=(-1,0,0.1), f=(0.1, 1)) output = interactive_plot.children[-1] output.layout.height = '300px' interactive_plot
Run the code cell and play with the sliders and see the plot change. The sliders should change the frequency and amplitude of the sine wave.
Test Voila locally
Next, we can test our website running on our local machine. Close the Jupyter notebook and make sure the environment where Voila was installed is activate. Type the command below into a terminal to run the app locally. Note how we don't see the code in the code cells of our Jupyter notebook; we just see the markdown cells, sliders and plot.
voila app.ipynb
Great! The Voila app works locally and we can move the sliders and see the plot change, just like when we ran the code cell in the Jupyter notebook. So... next, we need to deploy this Voila app online so that other people can see it and interact with it too.
Deploy Voila App on Heroku
We are going to deploy our Voila web app on Heroku. Heroku is a service that hosts web apps and takes care of server administration for you. You can deploy Flask or Django webs apps on Heroku. We can also deploy our Voila app on Heroku. Luckily, Heroku has a free tier- you can try out deploying Voila online without having to pay any money.
A couple of steps need to be completed before we deploy our Voila app on Heroku.
Create Three Files
The first step to deploy our Voila app on Heroku is to create three files that Heroku requires. The three required files are:
requirements.txt
runtime.txt
Procfile
requirements.txt
Create the
requirements.txt file with pip. The
requirements.txt file tells Heroku which Python packages to install when it runs our web app.
pip freeze > requirements.txt
runtime.txt
The
runtime.txt file specifies the version of Python we want Heroku to use. Create a new file called
runtime.txt. Inside the file, just one line of text is needed. Note the lowercase
python and the dash
-.
python-3.7.6
Procfile
The last required file for our Heroku deployment is a
Procfile. This file includes the instructions for Heroku to deploy our Voila app. Create a new file named
Procfile (no extension) and include the text below:
web: voila —-port=$PORT —-no-browser app.ipynb
Next, we'll use the Heroku command-line interface (CLI) to deploy our app.
Install the Heroku CLI
The Heroku CLI (command line interface) is the way we are going to deploy our Voila web app online. I had the most success installing the Heroku CLI on Linux, MacOS or WSL (Windows Subsystem for Linux). I had trouble installing the Heroku CLI on regular Windows 10. A link to instructions on how to install the Heroku CLI is below:
After the Heroku CLI is installed, a couple more steps are needed before we can deploy our Voila app online.
Create a git Repo
I'm using Windows 10. And because we need to use WSL to use the Heroku CLI, we have to move the whole project into the proper WSL folder. You could move it over manually using the Windows file browser, but the way I did it was to save the project on GitHub.com and then pull the project down from GitHub.com in WSL using git.
Create repo on GitHub.com
Log into GitHub.com and create a new repo. I always add a readme,
.gitignore, and a license.
Make sure to copy the GitHub URL from the repo to make the next step easier.
Add, commit and push local files to GitHub
Next, back on your local machine, move into the main project directory that contains the
app.ipynb file. Use the commands below to create a local git repo and add the newly created GitHub.com repo as a remote. Make sure to change
<username> and
<reponame> corresponding to you and your project. Add all the files in the directory, commit and push up to Github.
git init git remote add origin<usename>/<reponame> git add . git commit -m "initial commit" git push origin master
Pull the Repo down into WSL
Now that the repo is up on GitHub.com, we can pull it down into WSL where the Heroku CLI is installed. Back in the Windows Subsystem for Linux terminal, type the following commands. Make sure to change
<username> and
<reponame> corresponding to you and your project.
mkdir voila cd voila git init git remote add origin<username>/<reponame> git pull origin master
After you pull the repo down from GitHub, the following files should be present.
. ├── LICENSE ├── .gitignore ├── Procfile ├── README.md ├── app.ipynb ├── requirements.txt └── runtime.txt
Now we can push our project up to Heroku.
Push to Heroku
After our files are pushed to GitHub, we are almost done. All that's left is to push the files to Heroku and view our live web app. Use the
heroku create command to create a new Heroku instance.hergit
heroku login heroku create
The output will look something like below:
Creating app... done, ⬢ apple-crumble-25196 |
The last thing to do is to push the changes to Heroku to publish our app.
git push heroku master
The first time the command is run, it will take a little time for the web app to be deployed.
View the Web App Online
You can view the web app running with the following Heroku CLI command:
heroku open
A web browser window should pop up and you should be able to see your web app running!
When the slider is moved, you will be able to see the plot change. The web address in the address bar can be shared with colleagues and friends.
Summary
In this post, we created a website from a Jupyter notebook using Voila. First, we created a Jupyter notebook with an interactive widget. Then we ran Voila locally and saw a preview of what the app would look like online. Lastly, we published the app on Heroku using the Heroku CLI. Thanks to all the maintainers of Voila. It is a wonderful package. | https://pythonforundergradengineers.com/deploy-jupyter-notebook-voila-heroku.html | CC-MAIN-2020-24 | refinedweb | 1,758 | 75.3 |
jTextField1.setText(String.valueOf(l.getCode())); share|improve this answer answered Mar 5 '13 at 11:24 Rais Alam 4,458104381 add a comment| up vote 3 down vote Use Integer.toString(l.getCode); share|improve this answer answered Mar 5 '13 Mostrar más Cargando... If you do explain it (in your answer), you are far more likely to get more upvotes—and the questioner actually learns something! –The Guy with The Hat Sep 10 '14 at On break with the proprietary solutions, Talend Open Data Solutions has the most open, productive, powerful and flexible Data Management solutions or manage your data warehouse- Open Studio -to the data have a peek at this web-site
Disclaimer: The intent of the site is to help students and professional in their academics and career.Though best effort are made to present the most accurate information, No guarantees are made Telusko Learnings 23.172 visualizaciones 10:26 About java.lang.String, why String is special in java - String tutorial - Duración: 39:19. I guess I should use the Expression builder but I cannot find out the correct syntax.Some one can hel me ?Many thanks in advance.I'm running Talend V 2.2 project in Java Branded Logo Design 2.506 visualizaciones 5:59 Java Programming Ep. 3: Strings & Scanner Input - Duración: 14:44.
My manager said I spend too much time on Stack Exchange. How did early mathematicians make it without Set theory? Click here for more information. I didn't see that last phrase of your answer.
share|improve this answer edited Dec 26 '14 at 8:07 answered Dec 26 '14 at 6:38 Onots 1,6451019 Where is the like button here?.. –Devenv Sep 1 '15 at 19:43 Integer i = 33; String s = i.toString(); //or s = String.valueOf(i); //or s = "" + i; Casting. For organizations looking to jump-start a big data analytics initiative, Talend provides applications that accelerate data loading and other aspects of Hadoop setup by enabling developers and analysts to leverage powerful Cannot Convert From Void To String In Java For instance, if I have a Foo reference that I know is a FooSubclass instance, then (FooSubclass)Foo tells the compiler, "don't change the instance, just know that it's actually a FooSubclass.
Talend's open source solutions for developing and deploying data management services like ETL, data profiling, data governance, and MDM are affordable, easy to use, and proven in demanding production environments around Convert Int To String C# Is it acceptable to ask an unknown professor outside my dept for help in a related field during his office hours? To convert an integer to string use: String.valueOf(integer), or Integer.toString(integer) for primitive, or Integer.toString() for the object. Slaxmi Raj Ranch Hand Posts: 45 posted 4 years ago public class Test15 { public Integer showVal; public void methodOne() { Integer i=new Integer(1); showVal=i; methodTwo(i); } private void methodTwo(Integer val)
RegisterLog in Talend TalendForge Downloads Exchange Forum Tutorials Sources Bugtracker Other Babili Components Want to talk about Talend Open Studio? Int Cannot Be Dereferenced floatValue() - Duración: 6:33. more stack exchange communities company blog Stack Exchange Inbox Reputation and Badges sign up log in tour help Tour Start here for a quick overview of the site Help Center Detailed Talend's ESB and data services infrastructure solutions extend proven Apache open source ESB technologies like Apache CXF, Camel, Karaf and ActiveMQ to deliver affordable, flexible service enablement of distributed applications.
Primenary Strings Storage of a material that passes through non-living matter Draw some mountain peaks Why do I never get a mention at work? Cerrar Más información View this message in English Estás viendo YouTube en Español (España). Cannot Convert From Int To String C# Were the Smurfs the first to smurf their smurfs? Type Mismatch Cannot Convert From String To Int In Java Linked 0 Simple parse of an int into a string 0 I have a listbox of ports, I keep getting “Cannot implicitly convert type 'int' to 'string'” 0 Count the Number
share|improve this answer edited Jan 23 '12 at 15:00 answered Jan 23 '12 at 14:46 Jonathan 4,77321835 OP is starting with an Integer object. Check This Out Below is an example of a defined integer set to the value of 1.int myInteger = 1;2 . What is the definition of "rare language"? Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count). Convert Integer To String Java
Join them; it only takes a minute: Sign up Convert int to string? Could you give me the right syntax please ?thanks in advance Offline Quote #52008-02-04 21:12:33 Volker Brehm Member 1139 posts Volker Brehm said: Re: Taype mismatch : cannot convert fron int ModcrafterdotCom 41.420 visualizaciones 14:44 How to Reverse a String in Java - Duración: 10:26. Source My manager said I spend too much time on Stack Exchange.
Iniciar sesión 34 19 ¿No te gusta este vídeo? Int To String C++ Talend integrates, consolidates, transforms any data - Business - Extract Transform Load - ETL - EAI - ERP Index Tags Timeline User list Rules Search You are not logged in. In it, you'll get: The week's top questions and answers Important community announcements Questions that need answers see an example newsletter By subscribing, you agree to the privacy policy and terms
Deshacer Cerrar Este vídeo no está disponible. If you want a string representation of whatever object, you have to invoke the toString() method; this is not the same as casting the object to a String. Hence as others have mentioned already, to convert an integer to string use: String.valueOf(integer), or Integer.toString(integer) for primitive, or Integer.toString() for the object. Convert Int To String Python Print the variable in the edit plus tool.
share|improve this answer answered Jan 23 '12 at 14:49 yshavit 27.7k44274 add a comment| up vote 0 down vote Use String.valueOf(integer). To print in Java, use the code below.System.out.println(myString);Please feel free to comment!!!!!!!!!!!!!!!!!!!!!!! more stack exchange communities company blog Stack Exchange Inbox Reputation and Badges sign up log in tour help Tour Start here for a quick overview of the site Help Center Detailed have a peek here Matthew Brown Bartender Posts: 4568 9 posted 4 years ago If you're using earlier than Java 1.5, then you'd expect line 14 to throw an error, because you're assigining an int
Click Here ERROR - Type mismatch: cannot convert from int to String Error Type mismatch: cannot convert from int to String Error Type Compile Time Sample Code public class Test { Every object can be casted to an java.lang.Object, not a String. Coding Standard - Time Cost Factor All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter Contact Us | advertise | mobile view | Powered by JForum | Copyright Player claims their wizard character knows everything (from books).
Iniciar sesión 20 Cargando... What does the Hindu religion think of apost! Word or phrase for "using excessive amount of technology to solve a low-tech task" why isn't the interaction of the molecules with the walls of the container (in an ideal gas)
Want to make suggestions and discuss with dev team? Esta función no está disponible en este momento. Unacademy 76.875 visualizaciones 18:06 CA Exercise 1 - Java Tutorials Arrays Strings Scanner Integer - Duración: 12:39. Not the answer you're looking for?
Boggle board game solver in Python more hot questions question feed lang-java about us tour help blog chat data legal privacy policy work here advertising info mobile contact us feedback Technology A string variable needs to be defined to save the converted integer. Cargando... Cambiar a otro idioma: Català | Euskara | Galego | Ver todo Learn more You're viewing YouTube in Spanish (Spain).
more hot questions question feed lang-cs about us tour help blog chat data legal privacy policy work here advertising info mobile contact us feedback Technology Life / Arts Culture / Recreation asked 4 years ago viewed 100663 times active 10 days ago Get the weekly newsletter! | http://hiflytech.com/to-string/cannot-convert-from-int-to-string.html | CC-MAIN-2018-13 | refinedweb | 1,380 | 61.36 |
RTL Interface: Change some elements to LTR
Hello,
I use NPP in a RTL interface.
I’d like to change the following elements to LTR:
- Text in the Status Bar (i.e. align to left).
- Text direction in the Find and Replace various Combo-Boxes.
- Text direction in the Incremental Find Bar.
I’ve managed to change the default text direction in the Incremental Find Bar by calling
setDirLTR()when the FindBar is first displayed (in
FindIncrementDlg::display(bool toShow) const. (FindReplaceDlg.cpp) ).
void setDirLTR() { INPUT inputDirLTR[4] = { { INPUT_KEYBOARD }, { INPUT_KEYBOARD }, { INPUT_KEYBOARD }, { INPUT_KEYBOARD } }; inputDirLTR[0].ki.wScan = (WORD)MapVirtualKey(VK_LCONTROL, 0); inputDirLTR[0].ki.wVk = VK_LCONTROL; inputDirLTR[0].ki.dwFlags = 0; // 0 == Key Down. inputDirLTR[1].ki.wScan = (WORD)MapVirtualKey(VK_LSHIFT, 0); inputDirLTR[1].ki.wVk = VK_LSHIFT; inputDirLTR[1].ki.dwFlags = 0; // 0 == Key Down. inputDirLTR[2].ki.wScan = (WORD)MapVirtualKey(VK_LCONTROL, 0); inputDirLTR[2].ki.wVk = VK_LCONTROL; inputDirLTR[2].ki.dwFlags = KEYEVENTF_KEYUP; inputDirLTR[3].ki.wScan = (WORD)MapVirtualKey(VK_LSHIFT, 0); inputDirLTR[3].ki.wVk = VK_LSHIFT; inputDirLTR[3].ki.dwFlags = KEYEVENTF_KEYUP; SendInput(4, &inputDirLTR[0], sizeof(INPUT)); }
Obviously this is a hack.
I haven’t been able to achieve that with
WS_EX_LAYOUTRTL,
WS_EX_NOINHERITLAYOUT,
WS_EX_LEFTand
WS_EX_LTRREADING.
I’d appreciate your help.
Best regards.
- Claudia Frank
Hello Yaron,
not sure what you’ve already tested but from MS point of view you have to use 4 steps.
// Get the window extended style flagsfor the current window. DWORD dwStyle = GetWindowExStyle(hwnd_); // Is the WS_EX_LAYOUTRTL flag present? BOOL bWSLayout = dwStyle & WS_EX_LAYOUTRTL; // Is the WS_EX_RLTREADING flag present? BOOL bWSReading = dwStyle & WS_EX_RTLREADING; // If either the WS_EX_LAYOUTRTL flag or the WS_EX_RLTREADING flag is present, // but NOT BOTH, set the reading direction to right to left. if ((bWSLayout && !bWSReading) || (!bWSLayout && bWSReading)) { pTextFormat_->SetReadingDirection(DWRITE_READING_DIRECTION_RIGHT_TO_LEFT); }
Hope this is helpful for you.
Cheers
Claudia
Hello Claudia,
Thank you. As always I appreciate your kind help.
I haven’t tried
SetReadingDirection().
For using it I’d have to add the Dwrite.h header; before doing that I’d like to make sure there isn’t a simpler way.
With your permission, let’s concentrate on the Status Bar.
Changing (in StatusBar.cpp)
return (TRUE == ::SendMessage(_hSelf, SB_SETTEXT, whichPart, (LPARAM)_lastSetText.c_str()));
to
return (TRUE == ::SendMessage(_hSelf, SB_SETTEXT, whichPart | SBT_POPOUT, (LPARAM)_lastSetText.c_str()));
does change the bar’s style.
If I understand this article correctly, the text direction can be set there as well.
What do you think?
I’d like to align the text to the left.
The equivalent in your LTR interface would be aligning the the text to the right.
Best regards.
- Claudia Frank
Hello Yaron,
First of all, I don’t have any experience with LTR/RTL stuff.
From what I read, yes, it should do the trick but it seems it also depends on the keyboard layout.
That might be the reason why I can’t get it to work.
This article I just found indicates this.
Unfortunattely I can’t test it as I don’t have a dotnet environment ready.
But from what I understand, creating a window with WS_EX_LAYOUTRTL should be prefered and npp
uses it already for a couple of windows.
Cheers
Claudia
Hello Claudia,
Thanks again. I highly appreciate your time and goodwill.
But from what I understand, creating a window with WS_EX_LAYOUTRTL should be prefered and npp
uses it already for a couple of windows.
Indeed.
This is how NPP changes the editor text direction:
void ScintillaEditView::changeTextDirection(bool isRTL) { long exStyle = ::GetWindowLongPtr(_hSelf, GWL_EXSTYLE); exStyle = isRTL ? exStyle | WS_EX_LAYOUTRTL : exStyle&(~WS_EX_LAYOUTRTL); ::SetWindowLongPtr(_hSelf, GWL_EXSTYLE, exStyle); }
I have managed to flip the Status Bar entire layout with
WS_EX_LAYOUTRTLetc.; changing only parts of an element seems to be more tricky.
Best regards. | https://notepad-plus-plus.org/community/topic/11563/rtl-interface-change-some-elements-to-ltr | CC-MAIN-2019-18 | refinedweb | 608 | 53.07 |
Interactive Halloween props are always fun and they are surprisingly easy to make. This year I designed a simple system that rotates a skull to face you and follows you movements as you walk by.
To accomplish this I used light sensors to detect a person's shadow. An Arduino microcontroller then calculates where they are standing and activates a servo that turns the skull to face them. When they move, the skull turns to follows them.
Step 1: Select a Halloween Prop to Use
The first thing that you need to do is select a Halloween prop that will turn and follow people walking by. Look for props that are both creepy and light weight. I chose to use a foam skull but there are a lot of other props that can also work. Use your imagination.
Step 2: The Light Sensors
This project uses an array of light sensors to detect where a person is standing. I used CdS photoresistors but you could also use phototransistors.
When using photoresistors, you need to be aware that CdS photoresistors can vary quite a lot in their output characteristics. Even if you purchase a set of photoresistors that are the same type from the same manufacturer, the output of one photoresistor can still be very different from the next. There are several ways that you can compensate for this. You could change the other circuit components to match the photoresistors in the desired lighting. Another option is to change the Arduino code to compensate for different values of the photoresistors. You can add in a simple adjustment factor to any inputs, or you can write code that calibrates itself by referencing its average value. If all else fails you can purchase more photoresistors than you need in the hopes that you can get a group of them with approximately the same output characteristics.
Step 3: The Microcontroller
The brain of this project is the Arduino UNO microcontroller. This board has six analog input ports that are used to measure the voltages coming from the light sensors. The Arduino monitors these voltages over time and calculates which sensor experiences the greatest drop in voltage. This typically results from a person walking in front of that sensor and casting a shadow on it. The arduino then activates a servo to turn the skull to face that sensor and the person standing in front of it.
Step 4: The Code
// Here is the Arduino code that I used.
// Open up the Arduino environment. Then copy and paste it into a new sketch.
// Then upload the code to the Arduino board.
#include <Servo.h>
Servo myservo; //create servo object to control a servo
int ResetTimer=0; //sets delay to reset position
int GoalPosition=3; //stores the goal postion (1-5) where the person is standing
int GoalPositionDegrees; //stores the goal position in degrees (30-150)
int CurrentPositionDegrees=90; //stores the current position in degrees (30-150)
int AveragingSpeed=100; //sets how quickly the average values adjust (a lower value changes average value quickly) //quickly. A value of 100 changes the average value slowly
// his effectively sets the speed at which the sensors recalibrate themselves to changing light conditions
int PinOneCurrent; //stores current value of pins 1-5
int PinTwoCurrent;
int PinThreeCurrent;
int PinFourCurrent;
int PinFiveCurrent;
float PinOneAverage; //stores the average value of pins 1-5
float PinTwoAverage;
float PinThreeAverage;
float PinFourAverage;
float PinFiveAverage;
float RatioPinOne=0.00; //stores the ratio of current pin value to average pin value
float RatioPinTwo=0.00;
float RatioPinThree=0.00;
float RatioPinFour=0.00;
float RatioPinFive=0.00;
float Threshold=0.95; //sets minimum threshold for sensors
void setup()
{
myservo.attach(13); //attaches servo to digital pin 13
PinOneAverage = analogRead(1); //reads from sensors to set initial average pin value
PinTwoAverage = analogRead(2);
PinThreeAverage = analogRead(3);
PinFourAverage = analogRead(4);
PinFiveAverage = analogRead(5);
}
void loop()
{
//read analog pins 1-5 and set the result as current value
PinOneCurrent= analogRead(1);
PinTwoCurrent= analogRead(2);
PinThreeCurrent= analogRead(3);
PinFourCurrent= analogRead(4);
PinFiveCurrent= analogRead(5);
//adjust average pin values
PinOneAverage=PinOneAverage+(PinOneCurrent-PinOneAverage)/AveragingSpeed;
PinTwoAverage=PinTwoAverage+(PinTwoCurrent-PinTwoAverage)/AveragingSpeed;
PinThreeAverage=PinThreeAverage+(PinThreeCurrent-PinThreeAverage)/AveragingSpeed;
PinFourAverage=PinFourAverage+(PinFourCurrent-PinFourAverage)/AveragingSpeed;
PinFiveAverage=PinFiveAverage+(PinFiveCurrent-PinFiveAverage)/AveragingSpeed;
//calculates ratio of current pin value to average pin value
RatioPinOne=(float)PinOneCurrent/PinOneAverage;
RatioPinTwo=(float)PinTwoCurrent/PinTwoAverage;
RatioPinThree=(float)PinThreeCurrent/PinThreeAverage;
RatioPinFour=(float)PinFourCurrent/PinFourAverage;
RatioPinFive=(float)PinFiveCurrent/PinFiveAverage;
//determine which ratio is the largest and sets the goal position
//set goal position
if (RatioPinThree < Threshold && RatioPinThree < RatioPinOne && RatioPinThree < RatioPinTwo && RatioPinThree < RatioPinFour && RatioPinThree < RatioPinFive)
{ GoalPosition=3;
ResetTimer=0; }
else if (RatioPinOne < Threshold && RatioPinOne < RatioPinTwo && RatioPinOne < RatioPinThree && RatioPinOne < RatioPinFour && RatioPinOne < RatioPinFive)
{ GoalPosition=1;
ResetTimer=0; }
else if (RatioPinTwo < Threshold && RatioPinTwo < RatioPinOne && RatioPinTwo < RatioPinThree && RatioPinTwo < RatioPinFour && RatioPinTwo < RatioPinFive)
{ GoalPosition=2;
ResetTimer=0; }
else if (RatioPinFour < Threshold && RatioPinFour < RatioPinOne && RatioPinFour < RatioPinTwo && RatioPinFour < RatioPinThree && RatioPinFour < RatioPinFive)
{ GoalPosition=4;
ResetTimer=0; }
else if (RatioPinFive < Threshold && RatioPinFive < RatioPinOne && RatioPinFive < RatioPinTwo && RatioPinFive < RatioPinThree && RatioPinFive < RatioPinFour)
{ GoalPosition=5;
ResetTimer=0; }
else if (ResetTimer > 100) //after delay resets to position 3
{ GoalPosition=3;
ResetTimer=0; }
else
{ ResetTimer=ResetTimer+1; }
GoalPositionDegrees=GoalPosition*25+15; //converts the goal position to degrees
myservo.write(GoalPositionDegrees); //sets the servo position according to the scaled value
delay(30); //sets how quckly the servo turns (lower numbers turn more quickly)
}
Step 5: Attach the Servo to Your Prop and a Base
To be able to turn your prop you need to attach it to a servo motor. How you attach your prop to the servo will depend on the geometry of your prop. Try to find an area where the servo can be easily hidden. If people can see the servo, it will be less impressive.
The skull that I am using has a flat recessed area on the bottom behind the jaw. This made a convenient place to mount the body of the servo. To attach the servo to the skull I applied a generous amount of hot glue to the bottom of the servo and pressed the two together for several minutes. Then I applied more hot glue around the edges.
To mount the skull and servo, I attached the rotor of the servo to piece of cardboard that will act as the base. First make sure that your servo is in the center position. This will make sure that it is oriented properly and can go through the full range of motion. I applied hot glue to the center of the cardboard and to the rotor. Then I pressed the two together for several minutes until the glue hardened. To make it a little more secure, I applied more glue around the edges.
Step 6: Setup the Light Sensor Array on a Breadboard
To assemble the photosensor array each CdS photoresistors is wired in series with a fixed 10kohm resistor. The fixed resistor is connected to GND and the photoresistor is connected to 5VDC . The center pin is connected to an analog input of the arduino. This forms a light sensitive voltage divider. As the light changes, so does the resistance of the photoresistor. This results in a change in voltage at the center pin that is detected by the microcontroller. I used five of these sensors in this project. But you can use as many sensors as you have analog input pins on your Arduino.
First I assembled the sensors on a breadboard. I ran a jumper wire from the 5V pin on the Arduino to one of the power rails on the breadboard. Then I ran a jumper wire from the GND pin on the Arduino to the other power rail. Then I added the photoresistors and 10k resistors between the power rails as shown in the picture above. Then I added a jumper wire from the center pins of each sensor to the analog input pins 1-5 on the Arduino.
Step 7: Attach the Servo to the Breadboard and the Arduino
Now you need to connect the servo to the Arduino. The servo has three wires. The ground wire is typically black or brown. This should be connected to one of the GND pins on the Arduino. The signal wire is typically yellow, orange or white. This should be connected to one of the digital pins on the Arduino. The positive power wire is typically red. This needs to be connected to the 5V pin from the Arduino. Unfortunately there is only one 5V pin on the Arduino and that is already being used to power the light sensors. So you should connect this wire to the positive positive power rail on the breadboard.
Step 8: Test the System
Now you need to test the system to make sure that it is working properly.
Plug the Arduino into your computer and upload the code. If everything wired up correctly, the skull should turn to face one of five positions when you cover the photoresistors with your hand. These five positions should correspond to the five photoresistors.
If the skull is facing the opposite direction from the sensor that you are covering, you can correctly this by switching which analog pins the jumper wires are connected to.
You will probably need to make some adjustments to the code to fine tune how it performs. But that can wait until everything is setup in the final location.
Step 9: Add Extension Wire for Each Photoresistor
In order to be able to mount the photoresistors in their final locations, you need to add extension wires to them.
Cut ten pieces of thin insulated wire that are each several feet long. Then strip the insulation off the ends. You can use individual wires or multi-wire bundle such as a computer connector cable. Remove one of the photoresistors from the breadboard. Then take two of the wires and connect one end of each piece to the locations on the breadboard where the photoresistor leads where inserted. Then connect the other ends to the leads of the photoresistor. For the best connection, you should solder them together.
After connecting the wires you should insulate the contacts. You can do this with either heat shrink tubing or tape. Repeat this process for each of the other photoresistors. Doing them one at a time helps to avoid crossed wires.
Step 10: Mount Everything in Its Final Location
Now it is time to setup everything in its final location. The ideal location for this is a shelf that is between waist height and head height. Place the skull on top of the shelf. If possible, use fabric to cover up the base and to help hide the servo.
Mount the photoresistors on the bottom side of the shelf along the front edge. The easiest way to do this is to just stick it in place with tape. Run the wires to a nearby place where you can hide the Arduino and the breadboard. Adding other decorations can help to hide the wires.
To power the system, you can run a USB cable to a nearby computer or you can use a 5VDC adapter that is plugged into a wall outlet or extension cord.
Step 11: Make Adjustments to the Code
The code that I included has several variables that you can change to adjust the performance of the skull. You can adjust the sensitivity of the sensors. You can change how quickly the system re-calibrates itself to changing light conditions. You can set the time delay before the skull resets its position. Try making adjustments until it performs the way that you like.
Second Prize in the
Halloween Decorations Contest
38 Discussions
Question 5 months ago
I just tried to make this. I’m having no luck. Nothing is working but the lights on the Arduino. Servo does not move. I might have not installed the photoresistors properly?
Answer 4 months ago
Can you post some pictures of your setup?
Reply 4 months ago
Hi there, I'm not the OP but I just encountered the same problem. I believe I have everything set up correctly, and my code uploaded to the board alright, but no luck. Here is a link to images of my setup, any help would be greatly appreciated!
Reply 4 months ago
It looks like you have everything hooked up correctly. Have you checked that your fixed resistor is close to the value of the photo resistor in the lighting that you will have it in?
Reply 4 months ago
I'm a complete novice here so forgive my stupid questions -- when you say "close to the value of the photo resistor in the lighting that you will have it in" do you mean physically move the resistor or adjust the code?
2 years ago
hey, is there a certain min characteristics for the servo? I have this one:is it strong enough to rotate a paper prop?
Reply 2 years ago
It all depends on your specific prop and servo. The best way to find out is to try it out.
4 years ago
awesome project. my six year old daughter and I had fun making this one.
Reply 4 years ago on Introduction
Awesome. Thanks for sharing.
4 years ago on Introduction
Hi! Nice project :)
What happens if you close completly the lights?
thanks!
marC:)
Reply 4 years ago on Introduction
This project requires a direct light source in order to work. You could make something similar that would work in the dark, but that would require infrared LEDs and receivers.
4 years ago on Introduction
Hi! I would like to know if it's possible to do this project with an HC-SR04 ultrasonic proximity? I want to use that project on the Halloween day, outdoor at night, so the photoresistor should have some problems to detect the shadow!
Thanks!
Reply 4 years ago on Introduction
It will probably work as long as the signal is 5 volts or less
Reply 4 years ago on Introduction
Nice! I'll try it!!! (When I will get my HC-SR04 from china! lol! Thanks Ebay!!
Thanks!! :)
4 years ago on Introduction
Hey really liked this project so much that i just finished making my own copy of it however it keeps spazzing out every time i plug it in, i use the original code but i don't know where exactly where to adjust it within the code (if that makes sense). I want it to just move slowly at a constant pace like the one in your youtube video . I also am using 5 sensors instead of 3. Here what it looks like
Reply 4 years ago on Introduction
You can adjust the "threshold" variable. You may need to create a separate threshold variable for each sensor. You can also adjust the averaging speed. Another thing that will help is moving the sensors farther apart. You don't want the shadow to hit more than one sensor at a time.
Reply 4 years ago on Introduction
So if i increase the threshold hold it should help?
4 years ago on Introduction
This is a cheap solution, but if you want highly accurate positioning you could use a Kinect sensor.
5 years ago on Introduction
Hi, I try made this project using Arduino promini and LDR. It reach at goal point 1, but it cannot back to goal point (or reset point) and cannot reach the other goal point.
Can you help me please?
Reply 5 years ago on Introduction
You may need to adjust the sensitivity of the light sensors in the code. Or you may need to change the values of the resistors. | https://www.instructables.com/id/Halloween-Props-That-Turn-to-Look-at-You-as-you-Wa/ | CC-MAIN-2019-13 | refinedweb | 2,597 | 63.19 |
@javax.annotation.PostConstruct javadoc at:
says
Only one method can be annotated with this annotation.
In that case, the following code:
-- cut here --
@Singleton
public class NewSessionBean {
@PostConstruct
void startup2() {
}
@PostConstruct
void startup() throws SQLException {
-- cut here --
should show tag an error.
Thanks a lot for reporting that, it's really good idea for new hint in the EJB area.
However I set the target milestone to Next since it will not be probably enough of time for doing that still for this release.
Done in web-main #acb87914f0bb.
Integrated into 'main-golden', will be available in build *201204140400* on (upload may still be in progress)
Changeset:
User: Martin Fousek <marfous@netbeans.org>
Log: #200715 - Only one @PostConstruct permitted in an EJB + #200716 | https://netbeans.org/bugzilla/show_bug.cgi?id=200715 | CC-MAIN-2015-32 | refinedweb | 123 | 63.09 |
import "gopkg.in/inf.v0".
This package does NOT support:
- rounding to specific precisions (as opposed to specific decimal positions) - the notion of context (each rounding must be explicit) - NaN and Inf values, and distinguishing between positive and negative zero - conversions to and from float32/64 types
Features considered for possible addition:
+ formatting options + Exp method + combined operations such as AddRound/MulAdd etc + exchanging data in decimal32/64/128 formats
A Dec represents a signed arbitrary-precision decimal. It is a combination of a sign, an arbitrary-precision integer coefficient value, and a signed fixed-precision exponent value. The sign and the coefficient value are handled together as a signed value and referred to as the unscaled value. (Positive and negative zero values are not distinguished.) Since the exponent is most commonly non-positive, it is handled in negated form and referred to as scale.
The mathematical value of a Dec equals:
unscaled * 10**(-scale)
Note that different Dec representations may have equal mathematical values.
unscaled scale String() ------------------------- 0 0 "0" 0 2 "0.00" 0 -2 "0" 1 0 "1" 100 2 "1.00" 10 0 "10" 1 -1 "10"
The zero value for a Dec represents the value 0 with scale 0.
Operations are typically performed through the *Dec type. The semantics of the assignment operation "=" for "bare" Dec values is undefined and should not be relied on.
Methods are typically of the form:
func (z *Dec) Op(x, y *Dec) *Dec
and implement operations z = x Op y with the result as receiver; if it is one of the operands it may be overwritten (and its memory reused). To enable chaining of operations, the result is also returned. Methods returning a result other than *Dec take one of the operands as the receiver.
A "bare" Quo method (quotient / division operation) is not provided, as the result is not always a finite decimal and thus in general cannot be represented as a Dec. Instead, in the common case when rounding is (potentially) necessary, QuoRound should be used with a Scale and a Rounder. QuoExact or QuoRound with RoundExact can be used in the special cases when it is known that the result is always a finite decimal.
NewDec allocates and returns a new Dec set to the given int64 unscaled value and scale.
NewDecBig allocates and returns a new Dec set to the given *big.Int unscaled value and scale.
Abs sets z to |x| (the absolute value of x) and returns z.
Add sets z to the sum x+y and returns z. The scale of z is the greater of the scales of x and y.
Cmp compares x and y and returns:
-1 if x < y 0 if x == y +1 if x > y
Format is a support routine for fmt.Formatter. It accepts the decimal formats 'd' and 'f', and handles both equivalently. Width, precision, flags and bases 2, 8, 16 are not supported.
GobDecode implements the gob.GobDecoder interface.
GobEncode implements the gob.GobEncoder interface.
MarshalText implements the encoding.TextMarshaler interface.
Mul sets z to the product x*y and returns z. The scale of z is the sum of the scales of x and y.
Neg sets z to -x and returns z.
QuoExact sets z to the quotient x/y and returns z when x/y is a finite decimal. Otherwise it returns nil and the value of z is undefined.
The scale of a non-nil result is "x.Scale() - y.Scale()" or greater; it is calculated so that the remainder will be zero whenever x/y is a finite decimal.
Code:
// 1 / 3 is an infinite decimal; it has no exact Dec representation x, y := inf.NewDec(1, 0), inf.NewDec(3, 0) z := new(inf.Dec).QuoExact(x, y) fmt.Println(z)
Output:
<nil>
Code:
// 1 / 25 is a finite decimal; it has exact Dec representation x, y := inf.NewDec(1, 0), inf.NewDec(25, 0) z := new(inf.Dec).QuoExact(x, y) fmt.Println(z)
Output:
0.04
QuoRound sets z to the quotient x/y, rounded using the given Rounder to the specified scale.
If the rounder is RoundExact but the result can not be expressed exactly at the specified scale, QuoRound returns nil, and the value of z is undefined.
There is no corresponding Div method; the equivalent can be achieved through the choice of Rounder used.
Code:
// -42 / 400 is an finite decimal with 3 digits beyond the decimal point x, y := inf.NewDec(-42, 0), inf.NewDec(400, 0) // use 2 digits beyond decimal point, round towards positive infinity z := new(inf.Dec).QuoRound(x, y, 2, inf.RoundCeil) fmt.Println(z)
Output:
-0.10
Code:
// 10 / 3 is an infinite decimal; it has no exact Dec representation x, y := inf.NewDec(10, 0), inf.NewDec(3, 0) // use 2 digits beyond the decimal point, round towards 0 z := new(inf.Dec).QuoRound(x, y, 2, inf.RoundDown) fmt.Println(z)
Output:
3.33
Round sets z to the value of x rounded to Scale s using Rounder r, and returns z.
Scale returns the scale of x.
Scan is a support routine for fmt.Scanner; it sets z to the value of the scanned number. It accepts the decimal formats 'd' and 'f', and handles both equivalently. Bases 2, 8, 16 are not supported. The scale of z is the number of digits after the decimal point (including any trailing 0s), or 0 if there is no decimal point.
Code:
// The Scan function is rarely used directly; // the fmt package recognizes it as an implementation of fmt.Scanner. d := new(inf.Dec) _, err := fmt.Sscan("184467440.73709551617", d) if err != nil { log.Println("error scanning value:", err) } else { fmt.Println(d) }
Output:
184467440.73709551617
Set sets z to the value of x and returns z. It does nothing if z == x.
SetScale sets the scale of z, with the unscaled value unchanged, and returns z. The mathematical value of the Dec changes as if it was multiplied by 10**(oldscale-scale).
SetString sets z to the value of s, interpreted as a decimal (base 10), and returns z and a boolean indicating success. The scale of z is the number of digits after the decimal point (including any trailing 0s), or 0 if there is no decimal point. If SetString fails, the value of z is undefined but the returned value is nil.
SetUnscaled sets the unscaled value of z, with the scale unchanged, and returns z.
SetUnscaledBig sets the unscaled value of z, with the scale unchanged, and returns z.
Sign returns:
-1 if x < 0 0 if x == 0 +1 if x > 0
Sub sets z to the difference x-y and returns z. The scale of z is the greater of the scales of x and y.
UnmarshalText implements the encoding.TextUnmarshaler interface.
Unscaled returns the unscaled value of x for u and true for ok when the unscaled value can be represented as int64; otherwise it returns an undefined int64 value for u and false for ok. Use x.UnscaledBig().Int64() to avoid checking the validity of the value when the check is known to be redundant.
UnscaledBig returns the unscaled value of x as *big.Int.
Rounder represents a method for rounding the (possibly infinite decimal) result of a division to a finite Dec. It is used by Dec.Round() and Dec.Quo().
See the Example for results of using each Rounder with some sample values.
var ( RoundDown Rounder // towards 0 RoundUp Rounder // away from 0 RoundFloor Rounder // towards -infinity RoundCeil Rounder // towards +infinity RoundHalfDown Rounder // to nearest; towards 0 if same distance RoundHalfUp Rounder // to nearest; away from 0 if same distance RoundHalfEven Rounder // to nearest; even last digit if same distance )
See for more detailed definitions of these rounding modes.
RoundExact is to be used in the case when rounding is not necessary. When used with Quo or Round, it returns the result verbatim when it can be expressed exactly with the given precision, and it returns nil otherwise. QuoExact is a shorthand for using Quo with RoundExact.
This example displays the results of Dec.Round with each of the Rounders.
Code:
var vals = []struct { x string s inf.Scale }{ {"-0.18", 1}, {"-0.15", 1}, {"-0.12", 1}, {"-0.10", 1}, {"-0.08", 1}, {"-0.05", 1}, {"-0.02", 1}, {"0.00", 1}, {"0.02", 1}, {"0.05", 1}, {"0.08", 1}, {"0.10", 1}, {"0.12", 1}, {"0.15", 1}, {"0.18", 1}, } var rounders = []struct { name string rounder inf.Rounder }{ {"RoundDown", inf.RoundDown}, {"RoundUp", inf.RoundUp}, {"RoundCeil", inf.RoundCeil}, {"RoundFloor", inf.RoundFloor}, {"RoundHalfDown", inf.RoundHalfDown}, {"RoundHalfUp", inf.RoundHalfUp}, {"RoundHalfEven", inf.RoundHalfEven}, {"RoundExact", inf.RoundExact}, } fmt.Println("The results of new(inf.Dec).Round(x, s, inf.RoundXXX):") fmt.Println() w := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', tabwriter.AlignRight) fmt.Fprint(w, "x\ts\t|\t") for _, r := range rounders { fmt.Fprintf(w, "%s\t", r.name[5:]) } fmt.Fprintln(w) for _, v := range vals { fmt.Fprintf(w, "%s\t%d\t|\t", v.x, v.s) for _, r := range rounders { x, _ := new(inf.Dec).SetString(v.x) z := new(inf.Dec).Round(x, v.s, r.rounder) fmt.Fprintf(w, "%d\t", z) } fmt.Fprintln(w) } w.Flush()
Output:
The results of new(inf.Dec).Round(x, s, inf.RoundXXX): x s | Down Up Ceil Floor HalfDown HalfUp HalfEven Exact -0.18 1 | -0.1 -0.2 -0.1 -0.2 -0.2 -0.2 -0.2 <nil> -0.15 1 | -0.1 -0.2 -0.1 -0.2 -0.1 -0.2 -0.2 <nil> -0.12 1 | -0.1 -0.2 -0.1 -0.2 -0.1 -0.1 -0.1 <nil> -0.10 1 | -0.1 -0.1 -0.1 -0.1 -0.1 -0.1 -0.1 -0.1 -0.08 1 | 0.0 -0.1 0.0 -0.1 -0.1 -0.1 -0.1 <nil> -0.05 1 | 0.0 -0.1 0.0 -0.1 0.0 -0.1 0.0 <nil> -0.02 1 | 0.0 -0.1 0.0 -0.1 0.0 0.0 0.0 <nil> 0.00 1 | 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.02 1 | 0.0 0.1 0.1 0.0 0.0 0.0 0.0 <nil> 0.05 1 | 0.0 0.1 0.1 0.0 0.0 0.1 0.0 <nil> 0.08 1 | 0.0 0.1 0.1 0.0 0.1 0.1 0.1 <nil> 0.10 1 | 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.12 1 | 0.1 0.2 0.2 0.1 0.1 0.1 0.1 <nil> 0.15 1 | 0.1 0.2 0.2 0.1 0.1 0.2 0.2 <nil> 0.18 1 | 0.1 0.2 0.2 0.1 0.2 0.2 0.2 <nil>
Scale represents the type used for the scale of a Dec.
Package inf imports 4 packages (graph) and is imported by 413 packages. Updated 2018-05-24. Refresh now. Tools for package owners. | https://godoc.org/gopkg.in/inf.v0 | CC-MAIN-2019-43 | refinedweb | 1,880 | 69.99 |
You want to use QML live code reloading to develop your application and you have custom C++ code? Felgo version 2.16.1 introduces the Live Client Module. You can use it to add QML live reloading features to your own application. This release also adds an important change for iOS app publishing, as well as other fixes and improvements.
Create Mobile Apps with QML Live Reloading on Desktop, Android and iOS
With the Felgo SDK, you can develop your mobile apps with live code reloading. View your app on any connected device at the same time, without waiting for slow deployment.
Tip for Qt developers: You can also use live code reloading with Qt Quick applications that do not include Felgo components! This means if your app uses for example an ApplicationWindow as root component and does not use any Felgo import, the live code reloading for your QML code still works.
How does QML Live Reloading with Felgo Live Work
Time for a quick detour to the basics of a Qt application. It consists of 2 layers.
The C++ layer handles all the core functionality and does the heavy lifting. The C++ layer also contains the QML engine, which is able to load QML code at runtime. Thanks to the QML engine, you can reload the whole QML layer at runtime.
This is exactly what happens when you hit save, and Felgo Live reloads your application. Your changed QML, JS and asset files are transferred to the Felgo Live Client, and the QML layer is reloaded.
All your custom C++ code however is part of the C++ layer. This code requires a build step to compile and deploy with the application. Many of you guys requested to be able to use your own C++ code together with QML live reloading. Good news for you, you can now use the Felgo Live Client Module in your own applications!
How to Build your own Live Client with Custom C++ and Native Code
With the new Live Client Module, you can add live code reloading to your own application in seconds. All you need to do is perform 2 simple steps:
1. Add the felgo-live config to your pro file
Open the *.pro file of your project and change the following line:
CONFIG += felgo
to this:
CONFIG += felgo felgo-live
Or you can also use 2 separate lines like this, so you can enable/disable the Live Client Module easier:
CONFIG += felgo CONFIG += felgo-live
2. Start the Live Client instead of your project main QML file
Go to your project’s main.cpp file and add the following line at the include section at the top:
#include <FelgoLiveClient>
You do not want to load your project’s main QML file initially, instead you want to start as Live Client. Your project will then start with a connection screen and you can connect to the Live Server.
Remove the following 2 lines in your main.cpp file. You will need those lines for standard deployment or publishing later, so only comment them like this:
// felgo.setMainQmlFileName(QStringLiteral("qml/Main.qml")); // engine.load(QUrl(felgo.mainQmlFileName()));
Now we can start the Live Client with one line of code. Add it just before the return statement at the end of the main function:
FelgoLiveClient liveClient(&engine);
That’s it, you turned your own project into a Live Client. Build and run your project for any platform you want, Windows, macOS, Linux, Android or iOS.
You can connect it to your Live Server just like the default Live Clients.
Tip: Disable the automatic start of the default Live Client in your Live Server, because you will use your own client instead!
To switch back to standard deployment, for example to publish your app, just undo the changes above.
Use Cases with new Live Client Module
There also is a more detailed blog post about communication between C++ and QML. These are only short examples, to give you an idea of what you can do.
Add a Global C++ Object as a Context Property
You can make C++ objects accessible from anywhere in your QML files, with a context property.
Expose an object of your custom C++ class with a context property, e.g. in your main.cpp:
int main(int argc, char *argv[]) { MyGlobalObject* instance = new MyGlobalObject(); engine.rootContext()->setContextProperty("myGlobalObject", instance); }
Now you can access your context property from anywhere inside your QML files.
AppButton { text: "Do Something" onClicked: myGlobalObject.doSomething("with this text") }
You can find a full example including the C++ files here: How to Access a C++ Object from QML
Register your C++ Class as QML Type
Another option to communicate between C++ and QML, is exposing your C++ class as QML type.
Expose the QML type, e.g. in your main.cpp:
#include "myqmltype.h" // … int main(int argc, char *argv[]) { // … // MyQMLType will be usable with: import com.yourcompany.xyz 1.0 qmlRegisterType<MyQMLType>("com.yourcompany.xyz", 1, 0, "MyQMLType"); // … }
Use your custom QML type anywhere in your QML files:
import com.yourcompany.xyz 1.0 // … MyQMLType { id: myType someProperty: "someValue" onSomePropertyChanged: doSomething() }
You can find a full example including the C++ files here: How to Register your C++ Class as a QML Type
GitHub Example for using C++ with QML
You can also download this example project from GitHub. The Live Client Module integration steps are already prepared in the FelgoCppQML.pro and main.cpp files, you only need to uncomment them!
Use All Felgo Plugins with Live Reload
Some plugins, like push notifications, rely on the app identifier of an application. With the Live Client Module, you will build your applications with your own app identifier set. This means you can use those plugins with live reloading as well.
Teaser: Use Live Code Reloading also for Published Apps
To see code changes reload your app within seconds on mobile or Desktop without a recompile is a magic moment. Once you experienced it, you’ll wonder how you could develop without it as it is THE biggest time improvement for development.
What if you could also update your published app in the app stores (or on Desktop) just as simple as during development? Your users would not need to update your app via the app stores, but you can choose which version you want to provide them. And this update is available to your users within seconds, no app store update process required.
We are currently working on this solution. If you are interested in access to it, please contact us here.
iOS Bundle Identifier Migration.
More Improvements and Fixes
- SimpleRow now includes a badgeValue property that allows to show a specified value in a badge style on the right edge of the row.
import Felgo 3.0 import QtQuick 2.0 App { id: app Navigation { navigationMode: navigationModeDrawer NavigationItem { icon: IconType.heart title: "Badge Item" badgeValue: "9" NavigationStack { Page { title: "My First App" SimpleRow { badgeValue: "5" text: "Badge Row" } } } } } }
- NavigationItem uses the new SimpleRow::badgeValue property to show a specific value displayed in a badge style on the right edge of the row, if displayed with navigationModeDrawer.
Code Example
- You can now use the SearchBar::textField property to access the internal AppTextField of the search bar.
- Fixes a potential crash and function evaluating warnings during object destruction when a Navigation and NavigationStack setup is used together with a Loader item.
- Resolves a possible memory leak on iOS during app shutdown with the GoogleCloudMessaging and GameCenter plugin._5<<
Release 2.16.0: iPhone X Support and Runtime Screen Orientation Changes
Release 2.15.1: New Firebase Features and New Live Code Reloading Apps | Upgrade to Qt 5.10.1 & Qt Creator 4.5.1
New Mobile App Development Documentation with QML Live Reloading of Code Snippets
| https://felgo.com/updates/release-2-16-1-live-code-reloading-with-custom-c-and-native-code-for-qt | CC-MAIN-2019-39 | refinedweb | 1,298 | 63.59 |
/******************************************************************************
* Player.java - Describe one FIBS player
* $Id$
*
* BuckoFIBS - Backgammon by BuckoSoft
* $Log$
* Revision 1.6 2011/01/04 17:42:02 dick
* Mixing ready and !isPlaying() is a bad idea.
*
* Revision 1.5 2011/01/01 00:17:39 dick
* Convienence constructor to set the player's name.
* Revision 1.4 2010/12/30 04:09:43 dick
* He's really only ready if he is not playing.
* Revision 1.3 2010/12/24 02:59:07 dick
* WinLoss becomes a light object instead of a String.
* Revision 1.2 2010/02/04 09:17:13 inim
* Made player parsing a little more robust
* Revision 1.1 2010/02/04 05:57:53 inim
* Mavenized project folder layout
* Revision 1.13 2010/01/23 06:17:02 dick
* Add the invited flag.
* Revision 1.12 2009/03/04 18:53:59 dick
* Add the winLoss attribute.
* Revision 1.11 2009/02/24 06:58:06 dick
* Add isPlaying().
* Revision 1.10 2009/02/20 10:26:26 dick
* Add id, which is a database key.
* Revision 1.9 2009/02/14 15:43:01 dick
* BuckoFIBS is released under the GNU license.
* Javadoc.
* Revision 1.8 2009/02/11 09:09:13 dick
* setName(s) for when we get an invite from an unknown player.
* Revision 1.7 2009/02/01 21:14:23 dick
* Add the MissManners attribute.
* Revision 1.6 2009/02/01 09:00:08 dick
* Add a saved match status string.
* Revision 1.5 2009/01/28 22:10:57 dick
* Wacky parsing error? How ss[1] be null?
* Revision 1.4 2009/01/28 02:52:31 dick
* Revision 1.3 2009/01/27 19:15:24 dick
* Add bfStatus stuff to handle player warnings.
* Revision 1.2 2008/12/11 10:01:28 dick
* Parse opponent named "-" as empty (no opponent).
* Revision 1.1 2008/03/31 07:10:56 dick
* Describe one FIBS Original Code is BuckoFIBS, <>.
* The Initial Developer of the Original Code is Dick Balaska and BuckoSoft, Corp.
package com.buckosoft.fibs.domain;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Describe one FIBS player. <br>
* Most of these fields don't have setters because this object is mostly filled out from FIBS.
* See {@link #parsePlayer(String)}.
* @author Dick Balaska
* @since 2008/03/31
* @version $Revision$ <br> $Date$
* @see <a href="">cvs Player.java</a>
public class Player implements Comparable<Player> {
private final static boolean DEBUG = false;
private Logger logger = LoggerFactory.getLogger(getClass());
private int id = 0;
private String name = "???";
private String opponent = "";
private String watching = "";
private boolean ready = false;
private boolean away = false;
private double rating = 0.0;
private int experience = 0;
private int idleTime = 0;
private long loginTime = 0;
private String hostName = "";
private String client = "";
private String email = "";
private WinLoss winLoss = null;
private int bfFlag = 0;
private String bfStatus;
private boolean invited = false;
// private boolean hasSavedGame = false;
private String savedMatch;
private String missManners;
/** Create a default/empty Player
*/
public Player() {}
/** Convienence constructor to set the player's name.
* @param playerName The name of this new player.
public Player(String playerName) {
this.name = playerName;
}
/** Get the local player id.
* This is a key to our local database, and is not a FIBS number at all.
* @return the id
public int getId() {
return id;
/** Set the local player id.
* @param id the id to set
public void setId(int id) {
this.id = id;
/** Get the username of this player
* @return The username
public String getName() {
return(name);
/** Set the username of this player.
* This is useful when we get an invite from an unknown player.
* @param name The player's name
public void setName(String name) {
this.name = name;
/** Return true if this player is playing someone.
* This field is derived from the opponent field.
* @return true if playing.
public boolean isPlaying() {
if (opponent.length() > 0)
return(true);
return(false);
/** If this player is playing someone, then return the opponent's name.
* @return The opponent's name or the empty string if not playing anyone.
public String getOpponent() {
return(opponent);
/** If this player is watching someone, then return the name of the player we are watching.
* @return The player being watched or the empty string if not watching anyone.
public String getWatching() {
return(watching);
/** Is this player ready to play?
* @return true if ready to play.
public boolean isReady() {
return(ready);
/** Has this player marked himself as away?
* @return true = yes
public boolean isAway() {
return(away);
/** Get the rating for this player
* @return The rating
public double getRating() {
return(rating);
/** Get the number of games this player has played
* @return The Experience
public int getExperience() {
return(experience);
/** How long has this player been idle?
* @return The number of seconds he has not done anything.
public int getIdleTime() {
return(idleTime);
/** When did this player log in?
* @return The number of seconds since Jan. 1, 1970
public long getLoginTime() {
return(loginTime);
/** Get the hostname of the machine this player is playing on.
* @return The hostname
public String getHostName() {
return(hostName);
/** What client is this player using?
* @return The name of the client.
public String getClient() {
return(client);
/** Set the name of the client that this player is using.
* @param client
public void setClient(String client) {
this.client = client;
/** What is this player's email address?
* @return The email address that the player gave to FIBS (probably not a real email address).
public String getEmail() {
return(email);
/** Return a string of your won/loss record against this player.
* @return the winLoss
public WinLoss getWinLoss() {
return(winLoss);
// if (winLoss == null)
// return("");
// return winLoss.toString();
/** Set the string of your won/loss record against this player.
* @param wins The number of times you have beaten this opponent.
* @param losses The number of times you have lost to this opponent.
public void setWinLoss(int wins, int losses) {
this.winLoss = new WinLoss(wins, losses);
/** Get the BuckoFIBS flag (not used yet)
* @return the bfFlag
public int getBfFlag() {
return bfFlag;
/** Set the BuckoFIBS flag (not used yet)
* @param bfFlag the bfFlag to set
public void setBfFlag(int bfFlag) {
this.bfFlag = bfFlag;
/** If this player has a special status string, like an invite warning, it goes here.
* @return the bfStatus The status string.
public String getBfStatus() {
return bfStatus;
* @param bfStatus the bfStatus to set
public void setBfStatus(String bfStatus) {
this.bfStatus = bfStatus;
/** Have we invited this player?
* @return the invited
public boolean isInvited() {
return invited;
/**
* @param invited the invited to set
public void setInvited(boolean invited) {
this.invited = invited;
/** If you have a saved match with this player, then this string describes it.
* @return the savedMatch or null if none
public String getSavedMatch() {
return savedMatch;
/** Set the savedMatch (tooltip) text
* @param savedMatch the savedMatch to set
public void setSavedMatch(String savedMatch) {
this.savedMatch = savedMatch;
/** If this player has a MissManners warning, this is it.
* @return the missManners warning, or null if this player has none.
public String getMissManners() {
return missManners;
/** Set the MissManners warning issued about this player
* @param missManners the missManners to set
public void setMissManners(String missManners) {
this.missManners = missManners;
/** Parse this player from a FIBS string.
* Fills in most of this object's fields from the FIBS
* <a href="">who info</a> line.
* @param s The who info line from FIBS
* @return success
public boolean parsePlayer(String s) {
String[] ss = s.split(" ");
if (ss.length != 13) {
if (DEBUG) {
logger.info("Error parsing player");
logger.info(s);
}
return(false);
}
name = ss[1];
opponent = ss[2];
if ("-".equals(ss[2]) || opponent == null)
opponent = "";
watching = ss[3];
if ("-".equals(watching))
watching = "";
ready = "1".equals(ss[4]);
away = "1".equals(ss[5]);
rating = Double.parseDouble(ss[6]);
experience = Integer.parseInt(ss[7]);
idleTime = Integer.parseInt(ss[8]);
loginTime = Long.parseLong(ss[9]);
hostName = ss[10];
client = ss[11];
return(true);
/** String compare the name of this player with that one.
* @param o The other player to compare
@Override
public int compareTo(Player o) {
return(this.name.compareToIgnoreCase(o.getName()));
} | http://www.buckosoft.com/fibs/buckofibs/maven/site/cobertura/com.buckosoft.fibs.domain.Player.html | CC-MAIN-2018-26 | refinedweb | 1,308 | 60.01 |
Fullscreen mode and transparent windows are supported in JavaSE 6 since update 10. I have developed the SideBar example for the JavaOne 2008 by using proprietary Java API to create translucent window that slides out of the right side of the screen. Now I am ready to show the SideBar example created by using the JavaFX API only.
Let's create a fullscreen window first. In the current implementation such windows can be opaque only. By this reason this window cannot be used as a SideBar, but its width and height will be further used.
def screen = Stage { fullScreen: true}
You should wait until the window appears in order to initialize its dimensions. As soon as the window's height becomes greater than 0, you can close the window and use its dimensions to initialize the main window. Note that if the auxiliary fullscreen window is closed before the main window is shown up, the application terminates.
def height = bind screen.height on replace { if (height > 0) { screen.close(); // initialize main stage ... }}
The main window contains the following content.
The base of the window is a translucent shape intended for processing of mouse events. This shape is based on a rectangle, whose left edge is a cubic curve instead of a line. Note that the shape of the window is not set, because JavaFX has no appropriate API. Besides, shaped windows do not support anti-aliasing.
Path { fill: COLOR opacity: OPACITY elements: [ MoveTo { x: stage.width } HLineTo { x: offset } CubicCurveTo { x: offset controlX1: x1 controlX2: x2 y: height controlY1: y1 controlY2: y2 } HLineTo { x: stage.width } ] }
The left edge of the shape is set off with a thick opaque cubic curve, whose parameters match those of the basic shape.
CubicCurve { fill: null stroke: COLOR strokeWidth: 4 startX: offset endX: offset controlX1: x1 controlX2: x2 endY: height controlY1: y1 controlY2: y2 }
Drawn over the shape is the rotated translucent text. Although the text has the same color and opacity as the basic shape, the text looks less transparent, because the opacity values are summed up.
Text { content: "JavaFX" opacity: OPACITY fill: COLOR font: Font {size: 220} scaleY: 0.8 translateX: 240 translateY: height transforms: Rotate {angle: 270} }
The close button is drawn in the right top corner of the main window.
Group { translateX: stage.width - 22 translateY: 22 cursor: Cursor.HAND content: [ Circle { fill: COLOR opacity: OPACITY radius: 8 } Line { stroke: COLOR strokeWidth: 4 strokeLineCap: ROUND startX: -4 endX: 3 startY: -4 endY: 3 } Line { stroke: COLOR strokeWidth: 4 strokeLineCap: ROUND startX: -4 endX: 3 startY: 3 endY: -4 } ] onMouseClicked: function(event) { stage.close() } }
The logo of Sun Microsystems is added to the center of the window. The clock widget from my first post about JavaFX is added over the logo. Note that the paused variable of the clock widget is bound to the visible variable. Thus you do not waste the processor time to update the hidden clocks.
paused
visible
ImageView { translateX: stage.width - 142 translateY: 224 image: Image { url: "{__DIR__}sun.png" } } Clock { translateX: stage.width - 222 translateY: 22 paused: bind not visible radius: 100 fill: COLOR }
The SideBar slides out when the mouse cursor hovers over the SideBar content and slides in when the mouse cursor leaves the window.
def slide = Timeline { keyFrames: [ at (0s) {stage.x => screen.width - stage.width} at (1s) {stage.x => screen.width - stage.width / 10} ]}var visible = bind group.hover on replace { slide.rate = if (visible) -1 else 1; slide.play()}
This approach has a couple of disadvantages. First, JavaFX has no API to keep the window on top of other windows even if it has the focus. Second, the closed fullscreen window does not receive events on the screen resolution changes. Therefore the SideBar will work incorrectly when the resolution changes.
Note that the application is signed and requires all permissions to slide out off the screen. The source file of the example is available.
by malenkov - 2009-03-29 23:31
by cheimpel - 2009-03-29 13:28
by thlandgraf - 2009-03-20 06:25
by dafei1288 - 2009-03-20 00:14
by malenkov - 2009-03-19 12:55
by malenkov - 2009-03-19 12:53
by prunge - 2009-03-18 15:44
by cozmint - 2009-03-18 06:26
by ilazarte - 2009-03-19 12:35 malenkov - 2009-03-29 23:31No. I'm waiting for this feature in the common API. Hint: screen.impl_stageDelegate as com.sun.javafx.stage.FrameStageDelegate; delegate.window.setAlwaysOnTop(true); It requires some additional work because of non-public.
by cheimpel - 2009-03-29 13:28Have you tried JFXStage from JFXtras? it has an alwaysOnTop property.
by thlandgraf - 2009-03-20 06:25Works great on MacOSX with the Apple Port of Java5... seems that Apple did some compatibility work with the elder JVM.
by dafei1288 - 2009-03-20 00:14nice job.....
by malenkov - 2009-03-19 12:55@ilazarte: Try Java 6u10 or later because the SideBar uses transparent window.
by malenkov - 2009-03-19 12:53@prunge: I'll try to fix it by using the clip variable, but I can't test it because of single monitor.
by prunge - 2009-03-18 15:44Looks cool - but there are problems when running with multiple monitors. When it slides off my primary display (what would normally be the hidden state) it actually slides onto the left of my secondary monitor.
by cozmint - 2009-03-18 06:26Just a word: amazing.
by ilazarte - 2009-03-19 12:35dont see anything... winxp, java 1.5.0_10. i also launched it via chrome... i see the sidebar app in my application taskbar but i can't find it on screen... | http://weblogs.java.net/blog/malenkov/archive/2009/03/18/sidebarfx | crawl-003 | refinedweb | 942 | 75 |
Related
Question
Sample code to use boto (not boto3) with Spaces
I’m hoping for sample code using boto (not boto3) for writing an object to the Spaces system and then reading it back.
This StackOverflow question 1 suggested one approach to get started, but the following code produces the result
None:
import boto s3 = boto.s3.S3RegionInfo(name='nyc3', endpoint='', aws_access_key_id=XXXX, aws_secret_access_key=XXXX).connect() print s3
I haven’t been able to find anything else potentially relevant.
(Why do I want to use boto instead of boto3? Answer: I have boto3 code working perfectly in my test system, but it fails in what seems to be unpredictable ways when operating at scale, and the fail seems to be inside boto3. If I can get the code working in boto, it is not only a workaround, but would suggest there is a boto3 problem.)
Here is the Stackoverflow page:
Am moving on from this question. Turns out that the perhaps-bug in boto3 was actually due to instability in the Spaces system. | https://www.digitalocean.com/community/questions/sample-code-to-use-boto-not-boto3-with-spaces | CC-MAIN-2020-45 | refinedweb | 173 | 61.56 |
Brian K. Justice (bjustice@fallschurch.esys.com)
Wed, 11 Nov 1998 13:27:27 -0500 (EST)
All,
I caught the discussion that went on here a few months ago
about ht://dig and SSL, but I'm going to bring it up again anyway.
We've used ht://dig to index a bunch of sites, but these sites
are now all going SSL, which presents the obvious problems. Does anyone
know of a search engine that will go through SSL? Or, better yet, how
feasible is it to add this functionality to ht://dig? I'd like to
think we (we = company I work for) could potentially do this, although
I may be dreaming. In any event, all info is appreciated....
Brian
PS. These sites can't be non-SSL long enough to just index, we're
talking about .mil sites, and these folks are *very* headstrong
about this :-(
============================================================================
Brian K. Justice Software Engineer
Raytheon Systems Company email: bjustice@fallschurch.esys.com
7700 Arlington Blvd., M/S N102 phone: (703) 560-5000 x 2840
Falls Church, VA 22046-1572 BGPHES lab: (703) 560-5000 x 4395
----------------------------------------------------------------------------
#include <raytheon/policy/95-1002-110>
============================================================================
---------------------------------------------------------------------- | http://www.htdig.org/mail/1998/11/0097.html | CC-MAIN-2015-32 | refinedweb | 192 | 72.97 |
Sass Mixin and Media Merging
If you are not very familiar with Sass, you might not be aware that Sass enhances media queries (actually the
@media directive) to provide extra interesting features. One of which is called (or rather often referred to as) media merging.
Before explaining to you what media merging is, did you know that the CSS specifications on Media Queries actually allow media queries to be nested? Some browsers like Firefox, Chrome and Opera support it; some other like Safari and Internet Explorer currently do not.
Because the browser support is not ideal, Sass kicks in and merges nested media queries into a single media condition. For instance, consider this code:
@media (min-width: 42em) { @media (max-width: 1337px) { .foo { color: red; } } }
This will be compiled as:
@media (min-width: 42em) and (max-width: 1337px) { .foo { color: red; } }
Pretty handy, isn’t it? This is what is called media merging. When nested media queries are merged into a single statement.
What do we want? Media queries!
Now that I have done with the introduction, let me get to the point. The other day, I was playing with this idea. Basically, I wanted to build a very simply mixin that takes a map of queries as input, and merge them into a single condition in a
@media directive as an output.
Coming back to the previous example, I would like to write something like this:
@mixin media($queries) { .. } .foo { @include media((min-width: 42em, max-width: 1337px)) { color: red; } }
And when compiling, having the same result as seen in the CSS snippet above. Now, on the top of my head I can think of at least two ways of building it. Let’s tackle the ugly one first.
The ugly version
The most straight-forward idea would be to build a string out of our map. We iterate over the map, and for each new key/value pair, we concatenate them into the result string, separating pairs with the
and keyword.
/// Media query merger (the ugly version) /// Create a single media condition out of a map of queries /// @param {Map} $queries - Map of media queries @mixin media($queries) { $media-condition: '; // Loop over the key/value pairs in $queries @each $key, $value in $queries { // Create the current media query $media-query: '(' + $key + ': ' + $value + ')'; // Append it to the media condition $media-condition: $media-condition + $media-query; // If pair is not the last in $queries, add a `and` keyword @if index(map-keys($queries), $key) != length($queries) { $media-condition: $media-condition + ' and '; } } // Output the content in the media condition @media #{$media} { @content; } }
Okay, it’s not that ugly. It does the job fine, but you have to admit that this is not very elegant, is it?
The elegant way
I don’t feel very comfortable manipulating strings when Sass provides such an elegant way to to deal with media queries. There surely is a better way to do this. And then it stroke me: recursion. According to the free dictionary, recursion is:
A method of defining a sequence of objects, such as an expression, function, or set, where some number of initial objects are given and each successive object is defined in terms of the preceding objects. The Fibonacci sequence is defined by recursion.
That’s a bit tough. If we put this very simply, recursion is a mechanism where a function calls itself over and over again with different arguments until a certain point. A practical example of a function using recursion in JavaScript would be:
function factorial(num) { if (num < 0) return -1; else if (num == 0) return 1; else return (num * factorial(num - 1)); }
As you can see, the function calls itself until the
num variable gets lesser than
1, by decreasing it by
1 at every run.
Why am I telling you this? I figured out we could use recursion to build our media condition using Sass media merging. What if we make the mixin output a media for the first query in the map, then call itself passing the map without this query, until there is no query left in the map? Let’s try it, and since it might be a bit complex, we’ll go step by step.
First, we now that if our map contains no (more) query, we simply output the content. What don’t we start with this?
@mixin media($queries) { @if length($queries) == 0 { @content; } @else { // ... } }
Now, we want to output a media block for the first media query in the map. To get the first key of a map, we can use
nth(..) and
map-keys(..) functions.
$first-key: nth(map-keys($queries), 1); @media ($first-key: map-get($queries, $first-key)) { // ... }
So far, so good. Now, we only need to make the mixin call itself although we don’t want to pass it the same
$queries map or we will face an infinite loop. We need to pass it
$queries after having removed the first key/value pair. Thankfully, there is the
map-remove(..) function for this.
$queries: map-remove($queries, $first-key); @include media($queries) { @content; }
Now the whole mixin:
/// Media query merger /// Create a single media condition out of a map of queries /// @param {Map} $queries - Map of media queries @mixin media($queries) { @if length($queries) == 0 { @content; } @else { $first-key: nth(map-keys($queries), 1); @media ($first-key: map-get($queries, $first-key)) { $queries: map-remove($queries, $first-key); @include media($queries) { @content; } } } }
Going further
In a previous article, we saw a couple of different ways to manage responsive breakpoints in Sass. The last version used a mixin that looks like this:
/// Breakpoints map /// @type Map $breakpoints: ( 'small': (min-width: 767px), 'medium': (min-width: 992px), 'large': (min-width: 1200px), ); /// Responsive breakpoint manager /// @param {String} $breakpoint - Breakpoint /// @requires $breakpoints @mixin respond-to($breakpoint) { $media: map-get($breakpoints, $breakpoint); @if not $media { @error "No query could be retrieved from `#{$breakpoint}`. " + "Please make sure it is defined in `$breakpoints` map."; } @media #{inspect($media)} { @content; } }
This mixin works like a charm but it does not support multiple-queries conditions such as
(min-width: 42em) and (max-width: 1337px) because it relies on the
inspect(..) function which does nothing more than print the Sass representation of the value.
So, on one hand we have a breakpoint manager which picks from a global map of breakpoints and handle error messages and on the other with have a breakpoint manager which allow the use of multiple-queries conditions. The choice is hard.
Or is it?
By slightly tweaking the
respond-to(..) mixin, we can make it include the
media(..) mixin instead of printing a
@media directive itself. Then, we have the best of both worlds.
@mixin respond-to($breakpoint) { // Get the query map for $breakpoints map $queries: map-get($breakpoints, $breakpoint); // If there is no query called $breakpoint in map, throw an error @if not $queries { @error "No value could be retrieved from `#{$breakpoint}`. " + "Please make sure it is defined in `$breakpoints` map."; } // Include the media mixin with $queries @include media($queries) { @content; } }
The best thing is, if you already use this mixin, you can totally include the multi-queries feature by tweaking
respond-to(..) and adding
media(..) because the API does not change at all:
respond-to(..) still needs a breakpoint name to work, the same as before.
Final thoughts
I must say I find this very exciting because it is the first time I have found a good use-case for both nested media queries and mixin recursion. While it is possible to skip this and simply build a string as we’ve seen with our first version, it sure is more elegant and interesting to tackle it with a recursive mixin. I hope you enjoyed it! The final example before leaving:
// _variables.scss $breakpoints: ( 'small': (min-width: 767px), 'small-portrait': (min-width: 767px, orientation: portrait), 'medium': (min-width: 992px), 'large': (min-width: 1200px), ); // _mixins.scss @mixin media($queries) { .. } @mixin respond-to($breakpoint) { .. } // _component.scss .foo { @include respond-to('small-portrait') { color: red; } }
Yielding the following CSS:
@media (min-width: 767px) and (orientation: portrait) { .foo { color: red; } } | https://www.sitepoint.com/sass-mixin-media-merging/?utm_source=sitepoint&utm_medium=articletile&utm_campaign=likes&utm_term=html-css | CC-MAIN-2020-10 | refinedweb | 1,347 | 62.38 |
How to setup Time Time-based RoutingImplementation Code Step Integration for Time-based routingHow does the above code work for Time-based Routing?
Understanding Time-based Routing
Consider, a user has requested to chat with an agent. According to the Time-based Routing algorithm, it would first check if the user's request falls in the time range when the agents are online.
You can add a condition, depending on your agents' working hours. If the user's request falls in working hours, the bot would direct the chat to the agent, else it would respond with "agent is offline". request for chatting with an agent.
Code Step Integration for Time-based routing
import json import logging import pytz from datetime import datetime from datetime import time logger = logging.getLogger() logger.setLevel(logging.DEBUG) def main(event, context): body = json.loads(event['body']) # set the start and end time startTime="09:00 AM" initialTime=datetime.strptime(startTime, '%I:%M %p') endTime="06:00 PM" finalTime=datetime.strptime(endTime, '%I:%M %p') # check the actual time present = datetime.now(pytz.timezone('America/New_York')) # Mention the time zone here present_time =present.strftime('%I:%M %p') final_present_time=datetime.strptime(present_time,'%I:%M %p') # condition to route the user if initialTime<= final_present_time <=finalTime: status = "agent_online" else: status = "agent_offline" final_response = { 'status': status } logger.info(f"Final Response Logged is {final_response}") response = {'statusCode': 200, 'body': json.dumps(final_response), 'headers': {'Content-Type': 'application/json'}} return response
How does the above code work for Time-based Routing?
The above code uses two main libraries of Python:
pytz(python timezone)
Datetime
The datetime library here uses a method called strptime, that checks the user’s actual time. By actual time, it means that it captures the system’s time.
When the user asks to chat with an agent, the algorithm would initially check the user's system time and would record it.
Also, a Start time, and an End time is defined in the code.
startTime="09:00 AM"
initialTime=datetime.strptime(startTime, '%I:%M %p')
endTime="06:00 PM"
finalTime=datetime.strptime(endTime, '%I:%M %p')
Here, as you can see, the start time is defined as 09:00 AM, whereas the End time is defined as 06:00 PM, which is their working hours.
Also, here initialTime and finalTime function are recording the time, in the string format.
The next would be pytz.timezone, where the code would define the timezone in the city that is mentioned.
In this case, America/New York has been entered, so this part of the code would ideally record the timezone details in New York, America, irrespective of what time it is.
present = datetime.now(pytz.timezone('America/New_York'))
The next function here would record the present time in New York. It will store this data for further evaluations. The time would be recorded in the string format here.
present_time = present.strftime('%I:%M %p')
Final_present_time = datetime.strptime(present_time,'%I:%M %p')
Here, it also records the Final present time. It would take the time data from the above function and would parse it into the format, which is mentioned in the brackets.
In this case: %I: %M: %p
There is a conditional loop that has been added in the code. It is as follows:
if initialTime<= final_present_time <=finalTime:
status = "agent_online"
else:
status = "agent_offline"
final_response = {
'status': status
}
Here, the logic is quite simple, it says, if the initial time is less than or equal to the final present time, and if that is less than or equal to the final time, which is 06:00 PM, then the status of the agent would be agent_online.
If in any case, the above condition is not met, the status of the agent would be shown as agent_offline.
Let's take an example here, consider you are in London and it is 12:00 AM there, and you have put up a query on the bot. So in this case, considering the time zones, the time at New York would be 07:00 PM.
In the above scenario, your time clearly doesn’t match the time constraint mentioned, which is 09:00 AM to 06:00 PM, which is why you would receive an agent status to be agent_offline. | https://docs.haptik.ai/en_US/how-to-setup-time-based-routing-for-smart-agent-chat | CC-MAIN-2022-27 | refinedweb | 705 | 63.9 |
Week 1: Introduction to the Course. What is IPE? Why do we study it? Issues and
leading approaches. Major theoretical perspectives in the IPE. Liberalism, realism and
Marxism (and their neo- versions).
Week 4: Bretton Wood Institutions and their impact on global economy. Design and
politics of the international trade regime. WTO and Challenges. Pressing Issues for
Poor Countries. EU and the WTO: Conflicts and conformity.
Week 7: State-centered approach and its pitfalls. Free trade versus protectionism
INTRODUCTION: INTERNATIONAL POLITICAL ECONOMY
The world economy is globalized, which means that countries are interdependent, connected
and that they share products (their design, production and sell). When we have an economic
exchange, it usually turns out to have losers and winners (if Apple sells more, Samsung sells
less and vice versa; if you increase tariffs on a product, international companies sell less –
national companies that produce steel benefit). This, many times, has international
consequences: after the steel tariffs, the European Union and Japan retaliated by raising their
own and investigating the USA in the WTO. Sometimes these situations are easier to see than
others. Global economic forces also determine our career opportunities (before you could be
employed in local textiles, now it’s easier to have technological job opportunities).
LESSON 1: INTRODUCTION TO IPE
WHAT IS IPE?
2. The products we probably consume are as likely to come from a distant country as from
Spain.
3. Global economic forces play a large role in determining many of our career opportunities
The opportunities available are far different than 30 years ago.
4. International Political Economy (IPE) studies how politics shape developments in the global
economy and how the global economy shapes politics.
5. It focuses on the enduring political battle between the winners and losers from global
economic exchange.
• Global economic exchange raises the income of some people and lowers the income of
others.
The winners seek deeper links with the global economy in order to extend and
consolidate their gains.
The loser try to erect barriers between the global and national economies in order
to minimize or even reverse their loses.
• To understand how the political battle between the winners and losers of global economic
exchange shapes the economic policies that government adopt.
Thus, we need to analyze the actors’ interests in the global economy. In order to do
that, we need to analyze the four issue areas of International Political Economy taking into
account that they are intertwined and we must connect them for further analysis:
1. International Trade System: there are 164 members in the World Trade Organization
(WTO), which is in the center of any international exchange. This institution has been
working in a lot of areas since it was created and it punishes countries that don’t use
adequate measures. It also studies the creation of the measures taken to improve the
trade among nations. However, it has been diminished by regional agreements
between countries that give preferential access to markets to their members (such as
the NAFTA).
2. International Monetary System (IMF): it facilitates transactions between countries (for
example, from dollars to yens and vice versa). Tt has been questioned lately because
austerity measures sometimes didn’t work as predicted: they didn’t bring the wealth
that they were supposed to, and this creates a slowing or collapse of the global
economy. Thus, the IMF doesn’t have the power that it used to. In this class, we are
going to study the currencies and exchange rate system. To give an overview: when
you devaluate your currency, exports are cheaper and you can sell more, and thus it
can be a way to face deficit. The IMF had more efficiency in the 50s and 60s because
countries had a fixed exchange rate system pegged to the dollar. Right now, the EU
has a fixed exchange rate between its countries and floating with other countries (and
thus it is a mixed exchange rate). When it is floating, sometimes business is more
difficult (which value is certain currency going to have tomorrow?), but countries are
freer (have autonomy over their monetary decisions as they don’t depend on another
currency).
3. Multinational Corporations System: MNCs are corporations that operate in at least
two different countries (cross-border management and production) and act according
to different laws and measures in each country. Examples of them are Ford Motor
Company, General Electric and General Motors. There are more than 82,000 MNCs in
the world that employ +77 M people, and comprise 1/3 of world trade. Sometimes
governments give a lot of rights away to bring international corporations (because of
job creation usually and because Foreign Direst Investment is very important), but
sometimes corporations press governments for them to give them those rights (and
they are many times questioned because of their actions). Because of this, they are
very controversial. What is their economic impact?
4. Economic Development: it is tried to be achieved through a pool of trade policies that
sometimes come from social interest and sometimes from national interest. Asian and
American countries, during the 60s, 70s and 80s, tried the measures mentioned before
in order to achieve a raise of income through industrialization. Some succeeded with
import substitution (NICs from Asia) and some didn’t (Africa and South America). We,
as analysts, would like to know what strategies caused these differences in results. It is
important to highlight the development of China: it was supposed to be a communist
country (in autarky), but liberalization in the economy succeeded, and they turned
from an agricultural to an industrialized country. It grew very much at the beginning,
now it does so less (economies are cyclical, and it is easier to grow much when you
have a lot of room for improvement.).
Thus, as we know, the allocation of resources implies very difficult decisions. This is so
because resources are finite, which means we have to decide what to use them for, and these
decisions have consequences for welfare and distributions (there are better and worse choices
regarding these two areas).
• Explanatory studies: they are why-questions. What decisions do governments take related
to the economy and why?
• Evaluative studies: they assess the policy outcomes, judge them and make alternatives if
they are considered negative.
• Mercantilism: theory born in the 16th and 17th centuries, when Absolutism controlled
all countries. The main goal was for the national economy to be promoted: the state’s
accumulation wealth was the most important. They wanted a surplus on the balance
of payments (higher exports than imports), and thought that exploiting manufacturing
was the best choice because it would create more wealth. The state has a big role for
this school, as it is the one which has to control that the production is well-directed.
Modern mercantilists believe the same, but have substituted manufacturing for
computers and telecommunication for their choice of profit-industries.
• Liberalism: Adam Smith and others (like Ricardo, father of the term comparative
advantage) said that the individuals – and not the state – are the ones who should be
rich. They wanted to alter the government’s economic policy. They were against any
intromission of the state in the economy out of regulation, protection of
ownership/resources and correction of market failures. Each one produces the
products that cost less for them to produce and makes voluntary transactions in a
market-based economy.
• Marxism: the main book describing this theory is The Capital (Karl Marx, 1867), which
is a very complex book and a critique to capitalism. It basically states that the
difference between the surplus that the entrepreneurs earn and the one that the
workers earn is huge and only increases because capitalism is focused on never ending
production that ends up in the hands of elites. Thus, salaries for workers will only
decrease and decrease because of cost cutting (since profits are falling due to
decreasing marginal returns, the only source for cost-cutting are wages) until the clash
of classes takes place. After this clash and the revolution, a communist country will
arise. Before this clash, the state is an agent of capitalism controlled by a few firms
that has promoted colonial structures before World War II and less intensive but still
dominance structures after it. For Marxism, the state has to have a role that makes
workers earn more than they do under capitalism to have material independence.
The problems each view faces are: for Mercantilism, how to compete to attract and
maintain the desired industries; for Liberalism, although the market is harmonious, the state
needs to create a good framework for markets; and for Marxism, the problem to deal with is
the distributional conflict between labor and capital and also between industrialized and non-
industrialized economies.
Here we can see a table of the comparative of the three schools of thought:
1. Hegemonic stability theories (Keohane, Organski): the international system is more likely to
remain stable when a single nation-state is the dominant world power, or hegemon.
Based on this, we have two mechanisms through which interests are formed:
1. Material interests: they arise from our personal positions in the economy. In our previous
steel example, you will be for or against tariffs depending on where you work (in the steel or in
the car industry?). Where you work shapes what you prefer.
2. Ideas: they are mental models that give us beliefs about causes and effects in the economy.
That is, we can believe either in the comparative advantage model by Ricardo or in the infant
industry argument. What is true doesn’t matter: what powerful people believe does.
Based on these mechanisms, this approach examines political institutions to see how
these interests are shaped into policies. Political institutions pass the rules that create the
groups which make decisions (based on majority in democracies or in economic power in
international institutions). The non-compliance of these groups with the rules creates issues
for the system (especially in the international system, which has no enforcement mechanism).
LESSON 2: HISTORY AND GLOBALIZATION
CONCEPTS
FISCAL POLICY
Fiscal policy is concerned about spending, taxes and borrowing by the Central Bank
government. Keynes established that fiscal policy should not be tied to a rigid balanced
budget: it could be used to manage the economy and smooth out the business cycle of
expansion and recession. However, sometimes this creates inflation and deficit spending
problems because of the increase in spending and decrease in taxes.
MONETARY POLICY
Monetary policy consists on the efforts by the Central Bank to manage money supply
and interest rates. This is done through:
1. Open market operations: pumping or draining funds from the banking system. This
consists on either expansionary policy (the Central Bank buys bonds and thus puts
money on the system) or contractionary policy (the opposite occurs).
2. Managing the discount rate1: when the discount rate increases, so does the price of
money. This discourages borrowing and thus slows economic growth down. The goal
of this is to provide stability, face financial panics and control inflation.
EXCHANGE-RATE SYSTEM
The exchange rate is the price of a currency in terms of another. The foreign exchange
market is the market in which the world’s currencies are traded. Also, the exchange trade
system has a set of rules governing how much national currencies can appreciate and
depreciate in the foreign exchange market.
Governments use several ways to influence exchange rates. There are three types of
exchange rate systems:
1. Fixed exchange rates: it involves government intervention to keep the price of a currency
from moving up and down. The government establishes this fixed price of currency in terms of
some international standard (either gold or a stronger currency). They maintain this fixed price
by buying and selling the currency they are pegged to in the foreign exchange market.
Governments hold a stock of other countries’ currencies as foreign exchange reserves. This
prevents the currency from changing its value. This was the system before the First World War
and from 1958 to 1973.
3. Fixed but adjustable exchange rate: the national currency is largely pegged or fixed to a
major currency, but can be readjusted from time to time within a narrow interval. The periodic
adjustments are usually intended to improve the country's competitive position in the export
market.
The value of the money is sometimes controlled because it affects the price of goods and
services abroad and at the home market. Changing the prices of exports and imports affects
the nation’s overall balance of trade.
BALANCE OF PAYMENTS
2. Capital account: financial flows, that is, the capital that flows in and out of the economy.
The current and capital accounts must be mirror images of each other: if there is a
current account deficit, the country is importing more than it is exporting, and thus the
financial flows are incoming and we have a capital account surplus. On the opposite, if there is
a current account surplus, the country is exporting more than importing, and so it is sending
financial flows outside and it has a capital account deficit. This signals whether the country is a
debtor (first case) or a creditor (second case).
TRADE DEFICIT
We could decrease the value of the dollar (being that our domestic currency), which
would lower our export price, whose demand and volume would thus increase. Also, our
imports price would increase, and thus its demand and volume would decrease. These two
mechanisms combined would lower our trade deficit.
The world, before industrialization, had always been protectionist. Why did this
change? In the 19th century, the world economy looks a little like our own (before, trade was
managed by empires): there was an increase in trade of manufactured goods,
interdependence and participation. However, participation was not even.
BRITISH INDUSTRIALIZATION
In 1750, Great Britain had a big domestic market: they were productive in agriculture,
had a monetary economy, a lot of labor mobility and abundance of capital. When they applied
new techniques of production – which caused a sharp declines in cost and thus prices –, they
started to produce a lot more wool and cotton cloth. As their prices were so low, exports rose
from 1784 to 1814, where it ended up needing an open international economy.
This new technology was based on new machinery and new forms of organization.
Also, the large British military helped to retain their benefits. Thus, they started to want freer
trade: they were in need of supply of materials from other countries. Mercantilist barriers
seemed irrelevant and an obstacle to growth.
Thus, there was a free trade demand from manufacturers, who had an increasing
importance in Great Britain versus the agricultural producers, who wanted to keep their tariffs.
Free trade demands, supported by the claim that if Britain lowered their tariffs so would other
countries (which had had a raise on protectionism after 1815) and British exports would rise
again, caused the Repeal of the Corn Laws.
After this, other countries did lower their tariffs (in 1860, Britain and Franc signed the
Cobden- Chevalier Treaty to eliminate tariffs), and so the British traded food for manufactured
goods. They thus shaped the international economy through their unilateral freeing of trade.
From 1850 to 1875 there was an increase in trade. This was mainly caused by the
political unification of Germany, who wanted a big market and international influence.
Because of this, railroads were starting to be built all across Europe, which boosted progress in
Europe along with the increase in textile production of Germany and France and the
continuing growth of Great Britain.
The USA, Australia and New Zealand imported European manufactured goods and
exported food also to Europe. The multilateral division of labor based on geography that was
in place in Europe and Germany’s rising with the help of Great Britain also helped to increase
trade. More tariffs were lifted (for example, in the German Zollverein or in the USA).
Thus, interdependence also rose: there were more financial transactions, the gold
standard was in place and there was private international cooperation. However, there was a
problem: no international public cooperation to manage the financial and trade international
system. Speculation rose around the gold standard and British hegemony was put into
question.
Although Great Britain was still dominant, its relative importance was declining since
they couldn’t adapt to managerial capitalism and they had a small domestic market, without
economies of scale of benefits from the new technologies. Thus, they remained in the old
industries. However, London still retained its power with the gold standard. Let’s review this a
little better:
GOLD STANDARD
Under the gold standard, developed in the 1870s, the value of any currency is defined
as an equivalent to a certain quantity of gold at a fixed rate. Central Banks are committed to
change national currency at this fixed rate. Gold is used just as reserve value and exchange
ratio. In this system, the Pound was the world currency, and London was the financial centre
and liquidity provider, even when Great Britain was declining in importance.
They provided long-term price stability, stable exchange rates (which causes less
uncertainty in international trade and freer capital movements) and price-specie flow
mechanism (Hume’s very controversial Quantitative Theory of Money2).
2 M·V = P·Y, where M = money supply, V = velocity and it’s constant, P = Price and Y = GDP,
which is also constant.
The system functioned as
described at the left: gold
inflows and outflows
controlled economies.
DISADVANTAGES OF PAX BRITANNICA:
The Central Bank has to do continuous interventions to maintain the value of the
national currency (drops in gold reserves). Also, the money supply’s growth is insufficient to
suit economic growth needs, which causes deflation and stagnation. This harms debtors and
benefits creditors, which causes growing inequality and social unrest.
The gold standard was too tightening to face economic recessions (impossibility of
expanding monetary policy), and it needs social rest (no strikes against wage deflation), free
capital movements and no state intervention. This caused its collapse.
MONETARY TRILEMMA
The monetary trilemma states the impossibility of having at the same time monetary
sovereignty, capital mobility and fixed exchange rates.
This is so because if you have an exchange rate fixed and monetary autonomy (can
increase and decrease money supply), when you move your money supply up, capital will flow
to other countries because the interest rate returns will be higher there, and the country will
lose its monetary autonomy (depends entirely on other countries. Thus, you can either have
free capital mobility and exchange-rate management, free capital mobility and monetary
autonomy (letting exchange rates flow) or monetary autonomy and exchange-rate
management.
Since the gold standard implies the last two features, Central Banks lose monetary
policy as a tool to solve economic recessions.
The main problem from this period was the great interdependence and how it was
managed. It contributed to the depression (1873-1896) after financial panics, the effects of the
Civil War of the USA and the effects of the French reparation debt. This happened when there
was an oversupply of wheat, which decreased its price, and Europe raised tariffs again. This
made earnings fall and international trade to slow down.
Due to these financial crashes, national leaders see trade in mercantilist terms, as a
weapon in international competition. The ideas of mutual gains of free trade were retreated in
the years before 1913, when the WWI started after a military competition and the creation of
alliances.
Thus, there were three major impediments for international economic stability during
this period:
1. Nations failed, after the first world war, to manage domestic and international
economic systems. They could not find a way to move capital from surplus to deficit
countries and did not implement managerial capitalism.
2. The failure of the world’s largest economy, the USA, to accept a leadership role.
3. The ferocity of the downturn in the world after the 1929 crisis guaranteed a retreat to
autarky and protection as nations struggled to defend their domestic economies.
The USA helped the Allies during the war, for which they owed $10 billion. The USA
thus was a creditor, along with Japan. Europe was not competitive because their industries
were destroyed and their financial systems too. They had no gold standard and an oversupply
of money (and thus inflation). Moreover, the USA insisted on reparations to be payed as soon
as possible (while they raised tariffs, harming European imports), and so did France, imposing
an impossible task on Germany. The Pound’s return to the Gold Standard was artificial: Great
Britain could not meet their gold demands and they had no capital surplus to lend.
This combination of facts promoted that, after the 1929 crisis (having had already
restrictions on credit in 1928 by the USA that also harmed economies), the debt system
collapsed in 1931 and the payments were stopped. The economies entered a recession
marked by massive gold withdrawals and falling profits.
LESSON 3: POSTWAR INTERNATIONAL POLITICAL ECONOMY:
INSTITUTIONALIZATION AND MULTILATERALISM
We need to remember the monetary trilemma for this topic (see previous topic).
INTRODUCTION
The years following the Second World War produced epoch-changing changes in the
world economy: unprecedented prosperity, development of new international economic
institutions, explosion in world trade and an extraordinary expansion in international
cooperation.
This was possible because of the following reasons: the changing role of the USA form
the previous period, the cooperation between European countries, the threaten of Cold War
and MNCs.
MARSHALL PLAN
Because of the war, Europe is in a bad shape, not only regarding infrastructure but also
regarding the economic structure of the country, which is completely war-oriented. Moreover,
Europe is facing a short supply of basic resources like food. Thus, the USA’s policy will be
directed towards helping Europe once the countries within that continent have explained what
they exactly need.
The Bretton Woods System represented the first time that governments made
exchange rates a matter of international cooperation and regulation. The system pretended to
enjoy exchange-rate stability and domestic economic autonomy. These are its main
institutions:
This system was based on a fixed exchange rate that did not entail a loss of domestic
economic autonomy. However, it is important to stress the growing strength of labour unions,
who avoid falling output and rising unemployment. This poses a political constraint on
domestic adjustment.
At first, it was very difficult to implement Bretton Woods. Countries, at first, needed to
import foods and capital good in order to reconstruct their economy. The USA exported $ to
Europe in foreign aid through the Marshall Plans. The official price of gold was of $35 an
ounce.
This was based on a balance of payment deficit plan from the US, since more dollars
flowed out from the US than in. At the end, by 1959, European governments had accumulated
sufficient dollar and gold reserves to accept fully convertible currencies.
Thus, the dollar became the system’s primary reserve asset: it was used in
international payments, foreign exchange reserves and to intervene in the foreign exchange
market. Thus, the stability depended on the ability of the US to exchange dollars for gold at
$35 an ounce.
In 1957, some European countries signed the Treaty of Rome and created the
European Economic Community. This was promoted by the USA and France, who wanted
international market power and ability to control Germany.
After this, the Customs Union and the European Coal and Steel Community were
created as well, which tried to reduce tariffs and restrictions for trade. This promoted a lot of
growth, and after that Europe was able to accept full currency convertibility and close the
payments gap and peg their currency to the dollar.
Having the USA huge deficits because of all of their military spending in the Cold War
and their expansionary policies of military Keynesianism and reducing taxes. Thus, at the end,
the international capital market exceeded that of the USA by a lot.
DOLLAR GLUT
During the 60’s there is a dollar glut as a consequence of balance of payment deficit
(expansionary policy) because of what we have stated before:
The consequence of the dollar overhang was the decreased confidence on the US
government and dollar. This is so because the quantity of gold held by the USA was lower than
the dollar held by foreign countries. Thus, foreign claims on American gold grew larger than
the amount of gold the US held. In 1971, speculative attacks began to occur and gold
withdrawals took place.
3. Expand economic activity in the rest of the world in order to increase American exports.
However, the US government was unwilling to adopt any of these measures, and
instead it was paralyzed by political conflict. They tried other policies, such as getting the EEC
to lower their trade barriers or creating the stabilization fund. However, these policies did not
help enough.
In 1971, the USA had had several years of economic deterioration, and a crisis caused
the USA to suspend the gold convertibility, raise tariffs and depreciate the dollar. Other
countries started to reject the Bretton Woods System. 1972 was a stable year, but again in
1973, a massive crisis brought the system down, and most advanced countries abandoned
their fixed exchange rates and floated their currencies. This marks the end of the US
hegemony.
The oil situation also harmed the USA. US oil production was stagnated, and the wars
in the Middle East together with US barriers restricted oil production. However, oil demand
was ever-rising, and thus at some point oil prices rose a lot. This intensified the crisis.
CONCLUSIONS
International consumption and production has increased a lot because of the rapid and
long growth in world trade. Global markets rest on political structures such as the GATT and
the WTO. The World Trade Organization is an institution that negotiates, enforces and revises
trade rules after their establishment in 1947. It has 164 members nowadays but it still is a
small institution (635 staff and $170 Million as budget). It is at the center of the trade system
as it provides a forum for trade negotiations/administrators, it administers he trade
agreements that governments conclude and it provides a mechanism through which
governments can resolve trade disputes.
MARKET LIBERALISM
It is the economic rationale that justifies its existence. It states that opening up trade
entails an increase in standards of living for everyone. When trade is free (absence of barriers),
the gains from trade are higher.
NON-DISCRIMINATION
This principle ensures that each WTO member faces identical opportunities to trade
with other WTO members. Within the WTO, there are two forms of non-discrimination:
1. Most-favored nation (MFN): prohibits governments from using trade policies to provide
special advantages to some countries and not to others (article 1 of GATT). There are two
exceptions to this: trade regional agreements (RTAs, such as the NAFTA or EU) and General
System of Preferences (GSP, lower tariffs for developing countries).
2. National Treatment: prohibits governments from using taxes, regulations and other
domestic policies to provide an advantage to domestic firms at the expense of foreign firms.
You need to treat domestic and foreign versions of the same product identically once the
product is inside the market.
Also, the WTO is based on many rules. There are hundreds of them, the first ones
established in 1947. They can be proscriptive (prohibition against government discrimination)
or prescriptive (requirement to protect intellectual property). Also, right now, governments
have concluded 60 distinct agreements.
WTO DECISION-MAKING
Through 70 years of functioning, the WTO and ITS have experienced their critics,
although their core principles have remained stable. Now, the WTO faces new challenges that
may affect these principles.
EMERGENCE OF DEVELOPING COUNTRIES
The power for developing countries has been growing since 1985 as more of them
joined the WTO. It is difficult to gain consensus with different levels of development and
interests, but since the 80s a new bloc of emerging economies (Brazil, China and India at the
leadership) has been very influential.
Their topics into the agenda are the liberalization of agriculture and promoting
development policies. The cooperation on these issues they have carried out has been
institutionalized in the Group of 20. Current bargaining brings together governments
representing countries with very different economic structures: high technology, labor-
intensive manufactured goods and agriculture.
Therefore, at the WTO, since these countries are more important, new policies will
entail liberalization of sectors – such as agriculture in the EU or technology in developing
countries – that will not survive international competition.
NGOs are a powerful force outside the organization as they press for answer on
consumer and environmental issues. During the last years, NGOs have emerged trying to
influence the organization. They have three main areas of concern:
2. Consumers.
3. Environmental interests.
NGO’s critic the WTO saying that rules are rigged in favor of the rich through tariffs
and other barriers: domestic subsidies (agricultural) benefit the rich and increase poverty and
inequality in developing countries. Oxfam stated that if developing countries increased their
exports just 5% this would generate 7 times as much as they receive in aid ($135 billion).
Although trade is a powerful source of wealth, the poor are being left behind.
Also, they discriminate on patents and public health, since they are privatized and
medicines are too expensive for them to be expanded in these countries. Last, Foreign Direct
Investment (FDI) is questioned: they entail reduced capacity for research and development in
developing countries, growing dependence on technology imports for them as well, erosion of
employment standards (due to TNCs many times), real financial transfers made have been
reduced to attract investors and tax avoidance or profit repatriation.
Since the 90s, NGOs have complained because the balance struck by WTO rules is too
favorable to business and insufficiently protective of consumer and environmental interests.
The WTO decision- making is a process where producer interests are heavily represented and
consumer interest almost excluded. Thus, this process could be changed.
Regional Trade Agreements (RTAs) are trade agreements between two or more
countries, usually located in the same region of the world, in which each country offers
preferential market access to others. They take two basic forms:
1. Free trade areas: they reduce barriers among the countries that are in the agreement
but keep their own specific barriers for countries outside their agreement. An example
is the NAFTA.
2. Custom unions: they reduce/eliminate barriers among the countries within the
agreement and establish a common barrier policy for countries outside it. An example
is the EU.
RTAs are inherently discriminatory, but they are consistent with the article 24 of GATT
and allowed at the WTO. However, there are some worries relating to them: they are rapidly
proliferating (why are they doing RTAs and not simple negotiating within the WTO?), more
than half are bilateral and they are densely concentrated in Europe and the Mediterranean
region.
The EU and its member states became original member of WTO. This custom union has
a common commercial policy under article 113 EC (restricted to trade policy), confirmed by ECJ
(Opinion 1/94). However, they still have competences in services and intellectual property
rights (as confirmed by ECJ). | https://www.scribd.com/document/390962553/LESSONS-1-4 | CC-MAIN-2019-35 | refinedweb | 5,209 | 52.19 |
This walkthrough is a transcript of the Row Scrolling video available on the DevExpress YouTube Channel.
In this tutorial, you will learn about the various vertical scrolling modes in a grid View, including the following:
The tutorial will also describe the API that you can use to scroll the View or respond to end-user scrolling operations.
When you scroll the View vertically, you can notice how the first row in the View is always fully displayed. In other words, the default scrolling step is one row. The same happens when you group data. The View is scrolled one row at a time.
To enable pixel scrolling, access the grid View's properties, expand GridView.OptionsBehavior and set GridOptionsBehavior.AllowPixelScrolling to true.
Run the application now to see that scrolling is now smooth thus allowing for rows to be partially visible. The same happens with the grouped View.
Now notice that if you collapse all group rows, the vertical scrollbar automatically disappears as it's no longer needed. The behavior is also customizable. Set the View's GridView.VertScrollVisibility property to ScrollVisibility.Always to reserve space for the scrollbar even if scrolling is not required.
This is a classic scrollbar representation and many modern applications use a touch-enabled scrollbar version.
To change the scrollbar style, go to code, make sure to reference the XtraEditors namespace and then set the WindowsFormsSettings.ScrollUIMode option to ScrollUIMode.Touch in the Form’s constructor.
using DevExpress.XtraEditors;
public Form1() {
WindowsFormsSettings.ScrollUIMode = ScrollUIMode.Touch;
// ...
}
This mode implies that you scroll using gestures, and the scrollbar simply indicates the current position and then automatically fades out. If you are using the mouse, it will also appear when the pointer moves over the grid so you can scroll the grid by dragging the scrollbar thumb too.
The next thing to try is postponed vertical scrolling. First, disable pixel scrolling and then remove the ScrollStyleFlags.LiveVertScroll flag from the GridView.ScrollStyle property value.
In this mode, the View is updated only after you have released the scrollbar thumb. While you are still scrolling, a tooltip indicates the target position. If the View is grouped, tooltips will display group row values along with data row indexes.
In the grid View’s properties, set the GridView.VertScrollTipFieldName property to Name.
Now the data row tooltip will show values from the specified field instead of record indexes.
Now take a look at vertical scrolling API. The code will update the status bar with the current price range every time you scroll the View.
Return to design time, access grid View events and handle the GridView.TopRowChanged event, which fires when the View is scrolled vertically. The handler simply calls the UpdateStatus method, which is also called in Form’s Load handler.
The method first obtains the top visible row’s handle by converting from the current top visible index. Then, use this row handle as a parameter when obtaining the price in that top row. Similarly, obtain the price value in the bottom row. To get the bottom row’s handle, call a separate method.
In that method, enumerate visible indexes starting with the top visible index and stop the cycle if the index goes up to the GridView.RowCount value indicating that you’ve reached the last visible row. In the cycle body, use the GridView.IsRowVisible method to determine whether the currently processed row is within the grid’s visible area. Quit the enumeration if you reach a row that’s below the current scroll range. The row handle where the cycle stopped specifies the last visible row and thus it is the method’s return value.
Finally, in the UpdateStatus method change the scrollbar text to display the two price values – form the top and bottom rows.
private void UpdateStatus() {
int topRowHandle = gridView1.GetVisibleRowHandle(gridView1.TopRowIndex);
double topRowPrice = Convert.ToDouble(gridView1.GetRowCellValue(topRowHandle, colPrice));
double bottomRowPrice = Convert.ToDouble(gridView1.GetRowCellValue(getLastVisibleRowHandle(), colPrice));
siStatus.Caption = string.Format("Showing prices: {0:c0} - {1:C0}", topRowPrice, bottomRowPrice);
}
private void gridView1_TopRowChanged(object sender, EventArgs e) {
UpdateStatus();
}
private int getLastVisibleRowHandle() {
int rowHandle = 0;
for (int visibleIndex = gridView1.TopRowIndex + 1; visibleIndex < gridView1.RowCount; visibleIndex++) {
rowHandle = gridView1.GetVisibleRowHandle(visibleIndex);
if (gridView1.IsRowVisible(rowHandle) == RowVisibleState.Hidden)
break;
}
return rowHandle - 1;
}
Run the application. Enable the live scrolling mode again to see status bar text change while you’re scrolling.
Now create three button titles Make Row Visible, Move Focus and Change Top Row to explore different ways of scrolling the view in code.
The first handler will use the GridView.MakeRowVisible method to scroll to the last data row in the View. The second simply sets focus to the same row using the ColumnView.FocusedRowHandle property. The third handler uses the GridView.TopRowIndex property to try and scroll the View to the last visible row.
private void barButtonMakeRowVisible_ItemClick(object sender, ItemClickEventArgs e) {
gridView1.MakeRowVisible(gridView1.DataRowCount - 1);
}
private void barButtonMoveFocus_ItemClick(object sender, ItemClickEventArgs e) {
gridView1.FocusedRowHandle = gridView1.DataRowCount - 1;
}
private void barButtonTopRow_ItemClick(object sender, ItemClickEventArgs e) {
gridView1.TopRowIndex = gridView1.RowCount;
}
When you run the application you’ll see that all three methods will scroll the View to the bottom. | https://documentation.devexpress.com/WindowsForms/114731/Controls-and-Libraries/Data-Grid/Grid-View/Scrolling/Tutorial-Row-Scrolling | CC-MAIN-2017-39 | refinedweb | 854 | 51.44 |
From recent discussions on leo-editor-group I have been inspired to write in more details and try to better explain my point of view on efficient prototyping. Author of Leo (Edward K. Ream) is a man whose energy and dedication to this project, attracted many people from everywhere, and formed very pleasant, active and healthy web community. This community nourished and cherished by its founder is very interesting place to be, especially if you are in search for an inspiration.
Although there are times when I can’t take an active part in discussions, I am reading it very often. Few times I tried to share some ideas about programming on this forum and some of them were accepted. But in some cases I could not make my point clear. Generally I find very difficult to clearly explain coding ideas in plain English. More than once it turned out that just showing code does much better job in an idea explanation than writing thousand words.
In recent discussion I wrote:
Above all, I would suggest for any prototyping purposes to avoid classes as much as possible.
And Edward replied:
I could not possibly agree less with this statement.
At the same time code snippets editor in Google groups started to act strangely. It was impossible (or very hard) to copy and paste code examples. So, I have decided to use pelican tool to write and publish some articles about coding, software engineering with hopefully pretty formated code examples and maybe few diagrams.
Example problem
I didn’t want to insist on the same problem we were discussing recently. It would be easier, I thought, to show my ideas on a problem that is not currently in focus. I remember reading dozen times how Edward was blaming his own code. Googling for “complex” in leo-editor-group, gave me some ideas what to choose for example problem.
Among several other threads was this one , about
c.importCommands that hopefuly would provide a good example. Without looking in actual code, and without any preparation, I am guessing that even now (after cleaning and simplifying performed about nine months ago), this part of code can be substantially simpler. It could, however, happen that code turns out to be already in simplest possible form. In that case, I will have to look for some other domain to find example.
Let’s begin
First let us check how these import commands work now. A few years ago I have tried to import bunch of javascript files using at-auto but the results of that import were poor and I had to import those files manually. Those were the files of RPG game exported by RPG Maker MV. The largest one is about 300k and total size is about 1M.
Here is a script to import largest file rpg_objects.js and messure time spent in
createOutline method of
c.importCommands.
import timeit fileName = '/tmp/rpg_objects.js' p1 = p.insertAfter() p1.h = '@auto ' + fileName def doit(): c.importCommands.createOutline(fileName, parent=p1.copy()) t = timeit.timeit(doit, number=1) p1.doDelete(p) g.es('ok', t, 's') c.redraw()
It takes about 30s for my computer to import this file. Geany opens this file almost instantaneously. It has 8549 lines. It is not only slow import that bothers me, but also after importing this file, Leo has become unresponsive. For each mouse click or key press it was blocked for more than 10s. I could barely delete imported node.
After this initial experiment, I am almost sure that there is a bug somewhere in Leo. It is really hard to believe that any bug free code would be so slow. But, even if there is a bug that causes 25s of total processing time, I believe that there must be a way to have a better import done in less than 2s. After all executing this file using
nodejs interpreter is blazingly fast. Nodejs has to parse file before execution and even if the nodejs parser is written in C/C++, Python should not be too much slower than that. Hopefully, I will prove it.
First impressions
Before I even start prototyping, while I was looking for
createOutline method to test it, I have found that code is like spiders web. When user executes command to read at-auto file(s), Leo starts to collect pieces of information from several objects jumping back and forth before it finally gets to the importing code. Leo application
g.app contains
atAutoDict, which is populated in
LoadManager, and
atFileCommands.readOneAtAutoNode calls
createOutline in
importCommands. On the other hand,
importCommands in some places calls
readOneAtAutoNode from
atFileCommands. Finally inside
createOutline parsing of file is dispatched to unknown class defined in some leo.plugins.importers.* submodule. The only way you can find which class is responsible for parsing your file, is to open and read those modules searching for
javascript or
js. Luckily, modules are named mostly by language they import. But what if any of those modules contain parser/scanner for two or more languages? Or if you are looking for
less importer which is subtype of
css?
Terrifying! But, enough complains, let’s concentrate on solving problem! There must be a better way!
Initial idea
My initial idea (which may be totally abandoned in future work), is to develop a function that takes as argument position and perhaps some configuration dictionary. The body of given position should contain the source code. This function should return a generator of tuples. Each tuple will have a line of source code, headline of new node when this line is first line of a new node and level of new node relative to input position.
The other part of soultion would be to have a function which iterates generator returned by the previous function and build outline populating bodies with lines from generator. This function can be universal for all types of import.
def outline_generator(p, conf): lines = tuple(enumerate(p.b.splitlines(False))) for line, head, level in process_lines(lines): yield line, head, level # head can be False, or str headline for new node # level can be: # +1 when new node should be child of current node, # -1 if new node should be added as a sibling of # current node parent # 0 when new node should be added as a sibling of # current node def build_outline(p, it): stack = [p] p1 = p.copy() buf = [] for line, head, level in it: if not head: buf.append(line) else: p1.b = '\n'.join(buf) buf = [line] if level == 0: p1 = stack[-1].insertAsLastChild() elif level == 1: stack.append(p1) p1 = p1.insertAsLastChild() elif level == -1: stack.pop() p1 = stack[-1].insertAsLastChild() else: # this should never happen raise ValueError('unsupported level value %r'%level) p1.h = head p1.b = '\n'.join(buf)
In production build_outline should probably operate on vnodes instead of positions. Most likely it should build tuple like from sqlite3 table and use a function from fileCommands to build subtree.
Processing budget
Better import means more processing, which requires more time. If we want it to be fast enough there is an upper limit of processing we can afford. There maybe several strategies that we can use for dividing source code into blocks. Ideally, import would try them all and compare results using some score function defined by the user preferences, searching for the one with the highest score. However, it may be that such a clever import would require too much time. In that case solution maybe to make every strategy as fast as possible and let user see the preview results of each strategy and manually choose one. Let’s try to find out how much processing we can afford.
import timeit import re def get_source(): '''Read and return contents of largest js file''' return open('/tmp/rpg_objects.js', 'rt').read() patterns = [ re.compile(r'\s*((\w+)(\.(\w+))*)\s*\('), re.compile(r'\{([^}]+)\}'), re.compile(r'(\d+)(\s*,\s*\d+)*'), ] def dummy_processing(): src = get_source() lines = [] findex = 0 for i, line in enumerate(src.splitlines(False)): ms = [] for pat in patterns: ms.append(tuple(m for m in pat.finditer(line))) lines.append((i, findex, line, tuple(ms))) findex += len(line) + 1 def test(f, num): t = timeit.timeit(f, number=num) * 1000 / num g.es('average %5.1f ms'%t) c.frame.log.selectTab('Log') c.frame.log.clearLog() test(dummy_processing, 100)
To run this script it is necessary to have javascript file
rpg_objects.js in
/tmp/ folder (here you can find all javascript files. Windows users should choose similar path suitable for their OS. On my machine this script runs for about 40s.
average 408.6 ms
Conclusion: it is most likely possible to import this file in less than half a second. In its current version
leoImport.ImportCommands, Leo needs more than 30s to import this file and becomes unresponsive afterwards. | https://computingart.net/functional-programming-for-prototyping.html | CC-MAIN-2021-49 | refinedweb | 1,481 | 66.23 |
On 05/23/2013 01:18 AM, Claudio Fontana wrote: > +static inline void patch_reloc(uint8_t *code_ptr, int type, > + tcg_target_long value, tcg_target_long addend) > +{ > + switch (type) { > + case R_AARCH64_JUMP26: > + case R_AARCH64_CALL26: > + reloc_pc26(code_ptr, value); > + break; > + case R_AARCH64_CONDBR19: > + reloc_pc19(code_ptr, value); > + break; The addend operand may always be zero atm, but honor it anyway. > +static inline void tcg_out_ldst_9(TCGContext *s, > + enum aarch64_ldst_op_data op_data, > + enum aarch64_ldst_op_type op_type, > + int rd, int rn, tcg_target_long offset) Universally, use TCGReg for arguments that must be registers. > +static inline void tcg_out_movi32(TCGContext *s, int ext, int rd, > + uint32_t value) > +{ > + uint32_t half, base, movk = 0; > + if (!value) { > + tcg_out_movr(s, ext, rd, TCG_REG_XZR); > + return; > + } No real need to special case zero; it's just an extra test slowing down the compiler. > + /* construct halfwords of the immediate with MOVZ with LSL */ > + /* using MOVZ 0x52800000 | extended reg.. */ > + base = ext ? 0xd2800000 : 0x52800000; Why is ext an argument to movi32? Don't we know just because of the name that we only case about 32-bit data? And thus you should always be writing to the Wn registers, which automatically zero the high bits of the Xn register? Although honestly, if you wanted to keep "ext", you could just merge the two movi routines. For most tcg targets that's what we already do -- the arm port from whence you copied this is the outlier, because it wanted to add a condition argument. > +/* solve the whole ldst problem */ > +static inline void tcg_out_ldst(TCGContext *s, enum aarch64_ldst_op_data > data, > + enum aarch64_ldst_op_type type, > + int rd, int rn, tcg_target_long offset) > +{ > + if (offset > -256 && offset < 256) { > + tcg_out_ldst_9(s, data, type, rd, rn, offset); Ouch, that's not much room. You'll overflow that regularly getting to the various register slots in env. You really are going to want to be able to make use of the scaled 12-bit offset. That said, this is certainly ok for now. > +/* mov alias implemented with add immediate, useful to move to/from SP */ > +static inline void tcg_out_movr_sp(TCGContext *s, int ext, int rd, int rn) > +{ > + /* using ADD 0x11000000 | (ext) | rn << 5 | rd */ > + unsigned int base = ext ? 0x91000000 : 0x11000000; > + tcg_out32(s, base | rn << 5 | rd); > +} Any reason not to just make this the move register function? That is, assuming there's a real reason you set up that frame pointer... It's starting to look like "ext" could be set to 0x80000000 (or really a symbolic alias of that) and written as x | ext everwhere, instead of conditionals. At least in most cases. > + /* all arguments passed via registers */ > + tcg_out_movr(s, 1, TCG_REG_X0, TCG_AREG0); > + tcg_out_movr(s, 1, TCG_REG_X1, addr_reg); addr_reg almost certainly needs to be zero-extended for 32-bit guests, easily done by setting ext = 0 here. > + unsigned int bits; bits = 8 * (1 << s_bits) - 1; unsigned int bits = ... > +#else /* !CONFIG_SOFTMMU */ > + tcg_abort(); /* TODO */ > +#endif This really is even easier: zero-extend (if needed), add GUEST_BASE (often held in a reserved register for 64-bit targets), perform the load/store. And of course for aarch64, the add can be done via reg+reg addressing. See e.g. ppc64 for how to conditionally reserve a register containing GUEST_BASE. > + case INDEX_op_rotl_i64: ext = 1; > + case INDEX_op_rotl_i32: /* same as rotate right by (32 - m) */ > + if (const_args[2]) { /* ROR / EXTR Wd, Wm, Wm, 32 - m */ > + tcg_out_rotl(s, ext, args[0], args[1], args[2]); > + } else { > + tcg_out_arith(s, ARITH_SUB, ext, args[2], TCG_REG_XZR, args[2]); > + tcg_out_shiftrot_reg(s, SRR_ROR, ext, args[0], args[1], args[2]); You can't clobber the args[2] register here. You need to use the TMP register. And fwiw, you can always use ext = 0 for that negation, since we don't care about the high bits. > + case INDEX_op_setcond_i64: ext = 1; > + case INDEX_op_setcond_i32: > + tcg_out_cmp(s, ext, args[1], args[2]); > + tcg_out_cset(s, ext, args[0], args[3]); > + break; ext = 0 for the cset, since the result is always 0/1. > +static void tcg_target_qemu_prologue(TCGContext *s) > +{ > + /* NB: frame sizes are in 16 byte stack units! */ > + int frame_size_callee_saved, frame_size_tcg_locals; > + int r; > + > + /* save pairs (FP, LR) and (X19, X20) .. (X27, X28) */ > + frame_size_callee_saved = (1) + (TCG_REG_X28 - TCG_REG_X19) / 2 + 1; > + > + /* frame size requirement for TCG local variables */ > + frame_size_tcg_locals = TCG_STATIC_CALL_ARGS_SIZE > + + CPU_TEMP_BUF_NLONGS * sizeof(long) > + + (TCG_TARGET_STACK_ALIGN - 1); > + frame_size_tcg_locals &= ~(TCG_TARGET_STACK_ALIGN - 1); > + frame_size_tcg_locals /= TCG_TARGET_STACK_ALIGN; > + > + /* push (FP, LR) and update sp */ > + tcg_out_push_pair(s, TCG_REG_FP, TCG_REG_LR, frame_size_callee_saved); > + > + /* FP -> callee_saved */ > + tcg_out_movr_sp(s, 1, TCG_REG_FP, TCG_REG_SP); You initialize FP, but you don't reserve the register, so it's going to get clobbered. We don't actually use the frame pointer in the translated code, so I don't think there's any call to actually initialize it either. r~ | https://lists.gnu.org/archive/html/qemu-devel/2013-05/msg03204.html | CC-MAIN-2022-33 | refinedweb | 746 | 58.32 |
Transfer from: As follows: First, there do need ireprot report, Save ireport inside the field is where you want the list passed to the jasper model encapsulated the field, correspo
First tell us about their relationship: jasperReport: an open source, powerful and flexible reporting library that can generate the html, pdf, etc. statements other formats. Official website: When downloa
开发使用步骤(iReport 4.1.1) 1. 开发使用步骤(iReport4.1)... 2 4.1. JasperReport 和iReport的介绍... 2 4.1.1. JasperReport 简介... 3 4.1.2. iReport 简介... 3 4.1.2.1. iReport几个重要的概念... 3 4.1.2.2. iReport数据库连接的建立 DataSource. 5 4.2. 创建报表(以几个不同类型的报表为例)... 7 4.2.1. iReport基本报表
Nothing to do during leisure time, staged a struts2 + spring + ibatis + jquery + json small example of spring configuration file: <? xml version = "1.0" encoding = "UTF-8"?> <beans xmlns = "
Today, I want early adopters, prepared under the struts2.1.8 spring3.0.1 ibatis3.0beta10 spare time to do something. Learning predecessors, then 0 is not configured but the configuration is not better than the agreed allocation, less to do configurat
"Basic" elements in 7 provided by the JasperReports: - Line - Rectangle (rectangle) - Ellipse - Static text - Text field (or simply Field) - Image - Subreport The combination of these elements, to create any kind of report. Other than that, iRep
Jasperreport + ireport practice operations and web applications To learn End jasperreports + ireport, for I feel deeply, not only mastered the technical report development, but also how the web master to generate pdf, xls, rtf file, the following is
iReport release: 3.7.3, JavaBean as a data source. 1. Be configured about classpath, click on "Tools "-->" Options "-->" iReport "-->" classpath", Click "AddFolder", choose your store the compiled
本人遇到一个程序页面,要有很大量的数据进行交互操作. 第一次进入aspx页面,就要读取出大量数据.写入页面中.使用都在页面要有添删改的操作,而且只有当点击面的保存按钮才能真正的写入到数据库中.因此我选择了Ajax+JSON的方式来实现这个页面. <asp:ScriptManager <Scripts>
做Winform习惯了,大家都习惯设置datasource这样的写法,今天就先从这个updatepanel加timer实现页面自动刷新这个例子来下手吧,感兴趣的朋友可以了解下,或许对你学习ajax有所帮助 做Winform习惯了,大家都习惯设置datasource这样的写法. 如果想实现页面定时刷新的话,用.net给封装好的updatepanel和timer两个控件实现起来其实挺容易的.这样做加入了很多你不能控制的元素,举个例子说就是:用updatepanel后,你设置的样式很有可能就变了,然后
beans xmlns="" xmlns:aop="" xmlns:xsi="" xmlns:p=""
iReport 中创建JavaBeanDataSource 用JavaBeanDataSource是为了调试制作的报表效果如何,所以要首先要让 iReport能找到class文件,为此要配置iReport的classpath. 步骤如下: 点击 工具 ----> 选项--->iReport里的classpath标签---->Add Folder 然后选择 java项目的输出路径,例如:mvn 项目的输出路径是 项目\target\classes,普通项目的就是 项目\bin 目录(不要忘
iReport中使用JavaBeanDataSource 上次发布了怎么配置JavaBeanDataSource,那么这次要从这个数据源中获取java对象的属性. 新建一个报表后在report inspector 中右键点击Fields--->添加Field 如果我们的XXXDataSourceFactory 的静态方法返回的是一个Blog对象集合,比如 public class Blog { private String title; private String url; private D
最近些日子一直在研究报表生成的模块,用的是jasperreport,用ireport来设计报表模板,涉及到后台像子报表传递参数. 后台采用的是springmvc+spring+spring data jpa, 在后台向子报表传递map参数时的步骤是: 1.在Parameters添加一个同后台传递到子报表map同名的parameter 2.设置subMap的属性 3.设置子报表的属性 Parameters Map Expression属性填写$P{subMap}, (tips:此项只能用来向子报表
很小的项目中用了一下jfinal无奈不支持fastjson,传说中jfinal插件那么多,但是搜遍了地球也找不到与fastjson相关的,只看到,就没有下文了(大概是jfinal想搞基让温少给写插件支持,而温少不鸟,搞基失败!),于是大神们都不解决只有靠自己动手,废话少说,先看治疗效果: 用上 JFinal 但是没有用上fastjson插件的的攻城狮近照 用上 JFinal 也用上了fastjson插
Ireport 分页介绍 功能介绍 基于ireport 3.7.6版本介绍ireport如何进行分页 开发步骤 1. 在ireport 报表中添加分页需要的变量 2. 设定首页,上一页,下一页,末页的超链接 3. 用jasper调用设定好的报表文件 开发示例 分页信息 当前显示1- 10条 共32条 第1页 共4页 首页 上一页 下一页 末页 1.设置当前分页的显示信息 1.1. 设置当前显示1- 10条 步骤 1.1.1 拉一个 text Field 右击 点击 edit expression
Today was how to resolve the following complex json object to the difficult living over a long time .. did not find documentation how to read JsonReader Ways json object (possibly also because of their limited level of E the text did not correctly un
Yesterday evening on the json + js + servlet to carry out a study of communication study. JJS present sense of self, communication is very simple, a large number of packets launched JJS greatly simplifies the difficulty of this model. From the back o
jQuery excellent Javascript is a framework for a good js packaging, provides a lot of convenient features. jQuery for ajax packaging can be called outstanding. jQuery can json file transfer protocol to transmit data (similar to xml, but also signific
Sales: Jsp | Ajax + fileupload + json + servlet by many file upload progress bar shows demo video and screenshots download 7.55M: Download 1: mail.qq.com / cgi-bin / ftnExs_download Download 2 (javaEye):
Today, Qualcomm wanted to run your own AJAX + JSON + STRUTS1.2 procedures. MyJson.jsp <script src="Json/json.js"></script> <script type="text/javascript" > var myjosn = { "people": [ {"name":"
In the use of javascript built-in eval function json string format into a JS object, need to use one of "()" first of the string around. For example: Will var strTest = '( "a": "b")'; converted to JS objects correctly written
json.jar this thing really hard to find, download available to everyone. And copied an example to study study. Examples of sources: "Ajax basic tutorial" Kim Ryong Translation, etc. This book is very good. jsonExample.html <html> <head&
JSON debut
Article reprinted from: POST request using JSON data When the decision to use JSON data POST request sent to the server, does not require substantial changes to the code, as follows: var ur
Article reprint: JavaScript Object Notation (JSON) data format useful to learn how to use it more easily in the application of mobile data and objects. Recalling the name / value pairs and XML
JSON (JavaScript Object Notation) data format of a simple, more compact than the xml. JSON format is native JavaScript, which means that the JavaScript in the JSON data do not need to deal with any special API or tool kit. JSON rules is simple: the o
In this paper, based on jQuery expanded its capacity to deal with json string, great jQuery will be great, ha ha! Writing javascript with jQuery is very efficient, jQuery for ajax package also in place; using jQuery after a certain period of time, jQ
Understanding of JNDI in the java: comp / env / jdbc / datasource and jdbc / datas
Abstract XML - this for that client and server data exchange between the payload format has become almost synonymous with Web services. However, because Ajax and REST technology applications that affected the structure, forcing people to seek alterna
struts2.1.X version of ajax theme has moved to dojo-plugin plug-in, usage has changed, according to online reviews of the ajax theme struts2 efficiency a bit low, do not recommend the use of the Internet now follow in the example in struts2 json-plug
JSON plugin provides a json called the ResultType, once designated for a certain type of Action for the json of Result, without the Result of resources mapped to any view. JSON plugin because Action will be responsible for the status information in t
Get one of today Dongdong ajax, on the use json, but could not find a solution to the problem of their own Javaeye search in a case like me, but according to how the above methods can not ah? ? Post address is There
Directly through the server-side resource manager (database connection pool) JNDI database connection with the summary: Tomcat: In the $ CATALINA_HOME / conf / server.xml connection pool set up, configure and <Host> must be </ Host> inter - &l
Understanding of JNDI in the java: comp / env / jdbc / datasource and jdbc / datasource difference. In describing the JNDI, for example, when access to data sources, JNDI address two ways for writing, for example, the same jdbc / testDS data source:
Datasource saw the establishment of official jetty code need web / inf below to create a new jetty-env.xml. However, this method is only suitable for the entire project in a complete package of the war circumstances, in order to successfully load, if
Some time ago to do a project using json, I take the time to write a struts + ajax + json examples. Ajax + json personal feel to a large extent reduces network and server IO, is a very good combination! 1: json the lib I'm using json-lib-2.1-jdk15.ja
JSON is a plug-in, it allows us to call in the asynchronous JavaScript in Action, it provides a return json result type (ResultType), as long as the specified type for Action return json result type, then the outcome of this response does not need to
JSONObject.fromObject (hibernate object) The following Exception net.sf.json.JSONException: java.lang.reflect.InvocationTargetException net.sf.json.JSONObject._fromBean(JSONObject.java:959) detaiMessage:Positioned Update not supported. Solution is as
Has done so much, you are more comfortable to use JavaScript, and perhaps in the model to consider more information on the browser. However, after reading the previous example (the use of XML to the server to send complex data structures), you may ch
1, JSON What is this? JSON stands for JavaScript Object Notation, is a lightweight data interchange format. JSON and XML with the same characteristics, such as easy-to-person writing and reading, easy-to-machine generation and parsing. However, more
Usually json-lib to handle the conversion between the java and json. Download address: Data conversion between the two as follows: JSON <=> java string <=> java.lang.String, java.lang.Character, char number <
James Williams, in his recent Blog Introduced a new JSON repository, Deckchair. Deckchair, is from JS ( Lawnchair ) Transplant Groovy lightweight JSON storage solutions. Simple to understand is that it provides a JSON store database, this database ca
java.lang.ClassNotFoundException: net.sf.ezmorph.Morpher Could not initialize class net.sf.json.util.JSONUtils Other abnormalities appear to be happening, possibly because of the lack of one of the following packages: ezmorph-1.0.6.jar commons-lang 2
Use of the JSON plugin struts2 configuration to do Struts2 configuration file package to inherit json-default, rather than the struts-default. json-default has inherited the struts-default. Configuration action returns a result <result type="json&
jsp page: <% @ Page contentType = "text / html; charset = utf-8"%> <% @ Page import = "java.util .*, com.union.dao.Sys_adcontent"%> <% @ Include file = "/ jsp / common / jsphead.jsp"%> <% String basePath
Look at the source code is distributed together with you to explore the inadequacies of the wing please. 1. Test file: test.json /** * Test JSON * */ { id:-NaN, //ID $name_1:"johnson\" Lee \"+\"test\"", // Name married:false,
In the project to transfer data using the JSON format, often encounter data format conversion, generally you can use the Json.org's lib, as well as some third-party framework to complete. But if it is a simple project, and the use of json is not much
CodeWeblog.com 版权所有 闽ICP备15018612号
processed in 0.035 (s). 8 q(s) | http://www.codeweblog.com/stag/ireport-json-datasource/ | CC-MAIN-2016-22 | refinedweb | 1,646 | 51.99 |
IRC log of ws-addr on 2005-09-12
Timestamps are in UTC.
19:47:49 [RRSAgent]
RRSAgent has joined #ws-addr
19:47:50 [RRSAgent]
logging to
19:47:59 [mnot]
zakim, this will be ws_addrwg
19:47:59 [Zakim]
ok, mnot; I see WS_AddrWG()4:00PM scheduled to start in 13 minutes
19:48:15 [mnot]
Meeting: Web Services Addressing Working Group Teleconference
19:48:18 [mnot]
Chair: Mark Nottingham
19:48:31 [mnot]
Agenda:
19:53:30 [Nilo]
Nilo has joined #ws-addr
19:54:15 [Marsh]
Marsh has joined #ws-addr
19:56:39 [Zakim]
WS_AddrWG()4:00PM has now started
19:56:46 [Zakim]
+ +1.408.687.aaaa
19:56:57 [Zakim]
+Vikas_Deolaliker
19:57:42 [mlpeel]
mlpeel has joined #ws-addr
19:57:57 [Arun]
Arun has joined #ws-addr
19:58:10 [Zakim]
+Steve_Vinoski
19:58:15 [TonyR]
TonyR has joined #ws-addr
19:58:27 [Zakim]
+[Sun]
19:58:29 [Arun]
zakim, [Sun] is me
19:58:29 [Zakim]
+Arun; got it
19:58:34 [Zakim]
+Rebecca
19:59:02 [Zakim]
+Jonathan_Marsh
19:59:09 [vikas]
vikas has joined #ws-addr
19:59:18 [RebeccaB]
RebeccaB has joined #ws-addr
19:59:18 [Zakim]
+DOrchard
19:59:20 [Zakim]
+??P14
19:59:34 [TonyR]
zakim, ??p14 is me
19:59:34 [Zakim]
+TonyR; got it
19:59:36 [Zakim]
+Nilo_Mitra
20:00:03 [Zakim]
+MarkN
20:00:29 [Zakim]
+Mark_Little
20:00:35 [Pete]
Pete has joined #ws-addr
20:00:36 [Zakim]
+MSEder
20:00:46 [pauld]
pauld has joined #ws-addr
20:00:58 [Marsh]
ZAKIM, mute mseder
20:00:58 [Zakim]
MSEder should now be muted
20:01:01 [Marsh]
ZAKIM, unmute mseder
20:01:01 [Zakim]
MSEder should no longer be muted
20:01:05 [stevewinkler]
stevewinkler has joined #ws-addr
20:01:10 [Zakim]
+Andreas_Bjarlestam
20:01:20 [Zakim]
+Mark_Peel
20:01:23 [Zakim]
+Pete_Wenzel
20:01:30 [Zakim]
+swinkler
20:01:40 [MSEder]
MSEder has joined #ws-addr
20:01:41 [stevewinkler]
zakim, swinkler is me
20:01:41 [Zakim]
+stevewinkler; got it
20:02:02 [mnot]
zakim, who is on the phone?
20:02:02 [Zakim]
On the phone I
20:02:05 [Zakim]
... (muted), Mark_Peel, Pete_Wenzel, stevewinkler
20:02:08 [MSEder]
zakim, mute me
20:02:08 [Zakim]
MSEder should now be muted
20:02:25 [Katy]
Katy has joined #ws-addr
20:02:29 [andreas]
andreas has joined #ws-addr
20:03:46 [Zakim]
+David_Hull
20:03:50 [anish]
anish has joined #ws-addr
20:03:55 [Zakim]
+Mark_Peel/Katy_Warr
20:03:57 [mnot]
zakim, aaaa is GPilz
20:03:57 [Zakim]
+GPilz; got it
20:04:03 [Zakim]
+Prasad_Yendluri
20:04:26 [Zakim]
+Marc_Hadley
20:04:43 [prasad]
prasad has joined #ws-addr
20:04:48 [Zakim]
+Anish
20:04:58 [marc]
marc has joined #ws-addr
20:05:21 [dorchard]
dorchard has joined #ws-addr
20:05:28 [Zakim]
+[MIT528]
20:05:38 [GlenD]
GlenD has joined #ws-addr
20:05:56 [hugo]
Zakim, [MIT528] really is Hugo
20:05:56 [Zakim]
I don't understand '[MIT528] really is Hugo', hugo
20:05:59 [Zakim]
+GlenD
20:06:03 [uyalcina]
uyalcina has joined #ws-addr
20:06:09 [hugo]
Zakim, [MIT528] is really Hugo
20:06:09 [Zakim]
+Hugo; got it
20:06:11 [Marsh]
Scribe: Marsh
20:06:26 [Marsh]
Meeting: WS-Addressing telcon
20:06:31 [Marsh]
Chair: Mark
20:06:39 [Zakim]
+Paul_Knight
20:06:43 [Marsh]
Topic: Agenda review
20:06:52 [Zakim]
+Umit_Yalcinalp
20:06:57 [vinoski]
vinoski has joined #ws-addr
20:07:23 [Marsh]
Agenda:
20:07:36 [Marsh]
no changes or other business
20:07:48 [Marsh]
Topic: Minutes approval 29 August.
20:07:56 [PaulKnight]
PaulKnight has joined #ws-addr
20:08:00 [Marsh]
RESOLUTION: Minutes approved as sne
20:08:05 [Marsh]
s/sne/sent/
20:08:13 [Marsh]
Topic: AI review
20:08:27 [Marsh]
2005-07-25: Paul Downey to generate list of features, their
20:08:27 [Marsh]
requirement level and applicability for discussion
20:08:34 [Marsh]
: DROPPED
20:08:49 [Marsh]
Arun's material appears sufficient.
20:09:02 [Marsh]
DHull review: DONE
20:09:12 [Marsh]
MarcG review: DONE
20:09:16 [Marsh]
Katy: PENDING
20:09:23 [Marsh]
Marsh AI: DONE
20:09:35 [pauld]
pauld has joined #ws-addr
20:09:41 [Zakim]
+??P37
20:09:48 [Zakim]
+Abbie_Barbir
20:09:49 [Marsh]
...
20:09:54 [Marsh]
All done but Katy's...
20:10:03 [Marsh]
Topic: Namespace change policy
20:10:14 [abbie]
abbie has joined #ws-addr
20:10:17 [Marsh]
Mark: Hugo suggested it would be good to write down a policy
20:10:31 [Marsh]
Hugo: I wrote a doc.
20:10:40 [Zakim]
+pauld
20:10:50 [hugo]
Draft I did:
20:11:29 [Marsh]
Hugo: For each draft we have set a new namespace, with the form w3.org/year/month/identifier
20:11:37 [gpilz]
gpilz has joined #ws-addr
20:11:44 [Marsh]
... we have been updating the namespace each publication.
20:12:01 [Marsh]
... We haven't agreed on how to change this from now on.
20:12:03 [Zakim]
+Abbie_Barbir.a
20:12:11 [Zakim]
-Abbie_Barbir
20:12:17 [Zakim]
+[IBM]
20:12:32 [Paco]
Paco has joined #ws-addr
20:12:34 [Marsh]
... Before we reach CR, we replace the namespace each time. When we reach CR, we only update if there is a significant change is made.
20:12:41 [Marsh]
... WHat is a significant change?
20:12:53 [Marsh]
... Up to the WG in each case.
20:13:16 [Marsh]
Chorus: Seems sensible.
20:13:42 [Marsh]
Mark: Philippe said it might be good to document this at the end of the NS URI.
20:13:59 [Marsh]
Hugo: Only problem is that the policy is only visible when dereferencing the namespace URI.
20:14:08 [Marsh]
... We should also put it in the status section of the doc.
20:14:19 [Marsh]
... I'm very flexible.
20:14:31 [Marsh]
... Good to see when people read the draft.
20:14:45 [Zakim]
+J.Mischkinsky
20:14:52 [Marsh]
Mark: Can we get a paragraph to paste into the spec and the RDDL?
20:15:38 [Marsh]
Hugo: Do you want to include the appropriate section from my doc?
20:15:45 [Marsh]
Mark: Yes, not too heavyweight.
20:15:59 [Zakim]
-David_Hull
20:16:10 [Marsh]
Nilo: CR says the URI only changes with significant changes. Hugo's proposal says the opposite.
20:16:20 [Marsh]
... Seems we need to remove the "NOT
20:16:36 [Marsh]
s/NOT/NOT"s/
20:16:48 [mnot]
From Section 2.2: After a document has been published as a Candidate Recommendation, the namespace IRIs will be updated only if changes are made to the document are not significant and do not impact the implementation of the specification.
20:17:01 [uyalcina]
+1 to Nilo
20:17:25 [Marsh]
Hugo: Ah, I see! To many negatives...
20:17:44 [Marsh]
... needs to be fixed. "are significant and impact ..."
20:18:19 [Zakim]
+David_Hull
20:18:22 [Marsh]
Mark: After we get to CR, we will attempt to keep the URI the same.
20:18:27 [Marsh]
...OK?
20:18:46 [Marsh]
ACTION: Editors to incorporate this into the document and the RDDL.
20:18:56 [uyalcina]
uyalcina has joined #ws-addr
20:19:01 [Nilo]
After a document has been published as a Candidate Recommendation, the namespace IRIs will be updated only if changes made to the document are significant and impact the implementation of the specification.
20:19:04 [Marsh]
Mark: Only 2.2 applies to the CR docs, section 2.1 applies to the WSDL doc.
20:19:15 [Marsh]
[general agreement]
20:19:40 [Marsh]
Topic: WSDL 2.0 review
20:20:00 [Zakim]
+Bob_Freund
20:20:00 [Marsh]
Mark: We have 3 of 4 AIs done. Let's walk through them.
20:20:34 [gpilz]
anyone know what the address of this server is?
20:20:51 [mnot]
20:20:53 [Marsh]
Mark: Tony's review on the Primer
20:21:09 [gpilz]
I meant the direct IRC address
20:21:33 [Marsh]
Tony: saw a number of typos.
20:21:45 [marc]
ACTION 1=Editors to incorporate ns update policy into drafts
20:21:54 [Marsh]
... We aren't included in the references.
20:23:06 [Marsh]
... Section 5.3 discusses endpoint references to describe the URL where the service lives.
20:23:19 [Marsh]
... Could be "endpoint URL" or an "endpointer"
20:23:40 [Marsh]
... A different term than "endpoint reference" would reduce confusion.
20:24:27 [Marsh]
Umit: THere is a definition of endpoint reference in 5.3.
20:24:36 [Marsh]
DaveH: Confusing.
20:24:52 [bob]
bob has joined #ws-addr
20:24:53 [anish]
WSDL has an endpoint and ws-addr has an endpoint and they are quite different
20:25:32 [Marsh]
Umit: If there is a different term, would that solve the problem?
20:25:33 [RebeccaB]
RebeccaB has joined #ws-addr
20:25:38 [Marsh]
Glen: Just the term, I believe.
20:25:52 [Marsh]
DaveH: Partly the term, partly two parallel universes.
20:26:12 [Marsh]
... One where you refer with a URI, one with an EPR. Took a couple of readings to figure out what was going on.
20:27:18 [Marsh]
Glen: the third universe is the syntactical constructs, they may contain policy etc.
20:27:30 [Marsh]
... the "endpoint" construct in WSDL.
20:28:04 [Marsh]
Tony: 5.3 comes right after 5.2 which makes reference to WS-A, already given people a defn of endpoint reference there (implicitly).
20:28:16 [Marsh]
... Different term would avoid confusion.
20:28:57 [Marsh]
Umit: Definitions in Core and 5.3, and 5.2 introducing concepts in wrong order (possibly).
20:29:09 [Marsh]
Mark: Happy to send to WSDL?
20:29:18 [Marsh]
[apparently so]
20:29:20 [Gil]
Gil has joined #ws-addr
20:29:25 [Marsh]
s/send/send Tony's comments/
20:29:42 [Marsh]
Mark: Dave's comments
20:29:42 [gpilz]
gpilz has left #ws-addr
20:29:43 [mnot]
David Hull's comments on the Core:
20:29:51 [mnot]
zakim, who is on the phone?
20:29:51 [Zakim]
On the phone I see GPilz, Vikas_Deolaliker, Steve_Vinoski, Arun, Rebecca, Jonathan_Marsh, DOrchard, TonyR, Nilo_Mitra, MarkN, Mark_Little, MSEder (muted), Andreas_Bjarlestam
20:29:55 [Zakim]
... (muted), Mark_Peel, Pete_Wenzel, stevewinkler, Mark_Peel/Katy_Warr, Prasad_Yendluri, Marc_Hadley, Anish, Hugo, GlenD, Paul_Knight, Umit_Yalcinalp, ??P37, pauld, Abbie_Barbir.a,
20:29:58 [Zakim]
... [IBM], J.Mischkinsky, David_Hull, Bob_Freund
20:30:21 [Marsh]
[postponed temporarily]
20:30:31 [Marsh]
Mark: Marc Goodner's comments:
20:30:40 [Marsh]
... typos
20:30:57 [Marsh]
20:31:41 [Marsh]
... points out some relevant sections of the spec, but don't appear to be issues.
20:32:05 [mnot]
WSDL Adjuncts Section 2.2:
20:32:06 [mnot]
WSDL patterns specify propagation of faults, not their generation. Nodes which generate a fault MUST attempt to propagate the faults in accordance with the governing ruleset, but it is understood that any delivery of a network message is best effort, not guaranteed. The rulesets establish the direction of the fault message and the fault recipient, they do not provide reliability or other delivery guarantees. When a fault is generated, the generating node MUST atte
20:32:24 .
20:33:19 [Marsh]
Mark: That seems fine.
20:33:35 [mnot]
20:33:48 [Marsh]
... SOAP Action Feature doesn't mention WSA Action - oversight?
20:34:14 [Marsh]
... thoughts?
20:34:18 [Marsh]
Marsh: What would WSDL say?
20:34:29 [Marsh]
Mark: Might say "there are other specs out there..."
20:35:13 [yinleng]
yinleng has joined #ws-addr
20:35:15 [Marsh]
... Let's defer these till next week.
20:35:27 [Marsh]
... when Katy's got her review done.
20:35:36 [abbie]
abbie has left #ws-addr
20:35:44 [Marsh]
... And forward the typos.
20:35:44 [Zakim]
-Abbie_Barbir.a
20:36:20 [Marsh]
DaveH: Except for 3.3, most of the COre is too generic to be of concern to us.
20:36:50 [Marsh]
... In 3.3, wsdlx:interface and wsdlx:binding are defined.
20:37:17 [Marsh]
... Need to clarify endpoint references as applied to URIs.
20:37:50 [Marsh]
... By tagging it the semantics of "this is a reference to an endpoint" are applied.
20:38:25 [uyalcina]
q+
20:38:35 [Marsh]
... It's nice, e.g. WSN, to say that an EPR is a particular type.
20:38:53 [Marsh]
Marsh: Interesting it wasn't clear to you that you can use these for wsa:EPRs.
20:39:07 [Marsh]
DaveH: Wasn't clear - should make it more explicit.
20:39:18 [Marsh]
... Nice to hang it off an element declaration instead of just a type.
20:39:35 [Marsh]
... Seems lighter weight than deriving a new type.
20:39:58 [Marsh]
... Don't think anything would preclude that design. The examples in the primer tend towards extending a type nor an element.
20:40:36 [Marsh]
... A use case was what is in the data vs. a schema.
20:40:46 [Marsh]
... Could include wsdlx:interface in an EPR.
20:40:55 [Marsh]
... Is that what WSDL wanted?
20:41:43 [Marsh]
Umit: Is there a problem in the Core (3.3), it says that that are AIIs in wsdlx, and a comment about how these can be used together, and how they are applied to xs:anyURI.
20:42:10 [Marsh]
... No restriction against using them with wsa:EPRs. Are you saying there should be used on wsa:EPRs? and an example?
20:42:53 [Marsh]
DaveH: Says these annotate anyURIs or restrictions thereof, which sounds exclusive.
20:43:16 [Marsh]
Umit: That wasn't the intent. Add more text making it clear it can be used on EPRs too?
20:43:51 [Marsh]
Dave: "xs:anyURI" -> "xs:anyURI and wsa:EPR" or just drop xs:anyURI and talk about elements.
20:44:01 [Marsh]
... even adding "such as" would have helped.
20:45:23 [Marsh]
Marsh: Intention was to provide description level constructs to complement wsa:Metadata/wsaw:ServiceName, etc.
20:45:41 [Zakim]
-J.Mischkinsky
20:45:41 [Marsh]
Dave: Was the intention to allow on element decls as well as types?
20:45:46 [Marsh]
Marsh/Umit: Don't remember.
20:46:18 [Marsh]
Dave: Other than this, core looks good.
20:46:20 [Marsh]
Summary:
20:46:41 [Marsh]
1) Clarify wsdlx: can apply to EPRs, not just xs:anyURI.
20:46:56 [Marsh]
2) Can wsdlx: be applied to element decls, not just types?
20:47:31 [Marsh]
ACTION: DaveH to revise his comments on WSDL 2.0 3.3, by 9/19
20:47:54 [stevewinkler]
stevewinkler has joined #ws-addr
20:48:18 [mnot]
Topic: i061
20:48:19 [mnot]
20:48:28 [Marsh]
Topic: i061 i061 - Action without UsingAddressing
20:51:42 [GlenD]
+1
20:51:47 [marc]
q+ to ask a question on wsdl:required=false case
20:53:06 [mnot]
ack uyal
20:53:10 [Marsh]
Marsh: Goes through his posting.
20:53:15 [mnot]
ack marc
20:53:15 [Zakim]
marc, you wanted to ask a question on wsdl:required=false case
20:53:19 [Marsh]
Arun: We should add some of this to the spec.
20:53:21 [anish]
q+
20:54:06 [Marsh]
Marc: wsdl:required="false" allows a service to send headers without receiving them from the client.
20:54:20 [Marsh]
... That seems bad.
20:54:46 [Marsh]
... You could send me a message with a messageID, expecting a relatesTo, but you won't get it, which is bad.
20:55:22 [dhull]
dhull has joined #ws-addr
20:56:06 [Marsh]
Marsh: We could define that behavior - separate issue.
20:56:46 [mnot]
ack anish
20:57:06 [Marsh]
Umit: Bottom line: wsas:Action can't force behavior without wsa:UsingAddressing.
20:57:39 [TonyR]
"la la la" - can't hear anything
20:59:32 [Marsh]
Anish: you say a client MAY engage wsaw:Action when wsdl:required="false", but not pick and choose the rest of the WS-A features.
20:59:53 [Marsh]
... WHen the client uses WS-A it must engage it fully as we spec.
21:00:11 [Zakim]
-Mark_Little
21:00:31 [pauld]
s/"la la la" - can't hear anything//
21:02:41 [Zakim]
-DOrchard
21:02:58 [Marsh]
Marsh: Useful to clarify that.
21:03:41 [Gil]
get the video!
21:03:41 [Marsh]
Summary:
21:04:04 [Marsh]
1) in case 2, if wsa headers are sent, they must be responded to by the service.
21:04:57 [Marsh]
2) in case 2, client either chooses to honor Addressing, or not to include any wsa headers (whole enchilada)
21:05:29 [Marsh]
3) in case 3, wsaw:Action is informational.
21:05:36 [Marsh]
Clarify these three items.
21:05:38 [mnot]
[numbered bullets are additions to 3' proposal in Jonathan's e-mail]
21:05:55 [Marsh]
Paco:
21:06:08 [Marsh]
"informational/advisory" should say "no normative intent".
21:08:05 [Marsh]
Marsh: you can't ignore it in all cases (out of band may make use of it).
21:08:40 [Marsh]
Mark: Everyone comfortable with this?
21:08:44 [Marsh]
[seem so]
21:09:00 [Marsh]
... Can we send this off to the editors?
21:09:21 [Marsh]
Marc: Would like some text.
21:09:40 [Marsh]
ACTION: Paco to come up with wording to implement i061 based on the above discussion.
21:10:15 [Marsh]
Topic: i056 Determining the value of destination from WSDL.
21:10:42 [anish]
21:11:16 [Marsh]
Mark: Marc's link is the proposal on the table.
21:11:49 [Marsh]
... everyone comfortable at this point?
21:12:05 [Marsh]
Umit: looks reasonable, except for one thing.
21:12:46 [Marsh]
... "if there is no wsa:EndpointReference..." what does it mean that there is an anonymous URI for the destination?
21:13:05 [Marsh]
Marc: IIRC, the anonymous means "do what the transport says".
21:13:11 [anish]
q+
21:13:18 [Marsh]
... we define HTTP response.
21:13:30 [Marsh]
Umit: For destination what does that mean?
21:13:48 [Marsh]
... for SOAP/HTTP.
21:13:55 [vikas]
Every binding has its own "understanding" of what is anonymous URI
21:14:18 [Marsh]
Marc: Conclude it's bad WSDL at that point.
21:14:32 [Marsh]
Umit: Maybe the fourth rule shouldn't apply then.
21:14:47 [Marsh]
Mark: Are there other bindings where that would have utility?
21:15:20 [Marsh]
Umit: Unless there were a catalog or config file to map anonymous.
21:15:24 [Marsh]
... Not very interoperable.
21:15:32 [Marsh]
Marsh: What's the alternative?
21:15:35 [mnot]
ack anish
21:15:56 [Marsh]
Anish: If you wanted to support a way to have this defined elsewhere, we should call it "undefined".
21:16:26 [Marsh]
... IF a binding could define what anonymous means it would be useful, but I can't think of such a binding.
21:17:11 [Marsh]
... Maybe a separate issue: we require a destination to be anonymous, which is delegated to the binding. In the SOAP binding we define what it means for replyTO and faultTo, but not destination.
21:17:49 [Marsh]
Mark: We could change the fourth bullet to say "it's undefined", or define what anonymous means for destination.
21:18:21 [Marsh]
Umit: We need to define anonymous for [destination] in any case.
21:19:29 [Marsh]
Anish: If wsa:To is missing destination is anonymous already. Is #4 adding anything?
21:19:50 [Marsh]
Marc: Mixing up the value of wsa:To and the value of the property.
21:20:28 [Marsh]
Anish: Proposal is if no values are specified you use anonymous. Similar with wsa:To.
21:20:43 [Marsh]
Marc: Doesn't interfere with it, just conveys it.
21:21:17 [Marsh]
Umit: In the end, what is the address on the wire?
21:21:37 [Marsh]
Marc: If you're sending a message to anonymous, you can omit the wsa:To header or put in the anonymous value.
21:22:07 [Marsh]
Umit: The relation of the HTTP address and the anonymous URI needs to be clarified somewhere.
21:22:26 [Marsh]
Marc: We only define one case where anonymous has a meaning - HTTP back-channel.
21:22:41 [Marsh]
Mark: What are you recommending?
21:22:50 [Marsh]
... that people avoid anonymous for destination?
21:22:57 [Marsh]
Umit: Not sure what the solution is.
21:24:06 [Marsh]
... Maybe clarify where anonymous doesn't make sense.
21:24:20 [Marsh]
Mark: So should we change or remove the 4th bullet?
21:24:41 [Marsh]
Marc: Don't think we fix anything by removing the default.
21:25:08 [Marsh]
Paco: This is a hole in WSDL we're trying to fix.
21:25:58 [Marsh]
... If you have a WSDL with no address, we're providing an interpretation for that case.
21:26:15 [anish]
q+
21:26:57 [Marsh]
Paco: Can we derive the value of [destination] from WSDL? When the WSDL author doesn't provide one, we'll provide one.
21:27:09 [uyalcina]
q+
21:27:13 [Marsh]
... Is that the wisest thing to do?
21:27:18 [mnot]
ack anish
21:28:00 [Marsh]
Anish: In the proposal, the EPR is included as a child of wsdl:endpoint or wsdl11:port. DOes that mean the EPR applies only to the out messages for that endpoint/port?
21:28:06 [Marsh]
s/out/in/
21:28:33 [Marsh]
... What happens when it's specified for a port with only an out message?
21:28:52 [Marsh]
... Need to be more specific on which messages the embedded EPR applies to.
21:29:05 [Marsh]
... requires more thought.
21:29:52 [mnot]
ack uyal
21:29:54 [Marsh]
... Specifically a problem with the first "in" message, but might be others.
21:30:17 [Marsh]
Umit: The reason you don't have an address in teh port (WSDL perspective) is that the address is added at deployment.
21:30:31 [Marsh]
... Might not be safe to assume there is an anonymous destination.
21:30:40 [Marsh]
... Addresses might be provided at a later time.
21:30:55 [Marsh]
Marc: Why would you have an EPR at a later time.
21:31:29 [Marsh]
... OK, maybe so.
21:32:18 [Marsh]
ACTION: Anish to explore the issue of application to messages other than the first "in".
21:33:17 [Marsh]
ACTION: Umit explore the issues surrounding bullet 4 for next week.
21:33:35 [Marsh]
Mark: i056 to email.
21:34:06 [Marsh]
Topic: i059 support for async
21:34:20 [Marsh]
Mark: Delegated to the Async TF.
21:34:40 [Marsh]
... At this point it seems the TF is running out of steam a bit. Good time to bring it back into the WG.
21:35:02 [Marsh]
... Need to wrap this up to get the doc into CR.
21:35:29 [Marsh]
... Glen will write up a summary, esp. of the decisions to be made, different proposals for solving them.
21:35:33 [Marsh]
... Please look for it.
21:36:03 [Marsh]
... Will reserve a chunk of the FTF to talk about this issue. If you have a proposal get it in by then.
21:36:32 [Nilo]
Nilo has joined #ws-addr
21:36:36 [Marsh]
... Number of ways to address the issue, but we need to see which fit within our deliverables and our charter requirements.
21:38:29 [Marsh]
Topic: i020 Addressing and WSDL.
21:38:38 [Marsh]
Mark: Revised proposal from Anish.
21:38:42 [stevewinkler]
glen, I'll send my regrets for wed now, I'm on the road...
21:38:49 [mnot]
Topic: i020
21:38:50 [mnot]
21:39:28 [Marsh]
Anish: Logical/physical address
21:39:30 [bob]
q+ re Japan Logistics
21:39:48 [Marsh]
... There was the potential for a physical and logical address.
21:40:34 [Marsh]
... The proposal had three parts, part 2 and 3 defined the relation of physical and logical.
21:40:48 [Marsh]
... those have gone away. Part 1 uses updated terminology.
21:41:28 [Marsh]
... Proposal:
21:41:28 [Marsh]
When the EPR minter includes a [selected port type], and/or [service-port] then the EPR is considered to be specific to the [selected port type] and/or [service-port]
21:41:37 [Marsh]
Marsh: The spec doesn't say this yet?
21:41:39 [uyalcina]
q+
21:41:46 [Marsh]
Anish: No, not that I could see.
21:42:03 [mnot]
ack uyal
21:42:28 [Marsh]
Umit: No we don't say that anywhere. Although it seems obvious, it's not explicitly stated anywhere.
21:43:15 [Marsh]
Paco: Makes sense.
21:43:16 [uyalcina]
+1 for the proposal
21:43:56 [Marsh]
Mark: Any objections to the proposal?
21:44:12 [Marsh]
Vikas: Doesn't resolve the logical and physical.
21:44:27 [Marsh]
Mark: We resolved a while ago we wouldn't talk about that.
21:44:32 [mnot] t
21:44:41 [mnot]
vice QName is present in the EPR. I.e., should our spec say that if the service QName is present then the physical address is what is specified by the wsdl port.
21:46:10 [Marsh]
Anish: WSDL never says the port address is any more physical than the WS-A address. THey are all IRIs and that's that.
21:46:35 [Marsh]
Vikas: Maybe we should rewrite the issue to get rid of the logical/physical confusion.
21:47:15 [Marsh]
Umit: Does Anish's proposal make sense on it's own right or not.
21:47:38 [Marsh]
Vikas: If the issue is cloudiness about physical/logical, the proposal doesn't address it.
21:48:08 [Marsh]
Mark: Should we delete everything but the second sentence of the issue?
21:49:10 [Marsh]
Anish: We can point to i052, say the questions about logical/physical are addressed there.
21:49:35 [Marsh]
Mark: Proposed resolution: Anish's proposal, plus a ref to the resolution of 052.
21:49:55 [Marsh]
... Everyone comfortable?
21:50:12 [Marsh]
Vikas: i052 resolution: remove "logical" when talking about addresses.
21:50:21 [Marsh]
[silent assent]
21:50:37 [Marsh]
RESOLUTION: i052 closed with Anish's proposal.
21:51:21 [Marsh]
Topic: 2:51PM PDT, let's talk logistics
21:52:02 [Marsh]
Bob: Customers have co-opted our meeting room, we've moved to a nearby building.
21:52:33 [Marsh]
... Logistics coming.
21:52:43 [Marsh]
... Negotiated rates available through email reservation.
21:53:24 [Marsh]
... Unless you are fluent in Japanese, have an international drivers license, etc., it's maddness in the metro area to try to drive.
21:54:09 [Marsh]
... Will be escorting people from the hotel to the meeting room starting on the 7th
21:54:24 [Marsh]
... Trying to gauge interest in some sightseeing or entertainment.
21:54:57 [Marsh]
... Just after the peak of the autumn color season, we might be able to get some rooms there Nov 5,6.
21:55:38 [Marsh]
... Other details like how to buy tickets, get from the airport, etc. coming.
21:55:48 [Marsh]
DaveH: How long is the Narita express?
21:56:37 [Marsh]
Bob: About an hour. 12 min from hotel to meeting room; fare: 210. Narita Express fare information forthcoming.
21:57:00 [Marsh]
... $125 hotel + $10.70 internet access.
21:57:43 [Marsh]
... I'm translating maps from Japanese, takes a while.
21:58:06 [Zakim]
-stevewinkler
21:58:08 [Marsh]
Mark: Talk next week, might be absent, in which case Hugo will chair.
21:58:11 [Marsh]
... Do your AIs.
21:58:12 [Zakim]
-Paul_Knight
21:58:19 [Marsh]
... Get your potential issues in.
21:58:27 [Zakim]
-Hugo
21:58:27 [Marsh]
[adjourned]
21:58:28 [vinoski]
vinoski has left #ws-addr
21:58:28 [Zakim]
-Arun
21:58:28 [Zakim]
-pauld
21:58:29 [Zakim]
-Vikas_Deolaliker
21:58:30 [Zakim]
-Nilo_Mitra
21:58:31 [Zakim]
-??P37
21:58:32 [Zakim]
-MSEder
21:58:33 [Zakim]
-[IBM]
21:58:34 [Zakim]
-Mark_Peel
21:58:36 [Zakim]
-Mark_Peel/Katy_Warr
21:58:38 [Zakim]
-Pete_Wenzel
21:58:38 [Marsh]
RRSAgent, draft minutes
21:58:38 [RRSAgent]
I have made the request to generate
Marsh
21:58:40 [Zakim]
-Andreas_Bjarlestam
21:58:42 [Zakim]
-TonyR
21:58:44 [Zakim]
-Prasad_Yendluri
21:58:46 [Zakim]
-MarkN
21:58:46 [yinleng]
yinleng has left #ws-addr
21:58:48 [Zakim]
-GlenD
21:58:50 [Zakim]
-Rebecca
21:58:52 [Zakim]
-Anish
21:58:53 [Gil]
Gil has left #ws-addr
21:58:54 [Zakim]
-Umit_Yalcinalp
21:58:56 [Zakim]
-Marc_Hadley
21:58:58 [Zakim]
-Bob_Freund
21:58:58 [TonyR]
TonyR has left #ws-addr
21:59:00 [Zakim]
-Steve_Vinoski
21:59:02 [Zakim]
-David_Hull
21:59:04 [Zakim]
-GPilz
21:59:06 [Zakim]
-Jonathan_Marsh
21:59:08 [Zakim]
WS_AddrWG()4:00PM has ended
21:59:10 [Zakim]
Attendees,
21:59:13 [Zakim]
... Mark_Peel, Pete_Wenzel, stevewinkler, David_Hull, Mark_Peel/Katy_Warr, GPilz, Prasad_Yendluri, Marc_Hadley, Anish, GlenD, Hugo, Paul_Knight, Umit_Yalcinalp, Abbie_Barbir,
21:59:16 [Zakim]
... pauld, [IBM], J.Mischkinsky, Bob_Freund
22:00:05 [bob]
bob has left #ws-addr
22:03:26 [mnot]
rrsagent, please generate minutes
22:03:26 [RRSAgent]
I have made the request to generate
mnot
22:22:38 [anish]
rrsagent, make log public
22:23:03 [anish]
rrsagent, where am i
22:23:03 [RRSAgent]
I'm logging. I don't understand 'where am i', anish. Try /msg RRSAgent help | http://www.w3.org/2005/09/12-ws-addr-irc | CC-MAIN-2015-35 | refinedweb | 4,983 | 74.19 |
To).
A key concept to keep in mind is that when you start a Task your application is tombstoned. That is, it is likely to be terminated and the user may never return to your application (especially if you use a launcher, but even if you use a Chooser – they can always turn the phone off!)
In the case of a Chooser, when you return from the Task your call back method will be called, but only if you set it up as a private member variable and not as a local variable within a method. Here’s how to do it…
Declare the task as a private member variable.
I started by creating a new Windows Phone Application and added a button that I named SMS to the Main Page. I then declared the following at the top of the class, in the code behind,
public partial class MainPage : PhoneApplicationPage { private PhoneNumberChooserTask _choosePhoneNumber;
The next step is to initialize the PhoneNumberChooserTask in the constructor for the page,
public MainPage() { InitializeComponent(); _choosePhoneNumber = new PhoneNumberChooserTask();
Now we’ll set up an event handler for the button to invoke this Task. You invoke a task by calling its Show method.
void SMS_Click( object sender, RoutedEventArgs e ) { _choosePhoneNumber.Show(); }
As noted above the task runs asynchronously – in fact it runs even while your application is being tombstoned. You therefore need a callback method. Here’s the complete code-behind file. Note the set up for the button’s even handler and for the Tasks’s call-back in the constructor. In our case the callback will just open a message box with the phone number chosen from the sample contact data supplied with the emulator,
using System; using System.Windows; using Microsoft.Phone.Controls; using Microsoft.Phone.Tasks; namespace SMS { public partial class MainPage : PhoneApplicationPage { private PhoneNumberChooserTask _choosePhoneNumber; private SmsComposeTask _smsCompose; // Constructor ) { System.Windows.MessageBox.Show( "You picked the phone number " + e.PhoneNumber ); } } }
In the next mini-tutorial I’ll demonstrate how to take that phone number and use it to generate an SMS message (which is far easier than it sounds).
Pingback: Getting ready for the Windows Phone 7 Exam 70-599 (Part 3) –
Pingback: Launchers and Choosers
Pingback: Tweets that mention Tasks: Launchers and Choosers
Pingback: Tweets that mention Tasks: Launchers and Choosers | http://jesseliberty.com/2011/01/24/tasks-launchers-and-chooserswindows-phone-from-scratch-21/ | CC-MAIN-2021-31 | refinedweb | 382 | 60.55 |
Configuring a Gcr.io Registry
You can use gcr.io as registry to host Camel K images. Usually, users may want to use gcr.io in combination with Google GKE.
In order to push images to
gcr.io, you need to provide a valid key to Camel K. The best way to obtain a valid key is from the Google web console:
Go to
Make sure the project where you created the Kubernetes cluster is selected in the drop-down list
To avoid confusion, it’s suggested to use the "English" language in preferences of the Google Cloud console
Select "IAM & admin" from the navigation menu, then "Service accounts"
Create a new service account specifying the following id: "camel-k-builder"
You’ll be asked to select a role. It’s important to select the "Storage Admin" role from the "Storage" menu
Finish creating the service account
From the action menu of the service account you’ve created, create a key using the JSON format
A
.json file with the key will be downloaded to your machine. You need to store that key in a Kubernetes secret.
It’s important to rename the file you’ve just downloaded to
kaniko-secret.json (make sure you write it correctly). After the renaming, execute the following command to create the secret:
kubectl create secret generic kaniko-secret --from-file=kaniko-secret.json
You should now execute the following command to install cluster resources and the operator (in the current namespace):
kamel install --build-publish-strategy=Kaniko --registry gcr.io --organization <<your-project-id>> --registry-secret kaniko-secret
Use the project id of your project on GKE. Usually this can be obtained from the connection string. | https://camel.apache.org/camel-k/next/installation/registry/gcr.html | CC-MAIN-2022-40 | refinedweb | 283 | 64.71 |
go to bug id or search bugs for
New/Additional Comment:
Description:
------------
A class without __construct method cannot use a trait that has a method that equals the class it's name. It will execute the trait method as constructor when E_DEPRECATED errors are ignored. This should never happen.
Test script:
---------------
error_reporting(E_ALL ^ E_DEPRECATED);
class Callback {
use CallbackTrait;
}
trait CallbackTrait {
public function callback() {
echo 'this is called';
}
}
new Callback();
---
Expected result:
----------------
It should ignore the method as constructor like extends does or it should trigger a fatal error as it does when a constructor is present ()
Add a Patch
Add a Pull Request
I agree that we should only treat __construct as a constructor when coming from a trait.
Interesting that this only comes up now, probably not many people using traits with non-namespaced code.
While trying to fix this I found bug #55554, which is where the current behavior was implemented.
It also has this example, which makes slightly more sense in that the legacy ctor name is used as an explicit alias:
trait TConstructor {
public function constructor() {
echo "ctor executed\n";
}
}
class NewConstructor {
use TConstructor {
constructor as __construct;
}
}
class LegacyConstructor {
use TConstructor {
constructor as LegacyConstructor;
}
}
Given this, I'm not sure whether to make this change. It would only be able to go into 7.4 if at all, and in PHP 8 legacy constructors are going away entirely, so the problem will resolve itself at that time.
Marking this as won't fix per the above comment. Legacy dtor support is gone from PHP 8 and the code behaves as desired there. I don't think it's worthwhile to make a (BC-breaking) change in 7.4 in addition to that.
I agree. Thanks for looking into this. | https://bugs.php.net/bug.php?id=77470&edit=1 | CC-MAIN-2021-31 | refinedweb | 293 | 59.53 |
Grails: This Time With Tools
Here's how to get started with Grails in NetBeans IDE 6.5.
-.
-:
-:
- Create the Controller
Right-click the Controllers node:
Type "Book" and notice that you are shown that the generated class will be called "BookController":
Then comment out the one line generated within the braces and add this one:
def scaffold = Book
You should now see this:
-.
Jul 20 2008, 08:19:32 AM PDT Permalink
PS: The above is also available here:
Posted by Geertjan on July 20, 2008 at 09:41 AM 22, 2008 at 04:46 AM 08 07:03 PM PDT #
That's the main area that's currently being worked on Michael. Should be in good shape in the coming weeks.
Posted by Geertjan on July 23, 2008 at 11:44 PM PDT #
Same problem stopping jetty... otherwise the IDE is really nice, much comfortable than eclipse.
Posted by Pablo on July 24, 2008 at 04:45 AM 24, 2008 at 06:24 AM PDT #
Is it possible to execute Grails commands like generate-all from Netbeans 6.5 ?
Posted by carol mcdonald on July 28, 2008 at 10:37 AM PDT #
Yes Carol. Create a domain class by right-clicking on the Domain Classes node and then right-click a domain class node and you will see generate-all!
Posted by Geertjan on July 28, 2008 at 10 10:44 AM PDT #
Is there a paypal link or someplace to donate? Send me the link and I'll send you a beer... :)
Posted by Michael Kimsal on July 28, 2008 at 07:49 PM PDT #
interesting
Posted by satılık araba on August 03, 2008 at 01:48 AM PDT #
your website sucks. buy u some design dude
Posted by 89.15.87.125 on August 05, 2008 at 06:47 AM 10 21, 2008 at 01:00 AM 10:00 AM PST # | http://blogs.sun.com/geertjan/entry/grails_this_time_with_tools | crawl-002 | refinedweb | 315 | 76.15 |
C++..
Join the conversationAdd Comment
I can’t get the samples to compile with the Visual Studio “15” toolset. Is this a known bug in C++/WinRT or Visual Studio “15”?
The initial release targets Visual C++ Update 3. We’ll get an update out that also supports Visual Studio “15” preview very soon.
I just checked and all of the samples build cleanly with Preview 5. You might experience some msbuild warnings but nothing that should prevent you from building/debugging/running on Preview 5. If you’re still running into issues, please give us detailed feedback here and we’ll investigate:
This thread immediately springs to mind:
(linked here in)
Good to see that you finally saw what the C++ devs were saying to you back then. Five years wasted, but better late than never.
It’s been quite a journey. Credit goes too Kenny for relentlessly pursuing this standard-compliant approach as well as stretching the limits of the compiler many times with the work on this library.
But keep in mind that the MSVC compiler has been constantly improving its C++ standards support since then, release after release, to get to this point.
Frankly, some of those posters missed points by miles and proposed insane and brain-damaged (to borrow expression from Linus Torvalds) ideas like “just throw extra tools to support same things as C++/CX” to make compilation of project even bigger hassle and get us even more headaches just “because”.
But then, I used C++/CX for smaller projects and it demonstrated its worth.
BTW: It would be then great idea to force GCC to remove all those “nice” extensions too if they are so evil…
Except the thread wanted to put the added logic into the compiler and the only context in which “external tools” appeared was along the lines of “if for some reason you don’t want to put this into the compiler, fine, put it into an external tool, we’ll manage”. (Which, ironically, is exactly what happened with C++/WinRT where the logic generating header files is an external tool – nothing wrong with that, just showing that your objection of “these guys in the thread are nuts, they even want external tools, thank god Microsoft folks don’t fall for such brain-damaged suggestions” is completely bizarre.)
And your “just because” was, in fact, “in order to use WinRT from C++ without language extensions”. So, a little more than “just because”. It’s the exact same reason Microsoft created C++/WinRT that the blog is about.
Visual Studio 2015 Update 3 compiler produces an ICE if enabling PGO for release builds in samples. Apparently, coroutines are not compatible with PGO right now 🙁
Didn’t try the VS 15 Preview yet. If someone has it installed, is it able to successfully compile AsyncReader sample after enabling PGO?
Thanks for the report, Alex. The PGO dev is looking at it now.
It turns out there’s a known issue with PGO and resumable functions. We’re working on a fix but it’s a complicated issue.
Hi, could someone explain me, what is the C++/WinRT? Is it just a new extension of C++, like C++/CX, in other words, replacement of C++/CX?
PS: or is it something like STL in C++?
Watch CppCon 2016: Kenny Kerr & James McNellis “Putting Coroutines to Work with the Windows Runtime” on youtube for an explanation.
What is the purpose of this?
The Windows Runtime is the technology behind the modern Windows API, called the Universal Windows Platform. That just means that the same API can be used across all Windows devices, whether its Xbox, phones, tablets, HoloLens, PCs, or anything else that happens to run Windows.
Even though the Windows Runtime is based on COM, it wasn’t designed to be used directly as you might a classic COM API. Rather, a developer would use what we call a language projection, which is a way to project the Windows Runtime into your favorite language. While Microsoft did a great job of integrating the Windows Runtime into C# and the CLR, there was nothing for the standard C++ developer, who wasn’t satisfied with the non-standard CX extensions or the complexity of WRL.
That’s where C++/WinRT comes in. It is meant as an alternative to both C++/CX and WRL with a language projection designed specifically for modern C++ developers.
James and I gave a talk at CppCon introducing C++/WinRT in a lot more detail here:
I was also on the CppCast podcast today to talk about C++/WinRT:
Thanks a lot for explanation, great job!
On GitHub is this statement: “During our initial rollout of this template library, we will release only the C++ header files that comprise the library for the WinRT APIs documented in Windows 10 Anniversary Update SDK.”
What about “pre Anniversary SDKs”, will they be supported although most of Win10 systems are “forced” to update OS?
You can also use it to target previous builds. You just have to make sure that the Windows APIs you call are actually available on those older platforms.
Thank you for the explanation. So when is this coming to Xbox? As we are porting our game to Xbox we are very unhappy to have to deal with CX/WRL due to the fact that we have no knowledge with these technologies and at the same time we are pressured by time and budget.
We are working closely with the Xbox team to make the wrappers available for Xbox as part of the Xbox developer program. Please talk to your Microsoft contact or the ID@XBOX program for more details.
I’ve been waiting for this since Kenny joined MS
This is great! Thank you!
I’m trying to port this CX code to C++/WinRT, but I’m stuck on adding the button to the stack panel. How is this done?
using namespace Windows::UI::Xaml::Controls;
auto stackPanel = ref new StackPanel();
stackPanel->HorizontalAlignment= Windows::UI::Xaml::HorizontalAlignment::Center;
auto myMethodButton = ref new Button();
myMethodButton->Content= “myMethod”;
myMethodButton->Click += ref new Windows::UI::Xaml::RoutedEventHandler(this, &MainPage::myMethod);
stackPanel->Children->Append( myMethodButton );
Per the docs on migrating C++/CX code to C++/WinRT:
I think it would be:
using namespace Windows::UI::Xaml::Controls;
// depending on the class this will be stack allocated but here it will be a nullprt
// remove ref new calls default constructor
auto stackPanel = StackPanel();
//if no default contstructor call:
StackPanel stackPanel = nullptr;
// this will be a property … use ‘.’ instead of ‘->’
stackPanel.HorizontalAlignment= Windows::UI::Xaml::HorizontalAlignment::Center;
auto myMethodButton = Button();
// if no default contstructor use:
// Button myMethodButton = nullptr;
myMethodButton.Content= “myMethod”;
//myMethodButton.Click += ref new Windows::UI::Xaml::RoutedEventHandler(this, &MainPage::myMethod);
// a bit more complicated but it’s explained in the guide, we want a lambda passeed in here (new wave functor)
myMethodButton::Click([=] (auto const &&, auto const &&)
{
});
stackPanel.Children.Append( myMethodButton );
Not entirely sure this would work, but I’m open to help and try to fix too since I’m learning as well.
Close, but are few changes (written off the top of my head so not compiled):
using namespace winrt::Windows::UI::Xaml;
using namespace winrt::Windows::UI::Xaml::Controls; // Add the winrt:: namespace
StackPanel stackPanel;
stackPanel.HorizontalAlignment (HorizontalAlignment.Center); // Property set call of enum value
Button myMethodButton;
myMethodButton.Content (“myMethod”); // Property set
myMethodButton::Click([=] (auto const &&, auto const &&)
{
});
stackPanel.Children().Append( myMethodButton ); // Children is a propget – needs ()
Thanks Brent!
Note that you can actually simplify the event registration a bit more. As the handler is a separate method already, you don’t really need the lambda. You can write this:
myMethodButton.Click ( { this, &MainPage::myMethod } );
I’ve always compiled ISO C++ projects with MSVC++ natively as well as g++/DragonFlyBSD cross-compilation. Kenny sometimes mentions the library is usable with Clang. As the final product of native WinRT app is appxupload bundle ready for Windows Store Certification Kit testing, is the sequence for getting these for deliverable submission from Clang tooling to distribution channel outlined somewhere?
Specifically /ZW was required by MSVC linker to use WinMD, then which are the clang counterpart arguments?
The thought of throwing all sorts of tools other than proprietary Microsoft toolchain also at my C++ code for WinRT app sure is motivating for making releases aggressively, even if the final packages are made with MSVC only.
I think you have focused on the wrong thing. Clang wasn’t changed in any way to read the WinMD files, these metadata files were converted to a format that C++ compilers could easily read, C++ header files. So there is no options needed to get Clang to do anything, you just have to include the headers provided and the compiler will not have to access the WinMD file at all. This also goes for Visual C++, so you don’t have to use the C++/CX extension and the /ZW command line option.
As for how to get the appx related things with Clang? I haven’t tried myself, but considering the fact that the whole system doesn’t care as long as your exe and related files are in the right place, then I can’t see any major changes for applications that just consume components. At worst you may be forced to generate the WinMD file for your component manually using midl and mdmerge, but these are part of the Windows SDK anyway.
Hi! I could not see how can I create a UWP-compatible component in C++/WinRT which expose some class and consume it in UWP application written in C#. In other words, is there available any sample how to create class in C++/WinRT, then instantiate and call its methods in other UWP C#-project. Thank you! | https://blogs.msdn.microsoft.com/vcblog/2016/10/13/cwinrt-available-on-github/ | CC-MAIN-2017-13 | refinedweb | 1,636 | 59.84 |
You are given a list of numbers in a textfile. These numbers are from 1 to 10000000.
There are some numbers missing from the sequence.
How would find the missing numbers?
You are given a list of numbers in a textfile. These numbers are from 1 to 10000000.
There are some numbers missing from the sequence.
How would find the missing numbers?
Hi,
Here which i have taken few missing numbers from 1 to 10.
scala> val num = sc.parallelize(List(1,3,5,9,10))
num: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[25] at parallelize at :21
scala> val maxvalue = num.max()
maxvalue: Int = 10
scala> val fdata = sc.parallelize(1 to maxvalue).subtract(num)
fdata: org.apache.spark.rdd.RDD[Int] = MapPartitionsRDD[30] at subtract at :25
scala> fdata.collect
res14: Array[Int] = Array(4, 8, 2, 6, 7)
Thx,
Kiran
Hi Sandeep,
I have taken a sample of random numbers between 1 to 100 in text file using the sample function. File is saved as ‘mysample.txt’ in my home directory.
I wrote the below code to get the missing numbers in the sequence
Step1:
val myrdd = sc.textFile(“mysample.txt”).flatMap(_.split(",")).map(x=>x.toInt)
Step2:
def missnum(x:Int,y:Int):Int = {
import scala.collection.mutable.ArrayBuffer
import scala.io.Source
import java.io.FileWriter
var missing = ArrayBufferInt
val writer = new FileWriter(“output.txt”)
if((y-x)>1){
for(a<- x+1 to y-1){
missing += a;
writer.write(a)
}
return y;
}else{
return y;
}
}
Step3:
val missrdd = myrdd.reduce(missnum)
I am able to successfully execute this code and got the output.txt in my local directory. But this file is empty. Could you please help me to check why the output.txt file is empty and why it is not saving the results?
Thanks.
Here the assumption is that the reduce will be called always on adjacent values. In a distributed environment, it is never guaranteed that reduce will be called on adjacent values. So, the answer is going to be wrong.
Second, in distributed environment, the “output.txt” will be created parallely on all the nodes where the tasks are going to run.
Also, looks like you forgot to close the file, that’s why the output.txt might be empty.
def findMissing(xs: List[Int]): List[Int] = {
xs match {
case (a :: b :: tail) if (b - a != 1) => ((a + 1 until b) toList) ++ findMissing(tail)
case (a :: b :: tail) if (b - a == 1) => findMissing(tail)
case(a :: Nil) => Nil
case (Nil) => Nil
}
}
Can we do it like this. Working on to convert it to RDD but it seams not all operations are applicable in RDD.
Hi Sandeep,
Can you pls check if this makes sense.
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.functions.{col,sum,lag}
object entry {
def main(args: Array[String]): Unit = {
val spark: SparkSession = SparkSession
.builder()
.appName(“Weather Analysis”)
.config(“spark.master”, “local”)
.getOrCreate()
spark.sparkContext.setLogLevel(“ERROR”)
import spark.implicits._
val sc = spark.sparkContext
val rdd = sc.parallelize(List(1, 3, 5, 9, 10))
val w = Window.partitionBy().orderBy(“num”)
val df = rdd.toDF(“num”).withColumn(“prev_value”, lag(“num”,1).over(w))
//df.withColumn(“prev_value”, lag(df[“num”],1).over(w))
val x = df.filter(x => x.get(1) != null).map(x => (x.getInt(1)+1 until x.getInt(0)).toList).reduce( ++ )
println(x)
}
}
Output#:
List(2, 4, 6, 7, 8)
I doubt if this solution will work in distributed case as when we combine we need to find the previous element so result may not be correct. Your comments please. | https://discuss.cloudxlab.com/t/find-the-missing-numbers-in-sequence-using-spark-interview-question/346 | CC-MAIN-2019-13 | refinedweb | 608 | 62.64 |
Hide Forgot
Where it's failing is in calculating the frozen definition for all existing resources at the start of an update. There are several software deployments that reference {get_attr: [Compute, attributes, nova_server_resource]}. To calculate the frozen definition, all intrinsic functions must be resolved, and this one is resolving with an error. AIUI the patch improves the error message but does not result in the error being caught and handled anywhere, so the problem will still occur.
It's notable that getting the frozen definition generally uses the property values stored in the database at the time the resource was created or updated - so there are no intrinsic functions left to resolve, and we should never get into this situation. My best guess is that one of the software deployment group resources has never actually been created, and therefore never had its resolved properties stored. I can't see another reason that this error would crop up.
One possible way to fix this comes to mind: it's only necessary to calculate the frozen_definition for resources that are being updated in place, but the code currently does this for all existing resources. The problem should be avoided if we both:
* Remove the compute role from the templates altogether; and
* Change the code so that we don't calculate the frozen definition for resources that are going to be deleted in the update, like so:
diff --git a/heat/engine/update.py b/heat/engine/update.py
index 84f203664c..0ae1b647fe 100644
--- a/heat/engine/update.py
+++ b/heat/engine/update.py
@@ -39,7 +39,8 @@ class StackUpdate(object):
self.rollback = rollback
self.existing_snippets = dict((n, r.frozen_definition())
- for n, r in self.existing_stack.items())
+ for n, r in self.existing_stack.items()
+ if n in new_stack)
def __repr__(self):
if self.rollback:
The deployment was fixed by restoring both the heat and neutron database. Still waiting to here from the scale out. | https://partner-bugzilla.redhat.com/show_bug.cgi?id=1600391 | CC-MAIN-2020-10 | refinedweb | 320 | 56.25 |
Oil prices have been
very
volatile on the upside. However, oil prices are nothing compared to the
natural
gas (NG) price roller coaster. Why is NG now selling for about
$7/million Btu
(or Mcf, 1,000 cubic ft) when just a few weeks ago it was over $16?
Given the
short supply caused in part by hurricanes in the Gulf of Mexico and
strong
demand, some analysts were convinced that the $20 NG would be common on
the US
East Coast no later than Christmas Eve 2005. Of course, that didn't
happen.
Blame or credit warmer weather, NG prices fell.
So
what are the forces in play here? We believe that price is no longer
the defining
issue for the NG market. Supply is. And supply issues are
causing major price fluctuations. Even small supply-side
changes-excess gas or
a shortage of gas, real or perceived by as little as 0.5%-are being
amplified
by the market. This is a function of the cost of bringing new NG
supplies
online, especially the real intractability of existing sources.
Market
psychology, perhaps irrational in either direction, has taken over.
Four
years ago, we
calculated the "equilibrium price" of NG for the US using data and
full-cycle economic analyses. The calculation was done to find the
required
price for a company to get a return on its investment. We used
"activation
index" -how many dollars are required to deliver one Mcfd NG plus the
observed production decline rates and the reported operating costs. For
the US
as a whole, the average equilibrium price was about $2.50, but such
average
pricing is of little use because local equilibrium prices ranged from
$l/Mcf to
$4.75/Mcf.
Calculating the national
equilibrium price is an enormous headache to gather the required data.
Yet, the
equilibrium price would probably not result in much difference in the
price. This
is why, four years ago, we said that if anybody can bring liquefied
natural gas
(LNG) in the US for $3.50/Mcf would find a very inviting market share.
Several
companies acted on this advice.
Nothing shows the
maturity of the US oil and gas business than the hopelessness of
substantially
increasing domestic production no matter how much drilling is done and
no
matter how much politicians exhort the virtues of "energy
independence." Maturity in petroleum production implies several factors
in
a combination of one, two or all three factors: reservoir pressure
decline,
water influx into the production zone or exploitation of less and less
geologically attractive zones. Simply stated,
it takes 200 to 250 successful oil wells in the continental US to equal
the
production of one average Saudi Arabian well.
For NG, the situation is
actually equally bleak if not worse. For the last four years, the
number of
rigs drilling for gas increased from a little less than 700 to almost 1
,200-a
70% increase. And yet, NG production has remained flat to slightly
declining.
The geological and
physical requirements for increased production are simply no
longer there. The
increase in drilling activity, fueled by the recent unprecedented NG
price
increases, is barely slowing down the inevitable decline of domestic
production.
So
what does this mean for gas users and investors? Get used to
volatility.
Now that NG prices are declining, we believe they could fall yet
further. But
don't be surprised if NG prices increase to $16+ if we have a hot
summer and/
or a cold winter. This volatility will continue until the US begins
receiving
on a regular daily doses-several billion cubic feet (Bcf)-of LNG.
Importing LNG
is the only answer to US' predicament but the solution is at least two
years
away.
The UK, the world's other
major deregulated gas market, is experiencing similar
problemsdeclining
domestic production and how to secure supply in advance of completion
of major
import facilities. | http://www.lngplants.com/LNG_World_2004.html | crawl-002 | refinedweb | 651 | 54.63 |
of an OS plumber
The majority of GNU/Linux and Unix shells are not designed for extensibility or embeddability. The current exception is the 1993 version of the Korn Shell (ksh93) which includes support for runtime linking of libraries and custom builtins and accessing shell internals.
It is very difficult, however, to find good information or examples of how to implement ksh93 custom builtins. The source code to ksh93 has virtually no comments and the supplied documentation is extremely terse and often conflicts with other sections of the documentation or the source code itself.
This post is an attempt to show by example how to write your own simple ksh93 custom builtins. You are expected to be reasonably proficient in the C language and the use of the gcc compiler/linker. However, before we start, it is important to note that custom builtins can only be implemented on operating systems that support dynamic loading of shared objects into the current running process since, internally, a custom builtin is invoked as a C routine by ksh93. Fortunately most modern operating systems provide this feature via the dlopen(), dlsym(), dlerror() and dlclose() APIs.
Why bother implementing ksh93 custom builtins? The answer lies in fact that custom builtins are inherently much faster and require less system resources than an equivalent routine which uses other standalone commands and utilities. A custom builtin executes in the same process as the shell, i.e. it does not create a separate sub-process using fork() and exec(). Thus a significant improvement in performance can occur since the process creation overhead is eliminated. The author of ksh93, Dave Korn, reported that on a SUN OS 4.1 the time to run wc on a file of about 1000 bytes was about 50 times less when using the ksh93 wc built-in command.
There are two ways to create and install ksh93 custom builtins. In both cases, the custom builtin is loaded into ksh93 using the ksh93 builtin command. Which method you use is entirely up to you. The easiest way is to write a shared library containing one or more functions whose names are b_xxxx where xxxx is the name of the custom builtin. The function b_xxxx takes three arguments. The first two are the same as for the main() function in a C program. The third argument is a pointer to the current shell context. The second way is to write a shared library containing a function named lib_init(). This function is called with an argument of 0 when the shared library is loaded. This function can add custom builtins with the sh_addbuiltin() function.
I believe that the best way to learn about a new feature is to actually write code which uses the new feature. Following are two relatively simple examples which demonstrate the basics of how to write custom builtins. These examples were written and tested using ksh93 version M 93s+ 2008-01-31 and CentOS 5.0 but should compile and work on any modern Unix or GNU/Linux operating system.
Example 1 Write a simple custom builtin called hello which takes one argument and outputs “hello there ” to stdout.
#include <stdio.h>
int
b_hello(int argc, char *argv[], void *extra)
{
if (argc != 2) {
fprintf(stderr,"Usage: hello arg\n");
return(2);
}
printf("Hello there %s\n",argv[1]);
return(0);
}
Next compile hello.c and create a shared library libhello.so containing the hello builtin.
$ gcc -fPIC -g -c hello.c
$ gcc -shared -W1,-soname,libhello.so -o libhello.so hello.o
Some operating systems (Solaris Intel for example) do not require you to build a shared library and support the direct loading of hello.o. However the majority of operating systems require you to create a shared library as we have done for this example. Note the use of the –fPIC flag to indicate position independent code should be produced. Unlike relocatable code, position independent code can be copied to any memory location without modification and executed.
To actually use the hello custom builtin, you must make it available to ksh93 using the ksh93 builtin command.
$ builtin -f ./libhello.so hello
If you are unfamiliar with the builtin command, you can type builtin –man or builtin –help for more information or read the ksh93 man page.
You can then use the hello custom builtin just like you would use any other command or shell feature:
$ hello joe
Hello there joe
$ hello "joe smith"
Hello there joe smith
$ hello
usage: hello arg
$
Note that the hello custom builtin will show up when you list builtins using the builtin command.
$ builtin
....
hello
....
but not when you list special builtins using the builtin –s option.
To remove the hello builtin, use the builtin –d option.
$ builtin -d hello
$ hello joe
/bin/ksh93: hello: not found [No such file or directory]
$
Removing a custom builtin does not necessarily release the associated shared library.
Internally hello is named b_hello() and takes 3 arguments. As previously discussed custom builtins are generally required to start with b_ (There is an exception which will be discussed in a later example.) The arguments argc and argv act just like in a main() function. The third argument is the current context of ksh93 and is generally not used as another mechanism, sh_getinterp(), is provided to access the current content.
Instead of exit(), use return() to terminate or return from a custom builtin. The return value becomes the exit status of the builtin and can be queried using $? A return value of 0 indicates success with > 0 indicating failure. If you allocate any resources such as memory, all such resources used must be carefully freed before terminating the custom builtin.
Custom builtins can call functions from the standard C library, the AST (Advanced Software Technology) libast library, interface functions provided by ksh93, and your own C libraries. You should avoid using any global symbols beginning with sh_, .nv_, and ed_ or BSH_ since these are reserved for use by ksh93 itself.
If you move libhello.so to where the shared libraries normally reside for your particular operating system, typically /usr/lib, you can load the hello custom builtin as follows
$ builtin -f hello hello
as ksh93 automatically adds a lib prefix and a .so suffix to the name of the library specified using the builtin –f option.
It is often desirable to automatically load a custom builtin the first time that it is referenced. For example, the first time the custom builtin hello is invoked, ksh93 should load and execute it, whereas for subsequent invocations ksh93 should just execute the hello custom builtin. This can be done by creating a file named hello as follows:
function hello
{
unset -f hello
builtin -f /home/joe/libhello.so hello
hello "$@"
}
This file must to be placed in a directory that is in your FPATH environmental variable. In addition, the full pathname to the shared library containing the hello custom builtin should be specified so that the run time loader can find this shared library no matter where hello is invoked.
There are alternative ways to locating and invoking builtins using a .paths file. See the ksh93 man page for further information.
Example 2 Uppercase the first character of a string.
#include <stdio.h>
#include <ctype.h>
int
b_firstcap(int argc, char *argv[], void *extra)
{
int c;
char *s;
if (argc != 2) {
fprintf(stderr, "usage: firstcap arg\n");
return(2);
}
s = argv[1];
c = *s++;
printf("%c%s\n", toupper(c), s);
return(0);
}
Assuming you created a library called libfirstcap.so and placed this library in the default directory for shared libraries you can load and use this custom builtin as follows.
$ builtin -f firstcap firstcap
$ firstcap joe
Joe
$ firstcap united
United
$
Custom builtins can be used to extend ksh93 in many useful ways just as Perl modules are used to extend Perl and Python modules are used to extend Python. To date this has not happened with ksh93. I believe that this is mainly due to the lack of good documentation on how to write custom builtins.
This post is but a brief introduction to the subject of ksh93 custom builtins. To really learn how to write custom builtins, you ahould download the ksh93 sources and study the code. Also read “Guidelines for writing ksh-93 built-in commands” (builtins.mm) which is located in the top-level directory of the ksh93 source tree.
Enter your email address | http://blog.fpmurphy.com/2008/11/korn-shell-secrets-11.html | CC-MAIN-2014-49 | refinedweb | 1,404 | 62.98 |
- Code: Select all
>>> def somefunc(s):
s[0]=22
>>> def test(s):
def helper(s):
somefunc(s)
s=s+[2,3]
return s+[3,4]
s=helper(s)
>>> a=[1,33,4,23]
>>> somefunc(a)
>>> a
[22, 33, 4, 23]
>>>#somefunc() works properly
>>> a=[1,33,4,23]
>>> test(a)
>>> a
[22, 33, 4, 23]
>>> a=[1,33,4,23]
>>> def helper(s):
somefunc(s)
s=s+[2,3]
return s+[3,4]
>>>#helper function taken out of test
>>> helper(a)
[22, 33, 4, 23, 2, 3, 3, 4]
So I created a function test that has a nested function helper. Test is supposed to modify list (s) but not return any value, although the inner nested helper function returns a value. However, when I called test(a), it seems like the nested helper function works partially by implementing somefunc(s), but ignores the rest of the body. There's nothing wrong with helper itself since when I took it out, the function works as intended. Can someone tell me what's wrong? It's especially odd to me that the helper function in test was partially implemented, not ignored or implemented all the way. Oh and I'm new to this forum so if any indenting doesn't look right, it's because my code's indentation won't copy over from IDLE so I have to manually press the space bar on all lines of code that needs to be indented. | http://www.python-forum.org/viewtopic.php?f=6&t=4760&p=6103 | CC-MAIN-2015-35 | refinedweb | 243 | 59.67 |
iscntrl() prototype
int iscntrl(int ch);
The
iscntrl() function checks if ch is a control character or not as classified by the currently installed C locale. By default, the characters with the codes from 0x00 to 0x1F and 0x7F are considered control characters.
There are 32 control characters in the ASCII character set, including null, line feed, start of text, backspace, tab etc.
The behaviour of
iscntrl() is undefined if the value of ch is not representable as unsigned char or is not equal to EOF.
It is defined in <cctype> header file.
iscntrl() Parameters
ch: The character to check.
iscntrl() Return value
The
iscntrl() function returns non zero value if ch is a control character, otherwise returns zero.
Example: How iscntrl() function works
#include <cctype> #include <iostream> using namespace std; int main() { char ch1 = '\t'; char ch2 = 'x'; iscntrl(ch1)?cout << ch1 << " is a control character":cout << ch1 << " is not a control character"; cout << endl; iscntrl(ch2)?cout << ch2 << " is a control character":cout << ch2 << " is not a control character"; return 0; }
When you run the program, the output will be:
is a control character x is not a control character | https://cdn.programiz.com/cpp-programming/library-function/cctype/iscntrl | CC-MAIN-2021-04 | refinedweb | 192 | 52.7 |
The FTP server provides a single entry point:
#include <ftpserver.h>
__externC int cyg_ftpserver_start( cyg_ftpserver *server );
This function starts an FTP server running using parameters defined
in the server argument. It should be called
from a thread with a stack with at least
CYGNUM_NET_FTPSERVER_STACK_SIZE bytes
available. Under normal circumstances this function will not
return, so the application should create a thread dedicated to the
server. There are examples of this in the test programs.
The server argument contains a number of
fields that the user may set to control the behaviour of the FTP
server.
This is a string giving the IP address on which the server will
listen. If not set this will default to listening on all
network interface, which is usually what is wanted. This option
is only useful if a target has more than one network interface
and the FTP server should only listen on one of them.
This defines the port number on which the server will
listen. Leaving this value unset, zero, will cause the server
to choose the default FTP port of 21.
This is the string that the server will use in its initial
response to a client connection. Leaving this NULL will cause
the server to use a default message: "Welcome to eCosPro FTP service.".
This string defines a filesystem pathname to the root directory
of the FTP server. Files will only be transferred to and from
this directory or any subdirectories. A NULL pointer here will
cause the server to use "/" as the root.
This defines the first port at which the server will create
passive data connections. It will try successive ports from
this value until a free port is found, limited to the following
20 ports. Leaving this value NULL will cause the server to
start from port 5000.
The normal idiom for use of the FTP server is to define the
cyg_ftpserver structure statically and to then call
cyg_ftpserver_start() with a pointer to
that. The following is a somewhat contrived example:
cyg_ftpserver_start()
#include <ftpserver.h>
//==========================================================================
static cyg_ftpserver ftp_server =
{
.port = 2121, // Listen on port 2121
.root = "/fatfs/ftp", // FTP to/from here
.greeting = "Welcome to Fubar FTP service.", // Welcome string
.data_port = 40000 // Move data ports to 40000+
};
//==========================================================================
static void ftpd(CYG_ADDRWORD p)
{
init_all_network_interfaces();
cyg_ftpserver_start( &ftp_server );
}
//==========================================================================
#define STACK_SIZE CYGNUM_NET_FTPSERVER_STACK_SIZE
static char stack[STACK_SIZE] CYGBLD_ATTRIB_ALIGN_MAX;
static cyg_thread thread_data;
static cyg_handle_t thread_handle;
void start_ftpd_thread(void)
{
cyg_thread_create(10, // Priority
ftpd, // entry
0, // entry parameter
"FTP test", // Name
&stack[0], // Stack
STACK_SIZE, // Size
&thread_handle, // Handle
&thread_data // Thread data structure
);
cyg_thread_resume(thread_handle); /* Start it */
}
The defaults for the configuration parameters are such that
leaving them all zero or NULL will cause the server to configure
itself on the standard port serving files to/from the root of the
filesystem.
The default server operates to and from a directory in a
filesystem, in the same way that most FTP servers
operate. However, not all embedded systems have filesystem
support. To allow such systems to provide an FTP service, all file
access operations go through a set of callback functions in the
cyg_ftpserver structure. The user can define these to
redirect file I/O operations to other devices such as memory
buffers or flash memory regions.
The callback interface defines a type,
ftpserver_cookie that is passed to the callback
functions. It is a word or pointer sized value and is typically
used by the callback functions to contain a data structure
pointer, or an index into a table that uniquely identifies an open
file.
The callbacks for a notional example
interface are defined as follows:
Called to open a file for data transfer. The
path is a fully rooted path formed from
the root field of the server
configuration plus the client supplied path. The
write argument is true if the file is to
be opened for writing and false if for reading. If successful
the function may store a private value to
*cookie.
root
If the file is opened successfully this function should return
FTPSERVER_OK. If the file cannot be opened
for reading it should return FTPSERVER_NO_FILE.
If the file cannot be written to or created it should return
FTPSERVER_NOT_ALLOWED.
Called to write data to the file. The
cookie argument is the value stored by
the open callback. Arguments buf and
size define the data to be written.
If the data is successfully written this function should return
FTPSERVER_OK. If any error occurs it should
return FTPSERVER_WRITE_FAIL.
Called to read data from the file. The
cookie argument is the value stored by
the open callback. Arguments buf and
*size define a buffer into which the
data should be stored, *size should be
updated with the amount of data written to the buffer. If no
more data is available, *size should be
set to zero.
If the function is successful it should return
FTPSERVER_OK. If any error occurs it should
return FTPSERVER_READ_FAIL.
Called to close the file for further data transfer. The
cookie argument is the value stored by
the open callback. After this call the cookie value will not be
used in further calls.
This function should return FTPSERVER_OK
under all circumstance, there are no error conditions of
interest to the FTP server.
This function is called to authenticate a user ID and password
supplied by the client. The FTP server will only request a
password, by returning a 331 response, if a user supplied
authentication function is installed.
If the user and password are accepted, this function should
return FTPSERVER_LOGIN_OK; it should return
FTPSERVER_BADUSER if they do not.
Called to delete a file. The path is a
fully rooted path formed from the root
field of the server configuration plus the client supplied path.
If the file is deleted successfully this function should return
FTPSERVER_OPDONE. If the file cannot be deleted
or is not found, FTPSERVER_NO_FILE should be
returned.
Extending the previous example, the cyg_ftpserver
might look like this:
static cyg_ftpserver ftp_server =
{
.port = 2121, // Listen on port 2121
.root = "/fatfs/ftp", // FTP to/from here
.greeting = "Welcome to Fubar FTP service.", // Welcome string
.data_port = 40000, // Move data ports to 40000+
.open = example_open,
.read = example_read,
.write = example_write,
.close = example_close,
.auth = example_auth,
.delete = example_delete,
};
The FTP server package contains a number of configuration options:
This option defines the size of the buffer used for data
transfers. Buffer size is a tradeoff between memory use and
transfer speed. The default should be a reasonable compromise
between these two.
This option defines the size of the buffer used for storing the
user name supplied by the client.
This option defines the size of the buffer used for storing the
password supplied by the client. The default reflects the habit
of using a user's email address as a password for anonymous
FTP.
This option defines the timeout applied to control streams. If
after this number of seconds the client has not interacted with
the server, the connection is closed down. Since the server
only allows a single client at a time, any client that fails to
close a control stream down will block it for others.
This option defines the timeout applied to data streams. If
after this number of seconds the client has not transferred
data to or from the server, the connection is closed
down. Clients are expected to use a data connection immediately
after it is created so this timeout can be considerably smaller
than the control timeout. | http://www.ecoscentric.com/ecospro/doc/html/ref/net-ftpserver-api.html | crawl-003 | refinedweb | 1,223 | 64.2 |
02 February 2011 05:00 [Source: ICIS news]
SINGAPORE (ICIS)--Japanese producer Kuaray said on Wednesday its nine-month net profit surged 85% year on year to yen (Y) 22.4bn ($275m), on the back of an 11.4% increase in sales.
Sales for the period ending December stood at Y270.4bn from Y242.7bn in the previous corresponding period, it said in a statement.
Kuraray said demand for its products in Europe and the ?xml:namespace>
But the operating environment had remained unpredictable due to weakness in the Japanese economy, as well as the rapid appreciation of the yen, it said.
($1 = Y81. | http://www.icis.com/Articles/2011/02/02/9431463/japans-kuraray-nine-month-net-profit-surges-85-on-better-sales.html | CC-MAIN-2013-20 | refinedweb | 104 | 67.76 |
I have Matplotlib 1.1.0, and am doing point picking (using the OO approach to Matplotlib, and embedded in wxPython). My relevant code is as follows:
#connect the pick event to the pick event handler:
self.cid = self.canvas.mpl_connect(‘pick_event’, self.on_pick)
#This is the relevant part of the pick event handler:
def on_pick(self, event):
if isinstance(event.artist, Line2D):
ind = event.ind print 'ind is: ', str(ind)
This had been working in some cases, but I’ve found a case in which it appears to be giving me a value for ind that doesn’t make sense. For example, I have a plot with two lines on it (and two y axes), each with over 50 points. When I pick one of the points right near the end, I expect the ind here will be about 50. However, it prints ind is: 3. In other words, the wrong index value. This is a serious issue for me, because I then use that index to look up information about that point.
What could be going on here?
Thanks,
Che | https://discourse.matplotlib.org/t/event-ind-in-point-picking-gives-wrong-number/18207 | CC-MAIN-2022-21 | refinedweb | 182 | 82.65 |
Zulip Chat Archive
Stream: PR reviews
Topic: polynomial.eval2_smul
Bolton Bailey (Feb 01 2021 at 04:40):
Looking at the code for polynomial.eval2_smul
@[simp] lemma eval₂_smul (g : R →+* S) (p : polynomial R) (x : S) {s : R} : eval₂ g x (s • p) = g s • eval₂ g x p := begin simp only [eval₂, sum_smul_index, forall_const, zero_mul, g.map_zero, g.map_mul, mul_assoc], -- Why doesn't `rw [←finsupp.mul_sum]` work? convert (@finsupp.mul_sum _ _ _ _ _ (g s) p (λ i a, (g a * x ^ i))).symm, end
Shouldn't the lemma be
@[simp] lemma eval₂_smul (g : R →+* S) (p : polynomial R) (x : S) {s : R} : eval₂ g x (s • p) = g s * eval₂ g x p := ...
As both
g s and
eval₂ g x p are in S
Bolton Bailey (Feb 01 2021 at 04:51):
Similar thing with polynomial.eval_smul
Johan Commelin (Feb 01 2021 at 05:49):
@Bolton Bailey (Aside: is this part of an existing PR? If so, you can write
#1234 in the title of the thread, and it will create a link to PR 1234.)
I think the reason for using
\bu in both places is for some sort of "regularity" in the operations on both sides. But maybe in practice using
* on the RHS would be better. I don't have a strong opinion.
Bolton Bailey (Feb 01 2021 at 05:57):
It's not part of an existing PR, I was going to test the air here before writing one.
After wondering for a few days why the Infoview in my project was showing a coercion operation when I didn't think there should be one it seems like this is the reason. With that in mind, I think that the
* is more natural, but I'll try to figure out if changing it fixes the issue.
Johan Commelin (Feb 01 2021 at 06:03):
Aha, but then you should probably use a different stream. (Not too big of an issue.) We try to use this stream only for discussion about explicit PRs. (See the other thread titles, they all have the format
#1234 pr name.
Johan Commelin (Feb 01 2021 at 06:03):
But where is the coercion? Because there shouldn't be a coercion either.
Bolton Bailey (Feb 01 2021 at 08:42):
Thanks, in the future I'll open a PR before posting, and I'll make a PR for this as soon as I have time.
Here's a MWE of my case, where I am trying to reason about a polynomial that has been converted to a mv_polynomial using eval_2.
import data.polynomial.basic import data.mv_polynomial.basic section universe u parameter {S : Type} parameter {F : Type u} parameter [field F] lemma foo (s : S) (i : F) (p : polynomial F) : polynomial.eval₂ mv_polynomial.C (mv_polynomial.X s) (i • p) = i • polynomial.eval₂ mv_polynomial.C (mv_polynomial.X s) (p) := begin rw polynomial.eval₂_smul, -- ⇑mv_polynomial.C i • polynomial.eval₂ mv_polynomial.C (mv_polynomial.X s) p = -- i • polynomial.eval₂ mv_polynomial.C (mv_polynomial.X s) p end end
Eric Wieser (Feb 01 2021 at 08:44):
Where's the coercion?
Johan Commelin (Feb 01 2021 at 08:44):
Well, we enjoy discussions before PRs as well (-; But we put them in #general or #maths . (But no worries... it's not a big deal. I was just confused about whether I missed a PR that you were talking about.)
Eric Wieser (Feb 01 2021 at 08:45):
Are you talking about the function coercion right at the start? That's just how bundled functions work, and nothing to do with this lemma
Eric Wieser (Feb 01 2021 at 08:45):
Presumably a zulip admin can move this thread
Bolton Bailey (Feb 01 2021 at 09:03):
If that's how bundled functions look that's fine, but it's a bit surprising since nowhere in the code I write myself do I have to put
⇑ before
mv_polynomial.C when calling it as a function.
It still seems to me that it should be
* in the lemma - the
\smul is on the left hand side because it has to be, but an smul on the right hand side is not what I expected. You can see the original author was confused as to why they couldn't use
rw [←finsupp.mul_sum] - this indeed closes the lemma in the
* version.
Last updated: May 06 2021 at 11:23 UTC | https://leanprover-community.github.io/archive/stream/144837-PR-reviews/topic/polynomial.2Eeval2_smul.html | CC-MAIN-2021-21 | refinedweb | 734 | 71.65 |
I was just trying a simple code:
import sys
def main():
print "this is main"
return "string1"
if __name__ == "__main__":
sys.exit(main())
this is main
string1
Process finished with exit code 1
string1
this is main
Process finished with exit code 1
sys.exit takes the return value of
main() and produces it as the error code of the application. The value should usually be numeric, though Python is being a bit tricky here.
From the documentation of sys.exit:.
So what may be happening is a race between flushing of
stdout (for
stderr as specified above.
I suggest you try to flush
stdout after the
sys.stdout.flush) and see if you get consistent output that way. | https://codedump.io/share/zUiHVagUvq51/1/not-understanding-return-behavior-in-python | CC-MAIN-2017-09 | refinedweb | 119 | 74.08 |
A matrix library for Elm, written in pure elm! This library aims to be a reasonably complete suite of linear algebra tools.
Some highlights of this library include generic sized matrices, inverses, transposes, LU decomposition and more!
It's very easy to get started.
import Matrix as Mt identity = Mt.eye 3 -- make a 3x3 identity matrix identity |> Mt.debugPrint -- view the matrix in the repl identity |> Mt.toString -- view the matrix as a formatted string with newlines -- return the matrix as a list of lists: -- [[1, 0, 0], [0, 1, 0], [0, 0, 1]] identity |> Mt.to2DList -- return the matrix as a flat list -- [1, 0, 0, 0, 1, 0, 0, 0, 1] identity |> Mt.toFlatList -- multiply a matrix [[1, 1, 1], [2, 2, 2], [3, 3, 3]] and a column vector [4, 5, 6] a = Mt.mat [[1, 1, 1], [2, 2, 2], [3, 3, 3]] b = vec [4, 5, 6] result = Mt.mul a b
Check the documentation for the full list of features.
TODO: I would appreciate any help! | https://package.frelm.org/repo/1389/1.0.0 | CC-MAIN-2019-09 | refinedweb | 173 | 75.5 |
Standard C++ Library Copyright 1998, Rogue Wave Software, Inc.
greater_equal - A binary function object that returns true if its first argument is greater than or equal to its second
#include <functional> template <class T> struct greater_equal ; : binary_function<T, T, bool> { bool operator() (const T&, const T&) const; };
greater_equal is a binary function object. Its operator() returns true if x is greater than or equal to y. You can pass a greater_equal object to any algorithm that requires a binary function. For example, the sort algorithm can accept a binary function as an alternate comparison object to sort a sequence. greater_equal would be used in that algorithm in the following manner: vector<int> vec1; sort(vec1.begin(), vec1.end(),greater_equal<int>()); After this call to sort, vec1 is sorted in descending | http://docs.oracle.com/cd/E19205-01/820-4180/man3c++/greater_equal.3.html | CC-MAIN-2017-09 | refinedweb | 130 | 53.61 |
Tim Berners-Lee has a blog that is, more often than not, worth reading. Certainly that has been the case over the weekend as the inventor of the World Wide Web has been talking about reinventing HTML.
Referring to the W3C HTML group Berners-Lee admits that it is important to have real developers on the ground “involved fully with the development of HTML” and just as important to have browser client developers involved and committed. In his all encompassing vision, Berners-Lee goes on to say that users and user companies and makers of related products should also be involved. Which all starts to sound like one of those committees that is so large and diverse that nothing ever gets done.
But the problem that Berners-Lee and the W3C HTML group face, rather than nothing getting done is the majority of folk out in the real world accepting what they have done and adopting it as the norm.
Take XML, for example. Berners-Lee admits that with hindsight “the attempt to get the world to switch to XML, including quotes around attribute values and slashes in empty tags and namespaces all at once didn't work”. This was because the HTML-generating public did not want to move, did not see the value in moving, did not even know a move was available because their browser clients continued to function just nicely thank you very much. Sure, some large communities made the change and Berners-Lee insists they are “enjoying the fruits of well-formed systems” but these are in the minority.
So what was the problem, does Berners-Lee think? Simple, the all or nothing approach to maintaining HTML. “It is important to maintain HTML incrementally, as well as continuing a transition to well-formed world, and developing more power in that world” he states. And the solution is a new W3C HTML group which will be chartered to produce those incremental improvements, in parallel with XHTML, in fact it will work on both together it seems. XHTML2 will get a new working group, however, to ensure that there is no dependency of HTML work on the XHTML2 work.
First to face the new group would appear to be forms, or rather to extend HTML forms so that they can be thought of as XForm equivalents. The goal being to “have an HTML forms language which is a superset of the existing HTML language, and a subset of a XForms language with added HTML compatibility” Berners-Lee explains.
But wait, there is more. Another thing Berners-Lee wants to change is the validator which everyone would probably agree is of value to both user and developer alike, the latter in helping with standards deployment of course. Noting that W3C have just purchased new server hardware, paid for out of the Supporters program fund, Berners-Lee goes on to outline exactly what he wants to see happen to the validator. “I'd like it to check (even) more stuff, be (even) more helpful, and prioritize carefully its errors, warning and mild chidings. I'd like it to link to an explanations of why things should be a certain way.“ Which all sounds very good indeed, although there are no timescales mentioned in these meanderings.
Don’t think this is pie in the sky blog spouting either, remember this is Tim Berners-Lee making the comments here, holder of enormous power within the web standards development community and rightly so. Let’s just hope that his vision of the new collaboration via the HTML group being “one of the crown jewels of web technology” bears fruit, and sooner rather than later.
After all, nobody can deny that in recent years HTML development has become rather torpid, and the value and authority of the W3C has suffered as a direct result. | https://www.daniweb.com/programming/software-development/news/218181/html-the-next-generation | CC-MAIN-2017-09 | refinedweb | 641 | 55.68 |
public class ClassNonStatic // This is our non-static class { public static string staticString() // This is our static string method inside the non-static class. We can not create an instance of this method but we can call it directly. - Compilable { Console.WriteLine("I am allowed to be in non-static and static classes. And Can be used here."); return "I am allowed to be in non-static and static classes. And Can be used here."; } public string nonStaticString() // This is our non-static string method. - Compilable { Console.WriteLine("I am allowed to be in non-static classes. And Can be used here. Instance methods can also be used here."); return "I am allowed to be in non-static classes. And Can be used here. Instance methods can also be used here."; } } public static class ClassStatic // This is our static class { public static string staticString() // This is our static string method inside the static class. - Compilable { Console.WriteLine("I am a static string method and am allowed to be here. And Can be used here."); return "I am a static string method and am allowed to be here. And Can be used here."; } public string nonStaticString() // This is our non-static string method. - Not compilable { Console.WriteLine("I am not allowed to be here. And Can Not be used here. Instance members have no place here."); return "I am allowed to be here. And Can be used here. Instance members have no place here."; } }
Do you already notice any inconsistencies? If not I will show you in the blow screenshot ::
Instance members such as this nonStaticString can not be declared in a static class.
Lets say for arguments sake, we have a button and a simple windows form. We will put the following code inside a button and execute the below code from a click event. But which code lines are executable?
ClassNonStatic CallNonStaticInstance = new ClassNonStatic(); // Working logic :: You can create an instance of a non-static class. ClassStatic CallToStaticInstance = new ClassStatic(); // Broken logic :: You can not create an instance of a static class. CallNonStaticInstance.nonStaticString(); // Working logic :: We can call an instance of the nonStaticString() method. CallNonStaticInstance.staticString(); // Broken logic :: We can not call an instance of the staticString() method even though its in a non static class, this is because the method itself is static. You can't create an instance of a static method. ClassNonStatic.staticString(); // Working Logic :: We can call the staticString() member of the non-static class directly. ClassNonStatic.nonStaticString(); // Broken logic :: We can not call the nonStaticString() method member of the ClassNonStatic directly, as your IDE should tell you an instance of the object/method is required ([url=""]Object reference[/url]). // Now lets try the static class and see what is different and how we can utilize its member methods, and what works and what doesn't... Lets start by working with the instance we defined above. CallToStaticInstance.nonStaticString(); // Broken Logic :: You can create an instance of the class but can not access the nonStaticString() method, because it has no business being an instance member in a static class. CallToStaticInstance.staticString(); // Broken Logic :: You can not create an instance of this staticString() method member of ClassStatic because it is static. ClassStatic.staticString(); // Working Logic :: You can call this staticString() method member of ClassStatic directly. ClassStatic.nonStaticString(); // Broken Logic :: You can not call this nonStaticString() member of the ClassStatic class, because it has no business being in a static class in the first place.
In this screenshot, the underlying red squiggles under the code are telling you that the logic wrote will cause runtime problems and need addressing and most importantly rewriting. But what is restricting us from writing our code as described above? Simply put; your declaration type. Anything deriving the word static can't be instantiated as new. However, you may call it directly by is class name. Let me explain...
The static keyword in the C# programming language allows you to define static classes and static members appropriately. A static class is similar to a class which is both abstract/sealed. Declaring a class as static, you should define it with the static keyword in the class declaration. When the static keyword is used on a class declaration, it forces the class to have limited functionality and it cannot be instantiated or inherited and all of the members of that class are also static. Under no circumstances would you define or place non-static instance members in a static class. Statics don't offer any behaviour patterns, as I like to say they hold run'n'forget code, and so there is no point in allowing a static class to be inherited.
As you can see, non-static classes can be instantiated by creating a new instance of them.
And static classes cannot be instantiated i.e, ClassStatic CallToStaticInstance = new ClassStatic();.
All non-static classes can have instance method and static methods respectively. If you're creating static classes, you should note; they can only have static methods, and non-static members do not belong inside them. Instance methods must be called by instantiating a new instance of the class, and not the class itself. If you're calling static methods, you must call them on the class itself, and not on the new instances of the class. There are ways you can use delegates on classes to derive a certain functionality from static classes and also to use delegates in-place of interfaces when working with static classes, but we will need to draw up a new article on that one later on. But for this very basic tutorial, I will park this one here and perhaps do a part two of this :: Using delegates instead of interfaces with statics :: Advantages / Disadvantages.
You may also find my other tutorial on multithreading worth glancing over, as it holds some relevance to this topic, in regards; how to access methods, properties which belong to UI threads or classes, and exchanging information between classes. | https://www.dreamincode.net/forums/topic/413761-c?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+dic_featured+%28Dream.In.Code%29 | CC-MAIN-2019-18 | refinedweb | 999 | 56.76 |
Code. Collaborate. Organize.
No Limits. Try it Today.
Although the C# language has been used quite successfully in many kinds of projects, it still remains to be proven proficient for scientific computing. Questions remain as to whether or not C# can measure up to the likes of FORTRAN and C++ for scientific and mathematical projects.
Arithmetic and algebra on complex numbers is important in many fields of science and engineering. Even though C# does not support an intrinsic complex number data type, it doesn't stop you from creating your own. You can do so using a struct, which has value semantics. The purpose of this article is to present my attempt to fashion a complex arithmetic class for C#.
struct
The struct Complex is completely contained within the namespace ComplexMath in the file Complex.cs. There are three separate program files included in the download as well as a documented help file for the project. You can run the program either by using the ComplexMath.dll reference, or by using the ComplexMath library code directly by simply adding the Complex.cs file to a project. You must, in either case, add the header using ComplexMath; to the main project file. If you decide to go the DLL route, first build the library (DLL) by running the CompexMath.sln file from which you can generate two ComplexMath.dll files, one each in bin/Release and bin/Debug.
struct Complex
ComplexMath
ComplexMath
using ComplexMath;
Your test program should look something like the one below which briefly demonstrates many of the capabilities of the library:
using System.Collections.Generic;
using System.Text;
using ComplexMath;
namespace TestLib
{
class Program
{
static void Main(string[] args)
{
Complex z1, z2, z3; // instantiation
z1 = new Complex(1.0, -2.0);
z2 = new Complex(-3.0, -5.0);
z3 = new Complex(0.292342, -0.394875);
Console.WriteLine("instantiated complex numbers:");
Console.WriteLine(string.Format("z1 = {0}", z1));
Console.WriteLine(string.Format("z2 = {0}", z2));
Console.WriteLine(string.Format("z3 = {0}", z3));
// random complex numbers
z1 = Complex.Random();
z2 = Complex.Random();
z3 = Complex.Random();
Console.WriteLine("random generated:");
Console.WriteLine(string.Format("z1 = {0}", z1));
Console.WriteLine(string.Format("z2 = {0}", z2));
Console.WriteLine(string.Format("z3 = {0}", z3));
Console.WriteLine("basic properties:");
Console.WriteLine(string.Format
("z1.real = {0} z1.imag = {1}", z1.real, z1.imag));
Console.WriteLine(string.Format
("complex conjugate of z1 = {0}.", z1.Conjugate));
Console.WriteLine(string.Format
("complex modulus of z1 = {0}.", z1.Modulus));
Console.WriteLine(string.Format
("complex argument of z1 = {0}.", z1.Argument)); // operators
Console.WriteLine("operators:");));
// transcendental functions
Console.WriteLine("transcendental functions:");
z3 = Complex.Sin(z1); Console.WriteLine(string.Format("Sin(z1) = {0}", z3));
z3 = Complex.Cos(z1); Console.WriteLine(string.Format("Cos(z1) = {0}", z3));
z3 = Complex.Tan(z1); Console.WriteLine(string.Format("Tan(z1) = {0}", z3));
z3 = Complex.Sinh(z1);
Console.WriteLine(string.Format("Sinh(z1) = {0}", z3));
z3 = Complex.Cosh(z1);
Console.WriteLine(string.Format("Cosh(z1) = {0}", z3));
z3 = Complex.Tanh(z1);
Console.WriteLine(string.Format("Tanh(z1) = {0}", z3));
z3 = Complex.Exp(z1); Console.WriteLine(string.Format("Exp(z1) = {0}", z3));
z3 = Complex.Log(z1); Console.WriteLine(string.Format("Log(z1) = {0}", z3));
z3 = Complex.Log10(z1);
Console.WriteLine(string.Format("Log10(z1) = {0}", z3)); // roots
Console.WriteLine("roots:");
z3 = Complex.Sqrt(z1);
Console.WriteLine(string.Format("Sqrt(z1) = {0}", z3));
Console.WriteLine("k 4th roots:");
for (long k = 0; k < 4; k++)
{
z3 = Complex.NthRoot(z1, 4, k);
Console.WriteLine(string.Format("NthRoot(z1, 4, {0}) = {1}",k, z3));
} Console.WriteLine("the five 5th roots of unity:");
Complex z = new Complex(1.0, 0.0);
for (long k = 0; k < 5; k++)
{
z3 = Complex.NthRoot(z, 5, k);
Console.WriteLine
(string.Format("{0}th 5th root of unity = {1}", k, z3));
}
// powers
Console.WriteLine("powers:");
int n = 7;
z3 = Complex.Pow(z1, z2);
Console.WriteLine(string.Format("Complex.Pow(z1, z2) = {0}", z3));
z3 = Complex.Pow(z1, n);
Console.WriteLine(string.Format("Complex.Pow(z1, {0}) = {1}", n, z3));
// display
Console.WriteLine("display:");
z1.Show();
z1.ShowPolar();
Console.WriteLine(string.Format("polar form of z1 = {0}.", z1.Polar()));
// debug tracing
z1.Dump();
}// Program
}// TestLib
The accompanying TestLib program demonstrates all of the capabilities of the Complex struct. One point worth making is that complex numbers can be expressed both in a rectangular form that most high-school algebra students are familiar with and in the more sophisticated polar form which requires some more advanced understanding of trigonometry, De Moivre's Theorem and Euler's Identity. If you are interested, check them out on the Web.
TestLib
Complex struct
Note that all of the initialization input assumes that you are using the rectangular form of the complex number, which implies that real is measured along the x-axis of the Argand plane and imaginary is measured along the y-axis of that plane. However, the program has the capacity to output the components of the polar form -- that is, the modulus |z| and the argument (theta) -- by using the ShowPolar() and Polar() methods and the Argument and Modulus properties (see above).
|z|
ShowPolar()
Polar()
Argument
Modulus
Since complex numbers can be added, subtracted, multiplied and divided, it is convenient to have operators to accomplish those ends. Thus, we have incorporated those operators.
There appears to be no shortage of postings offering C# code for dealing with complex numbers. These include:
Although I have been involved in scientific mathematical and statistical programming for over 10 years, this article is the first that I have attempted to post. I quickly learned that there are many smarter and better programmers out there who have done a much better job at using C#. For me, this was an excellent learning experience, both in terms of learning some of the pitfalls of scientific computing with C# and having to explain to others what my code does.
The fact that C# class assignment operators which are automatically generated and cannot be overridden create something of a problem, particularly if one is coming from a C++ background. Once an assignment is made, the assignor and the assignee are locked together by a common pointer. Change one, you change the other. In order to work around that, one would have to implement ICloneable which can be rather tedious and complicated. For that reason, I chose to use the struct rather than a class. I am still learning about C#.
ICloneable
struct
I plan to update and improve this code for my own use and for any others who wish to use it, and to do a better job in the future. You may use this code in any manner that you wish. It is always polite and professional to give the original author credit. Please report any comments, criticisms or bugs to the forum. | http://www.codeproject.com/Articles/21059/A-C-Class-to-Perform-Arithmetic-on-Complex-Numbers | CC-MAIN-2014-23 | refinedweb | 1,130 | 52.05 |
San Beda College of LAW – ALABANG
GENERAL PRINCIPLES
b.Regulation – As in the case of taxes levied on
I. Concepts, Nature and Characteristics of excises and privileges like those imposed in
Taxation and Taxes. tobacco or alcoholic products or amusement
places like night clubs, cabarets, cockpits, etc.
In the case of Caltex Phils. Inc. vs COA
Taxation Defined: (G.R. No. 92585, May 8, 1992), it was held that
taxes may also be imposed for a regulatory
As a process, it is a means by which the purpose as, for instance, in the rehabilitation and
sovereign, through its law-making body, raises stabilization of a threatened industry which is
revenue to defray the necessary expenses of the affected with public industry like the oil industry.
government. It is merely a way of apportioning
the costs of government among those who in c.Reduction of Social Inequality – this is
some measures are privileged to enjoy its made possible through the progressive system of
benefits and must bear its burdens. taxation where the objective is to prevent the
under-concentration of wealth in the hands of few
As a power, taxation refers to the inherent individuals.
power of the state to demand enforced
contributions for public purpose or purposes.
d.Encourage Economic Growth – in the realm
of tax exemptions and tax reliefs, for instance,
Rationale of Taxation - The Supreme Court
the purpose is to grant incentives or exemptions
held:
in order to encourage investments and thereby
“It is said that taxes are what we pay for
promote the country’s economic growth.
civilized society. Without taxes, the government
would be paralyzed for lack of the motive power
to activate and operate it. Hence, despite the e.Protectionism – in some important sectors of
natural reluctance to surrender part of one’s the economy, as in the case of foreign
hard-earned income to the taxing authorities, importations, taxes sometimes provide protection
every person who is able must contribute his to local industries like protective tariffs and
share in the running of the government. The customs.
government for its part is expected to respond in
the form of tangible and intangible benefits Taxes Defined
intended to improve the lives of the people and
enhance their moral and material values. The Taxes are the enforced proportional
symbiotic relationship is the rationale of contributions from persons and property levied by
taxation and should dispel the erroneous notion the law-making body of the State by virtue of its
that it is an arbitrary method of exaction by those sovereignty for the support of government and
in the seat of power. for public needs.
Taxation is a symbiotic relationship,
whereby in exchange for the protection that the Essential Characteristic of Taxes [ LEMP3S ]
citizens get from the government, taxes are
paid.” (Commissioner of Internal Revenue vs 1.It is levied by the law-making body of the
Allegre, Inc.,et al., L-28896, Feb. 17, 1988) State
The power to tax is a legislative power
Purposes and Objectives of Taxation which under the Constitution only Congress can
exercise through the enactment of laws.
1.Revenue – to provide funds or property with Accordingly, the obligation to pay taxes is a
which the State promotes the general welfare and statutory liability.
protection of its citizens.
2.It is an enforced contribution
2.Non-Revenue [PR2EP] A tax is not a voluntary payment or
donation. It is not dependent on the will or
contractual assent, express or implied, of the
a.Promotion of General Welfare – Taxation
person taxed. Taxes are not contracts but positive
may be used as an implement of police power in
acts of the government.
order to promote the general welfare of the
people. [see Lutz vs Araneta (98 Phil 148) and
Osmeňa vs Orbos (G.R. No. 99886, Mar. 31, 3.It is generally payable in money
1993)]
TAX ATION
San Beda College of LAW – ALABANG
Tax is a pecuniary burden – an exaction to a.It does not mean that only those who are able
be discharged alone in the form of money which to pay and do pay taxes can enjoy the privileges
must be in legal tender, unless qualified by law, and protection given to a citizen by the
such as RA 304 which allows backpay certificates government.
as payment of taxes. b.From the contributions received, the
government renders no special or commensurate
4.It is proportionate in character - It is ordinarily benefit to any particular property or person.
based on the taxpayer’s ability to pay. c.The only benefit to which the taxpayer is
entitled is that derived from his enjoyment of the
5.It is levied on persons or property - A tax privileges of living in an organized society
may also be imposed on acts, transactions, rights established and safeguarded by the devotion of
or privileges. taxes to public purposes. (Gomez vs Palomar, 25
SCRA 829)
6.It is levied for public purpose or purposes - d.A taxpayer cannot object to or resist the
Taxation involves, and a tax constitutes, a burden payment of taxes solely because no personal
to provide income for public purposes. benefit to him can be pointed out as arising from
the tax. (Lorenzo vs Posadas, 64 Phil 353)
7.It is levied by the State which has jurisdiction
over the persons or property. - The persons, 3.Lifeblood Theory
property or service to be taxed must be subject Taxes are the lifeblood of the government,
to the jurisdiction of the taxing state. being such, their prompt and certain availability
is an imperious need. (Collector of Internal
Revenue vs. Goodrich International Rubber Co.,
Theory and Basis of Taxation Sept. 6, 1965) Without taxes, the government
would be paralyzed for lack of motive power to
1.Necessity Theory activate and operate it.
Taxes proceed upon the theory that the
existence of the government is a necessity; that
it cannot continue without the means to pay its Nature of Taxing Power
expenses; and that for those means, it has the
right to compel all citizens and properties within 1.Inherent in sovereignty – The power of
its limits to contribute. taxation is inherent in sovereignty as an incident
In a case, the Supreme Court held that: or attribute thereof, being essential to the
Taxation is a power emanating from existence of every government. It can be
necessity. It is a necessary burden to preserve the exercised by the government even if the
State’s sovereignty and a means to give the Constitution is entirely silent on the subject.
citizenry an army to resist aggression, a navy to a.Constitutional provisions relating to the power
defend its shores from invasion, a corps of civil of taxation do not operate as grants of the power
servants to serve, public improvements designed to the government. They merely constitute
for the enjoyment of the citizenry and those limitations upon a power which would otherwise
which come with the State’s territory and be practically without limit.
facilities, and protection which a government is b.While the power to tax is not expressly
supposed to provide. (Phil. Guaranty Co., Inc. vs provided for in our constitutions, its existence is
Commissioner of Internal Revenue, 13 SCRA recognized by the provisions relating to taxation.
775). In the case of Mactan Cebu International
Airport Authority vs Marcos, Sept. 11, 1996, as an
2.The Benefits-Protection Theory incident of sovereignty, the power to tax has
The basis of taxation is the reciprocal duty been described as “unlimited in its range,
of protection between the state and its acknowledging in its very nature no limits, so that
inhabitants. In return for the contributions, the security against its abuse is to be found only in
taxpayer receives the general advantages and the responsibility of the legislative which imposes
protection which the government affords the the tax on the constituency who are to pay it.”
taxpayer and his property.
2.Legislative in character – The power to tax is
exclusively legislative and cannot be exercised by
Qualifications of the Benefit-Protection the executive or judicial branch of the
Theory: government.
TAX ATION
San Beda College of LAW – ALABANG
3.Subject to constitutional and inherent for which the taxing power may be used but the
limitations – Although in one decided case the degree of vigor with which the taxing power may
Supreme Court called it an awesome power, the be employed in order to raise revenue (I Cooley
power of taxation is subject to certain limitations. 179-181)
Most of these limitations are specifically provided
in the Constitution or implied therefrom while the •Constitutional Restraints Re: Taxation is
rest are inherent and they are those which spring the Power to Destroy
from the nature of the taxing power itself While taxation is said to be the power to
although, they may or may not be provided in the destroy, it is by no means unlimited. It is equally
Constitution. correct to postulate that the “power to tax is
not the power to destroy while the Supreme
Court sits,” because of the constitutional
Scope of Legislative Taxing Power [S2 A P K A restraints placed on a taxing power that violated
M] fundamental rights.
In the case of Roxas, et al vs CTA (April
1.subjects of Taxation (the persons, property or 26, 1968), the SC reminds us that although the
occupation etc. to be taxed) power of taxation is sometimes called the power
2.amount or rate of the tax to destroy, in order to maintain the general
3.purposes for which taxes shall be levied public’s trust and confidence in the Government,
provided they are public purposes this power must be used justly and not
4.apportionment of the tax treacherously. The Supreme Court held:
5.situs of taxation “The power of taxation is sometimes
6.method of collection called also the power to destroy. Therefore it
should be exercised with caution to minimize
Is the Power to Tax the Power to Destroy? injury to the proprietary rights of a taxpayer. It
must be exercised fairly, equally and uniformly,
In the case of Churchill, et al. vs lest the tax collector kill the ‘hen that lays the
Concepcion (34 Phil 969) it has been ruled that: golden egg’. And, in order to maintain the general
The power to impose taxes is one so public’ trust and confidence in the Government
unlimited in force and so searching in extent so this power must be used justly and not
that the courts scarcely venture to declare that it treacherously.”
is subject to any restriction whatever, except The doctrine seeks to describe, in an
such as rest in the discretion of the authority extreme, the consequential nature of taxation
which exercise it. No attribute of sovereignty is and its resulting implications, to wit:
more pervading, and at no point does the power a.The power to tax must be exercised with
of government affect more constantly and caution to minimize injury to proprietary rights of
intimately all the relations of life than through the a taxpayer;
exaction made under it. b.If the tax is lawful and not violative of any of
And in the notable case of McCulloch vs the inherent and constitutional limitations, the
Maryland, Chief Justice Marshall laid down the fact alone that it may destroy an activity or object
rule that the power to tax involves the power of taxation will not entirely permit the courts to
to destroy. afford any relief; and
According to an authority, the above c.A subject or object that may not be destroyed
principle is pertinent only when there is no power by the taxing authority may not likewise be
to tax a particular subject and has no relation to a taxed. (e.g. exercise of a constitutional right)
case where such right to tax exists. This opt-
quoted maxim instead of being regarded as a Power of Judicial Review in Taxation
blanket authorization of the unrestrained use of The courts cannot review the wisdom or
the taxing power for any and all purposes, advisability or expediency of a tax. The court’s
irrespective of revenue, is more reasonably power is limited only to the application and
construed as an epigrammatic statement of the interpretation of the law.
political and economic axiom that since the Judicial action is limited only to review
financial needs of a state or nation may outrun where involves:
any human calculation, so the power to meet 1.The determination of validity on the tax in
those needs by taxation must not be limited even relation to constitutional precepts or provisions.
though the taxes become burdensome or 2.The determination, in an appropriate case, of
confiscatory. To say that “the power to tax is the the application of the law.
power to destroy” is to describe not the purposes
Theoretical Justice – the tax burden should be the manufacturer might have passed on to him. Internal Revenue vs John Gotamco and Sons. Hence.Administrative Feasibility – tax laws should taxes are not included. customs Basic Principles of a Sound Tax System [FAT] duties excise taxes on certain specific goods 1. The 1987 Constitution Internal Revenue et. TAX ATION San Beda College of LAW – ALABANG Aspects of Taxation 1. 27. L-19707. but the evident intention is to fixed amount upon all persons of a certain class exempt the contractor so that such contractor within the jurisdiction of the taxing power without may no longer shift or pass on any tax to the regard to the amount of their property or contractee. the sum or sums to be raised.As to Subject matter 3. 1987) requires taxation to be equitable and uniform. Inc. then the buyer of the product or service sold has a right to 3. just and effective cannot claim exemption from the payment of administration. but the burden thereof can be “taxation system”.Indirect Taxes – taxes wherein the incidence taxpayer and is referred to as tax administration) of or the liability for the payment of the tax falls The two processes together constitute the on one person. al. exemption covers only those taxes for which such consumer or end-user is directly liable. example: community tax et.Where the exemption from indirect tax is given 1. Macaraig. in proportion to the taxpayer’s ability to pay (Phil. percentage taxes.When the consumer or end-user of a government would be in keeping with the manufacturer product is tax-exempt. 1963) A. Classifications and Distinction tax and shifts the same to the buyer. Acetylene Co. 1987) 2. such principle. (this includes payment by the 2. Aug.. estate tax enforcement of the obligation on the part of those who are taxed. the enjoyment of a sellers passed on to him. estate tax or donor’s tax . clearly manifest therein that legislative intention example: real estate tax to exempt embraces indirect taxes. vs Commissioner of (ability-to-pay principle).Property Taxes – taxes on things or property 4.Direct Taxes – taxes wherein both the manner of levying and collecting taxes (strictly “incidence” as well as the “impact” or burden of speaking. L-10963. Neither an excess regarding Indirect Taxes: nor a deficiency of revenue vis-à-vis the needs of 1. the manufacturer be capable of convenient. and approximate the needs Important Points to Consider of government expenditure.al. examples: income tax. 2.Personal. capitation or poll taxes – taxes of to the contractee.Excise Taxes – charges imposed upon the be reimbursed the amount of the taxes that the performance of an act.Fiscal Adequacy – the sources of tax revenue should coincide with. sales tax.When the law granting tax exemption of a certain class within the jurisdiction of the specifically includes indirect taxes or when it is taxing power.Levy – determination of the persons.supra) examples: income tax. or the engaging in an occupation.. L-31092. but must hold it in trust for Classification of Taxes buyer.Collection – consists of the manner of donor’s tax.17. examples: VAT. value-added tax.As to Burden or excises to be taxed. shifted or passed to another person. 2. the due date thereof and the time and 1. the seller gets the refund. inc.. Indirect 2. (American Rubber Co. case. the contractor may claim tax occupations or businesses in which they may be exemption on the transaction (Commissioner of engaged in.When the transaction itself is the one that is tax-exempt but through error the seller pays the II. such refers to taxation) the tax faces on one person. Feb. neither can the consumer or buyer of the product demand the refund of the tax that 3. community tax. property B. April 30. (Maceda vs privilege.
. of a public nature.imposed by the government government or private 2.imposed only by the 4. 1. Toll – sum of money for the use of Examples: taxes on distilled spirits.Mixed Tax – tax rates are partly progressive and partly regressive. bridge of the like. to achieve some social or A regressive tax.As to Purpose examples: national internal revenue taxes.paid for the use of of the government another’s property 3.e. Regressive System of Taxation: D. estate tax. Government units. customs duties 1. 3.Progressive Tax – the rate or the amount of to amount imposed the cost of construction the tax increases as the amount of the income or or maintenance of the earning (tax base) to be taxed increases.imposed by the examples: real estate tax.imposed only by the 2.demand of 1. with regressive system of taxation.Special Assessment vs Tax tax Special Assessment – an enforced proportional contribution from owners of lands especially or peculiarly benefited by public 1. wines.As to Scope or authority imposing the c.Penalty vs Tax according to De Leon) Penalty – any sanctions imposed as a punishment for violations of law or acts deemed injurious.Proportionate Tax – tax rates are fixed on a raise revenue conduct flat tax base.demand of sovereignty proprietorship E.Specific Tax – tax imposed per head. 2. example: real property taxes.paid for the support 2.General/Fiscal/Revenue – tax imposed for the general purposes of the government.generally intended to 1. i. Note: We have no regressive taxes (this is b. VAT.As to Measure of Application focuses on indirect taxes. public improvement examples: income tax.Municipal/Local Tax – tax imposed by Local revenues for governmental needs.. donor’s used tax 4.Special/Regulatory – tax imposed for special Regressive Tax purposes. professional tax all taxes •Regressive System of Taxation vis-à-vis 2. Government.As to Date 2. 2. something. Tax vs Penalty 1. .Toll vs Tax to be taxed.designed to regulate 4. no limit as 3. TAX ATION San Beda College of LAW – ALABANG C.e.National Tax – tax imposed by the National improvements. Examples: educational fund tax under Real Regressive Tax: tax the rate of which Property Taxation decreases as the tax base increases. or by some standard of weight or Taxes distinguished from other Impositions measurement and which requires no assessment beyond a listing and classification of the subjects a. must not be confused economic needs.Regressive Tax – the tax rate decreases as the individuals or entities amount of income or earning (tax base) to be taxed increases. Examples: income taxes.amount depends on 1. unit or number. generally applied to the consideration and fermented liquors which is paid for the use of a road. and almost examples: real estate tax. VAT. it exists when there are more indirect taxes imposed than direct taxes. and other government government or private percentage taxes individuals or entities F.generally. to raise 2. customs Tax vs Toll duties 1. i.Ad Valorem Tax – tax based on the value of the article or thing subject to tax.
Debt vs Tax License or Permit fee – is a charge Debt is based upon juridical tie.no imprisonment for paid of inspection and sanction for non.generally not subject 4.The general rule is that an exemption from imposition of a tax. maybe considered both Sec.imposed on persons. 234 of the Local Government Code.But a tax may have only a regulatory purpose.levied only on land the act or business illegal property and excise illegal 2.enforced contribution 1.e. Tax vs License/Permit Fee Tax vs Debt 1.generally. it follows that the exemption under for revenue purposes. cannot be 2.non-payment makes Assessment not necessarily make the act or business 1.( see the primary purpose.general application 4.exceptional both as (see Apostolic Prefect time and place vs Treas. TAX ATION San Beda College of LAW – ALABANG persons and property to exercise privilege Tax vs Special 6. and that exemption from taxes may Regarding Special Assessments: not include exemption from license fees.legal compensation or 1. exclusively used for religious.However.non-payment does 6. contracts. the fact that incidentally Aban) revenue is also obtained does not make the 3 . related cases) 2. non-payment of debt regulation payment of tax except 5.generally no limit in 4. Three kinds of licenses are i.based on law 1. 3.The general rule is that the imposition is a tax if educational purposes are not exactly exempt its primary purpose is to generate revenue and from real property taxes but are exempt from the regulation is merely incidental.An extraction. properties which are actually.amount is limited to compensation the amount of tax to be the necessary expenses 5. however. 28(3).Licenses for the regulation or restriction of non- well as on benefits benefits useful occupations or enterprises received 3. (see American Mail Line vs Sec.Since special assessments are not taxes within 2. VI of the Constitution does not City of Butuan. 172 SCRA assessment. delicts or quasi-delicts between of regulation. created by imposed under the police power for the purposes law.based on contracts. May 31. parties for their private interest or resulting from their own acts or omissions.Licenses for revenue only 4. but if regulation is imposition of special assessments as well.for revenue purposes 2. in view of the exempting proviso in 3. directly and 4. 1967 and apply to special assessments.The power to regulate as an exercise of police the constitutional or statutory provisions on tax power does not include the power to impose fees exemptions. (see Progressive taxation does not include exemption from special Development Corp.imprisonment is a 5.imposed also on 5. his liability is limited recognized in the law: only to the land 1. 71 Importance of the distinctions Phil 547) between tax and license fee: 1. vs Quezon City.personal liability of 2.may be subject to taxing power police power to set-off or set-off or compensation 4. assessed by sovereign reward of an officer for express or implied authority to defray specific purposes 2.may be paid in kind purposes money 3.generally payable in 3. a tax and a license fee.Some limitations apply only to one and not to Important Points to Consider the other.based on necessity as 3. charitable and 5. Of Baguio.based wholly on 2. L-12647.an exercise of the 4.for regulation 3.not a personal liability the person assessed of the person assessed. 629) d.imposed on the right poll tax .assignable public expenses assigned 2.License or Permit Fee vs Tax e.an exercise of the 3.Licenses for the regulation of useful involved occupations. 1. 1. Art.
TAX ATION
San Beda College of LAW – ALABANG
6.governed by special 6.governed by the
prescriptive periods ordinary periods of 4.Tariff – it may be used in 3 senses:
provided for in the Tax prescriptions a.As a book of rates drawn usually in
Code alphabetical order containing the names of
7.does not draw 7.draws interest when several kinds of merchandise with the
interest except only so stipulated, or in case corresponding duties to be paid for the same.
when delinquent of default b.As duties payable on goods imported or
exported (PD No. 230)
General Rule: Taxes are not subject to set-off or c.As the system or principle of imposing duties
legal compensation. The government and the on the importation/exportation of goods.
taxpayer are not creditors and debtors or each
other. Obligations in the nature of debts are due 5.Internal Revenue – refers to taxes imposed by
to the government in its corporate capacity, while the legislative other than duties or imports and
taxes are due to the government in its sovereign exports.
capacity (Philex Mining Corp. vs CIR, 294 SCRA
687; Republic vs Mambulao Lumber Co., 6 SCRA 6.Margin Fee – a currency measure designed to
622) stabilize the currency.
Exception: Where both the claims of the 7.Tribute – synonymous with tax; taxation
government and the taxpayer against each other implies tribute from the governed to some form of
have already become due and demandable as sovereignty.
well as fully liquated. (see Domingo vs Garlitos, L-
18904, June 29, 1963)
8.Impost – in its general sense, it signifies any
tax, tribute or duty. In its limited sense, it means
a duty on imported goods and merchandise.
Pertinent Case:
Inherent Powers of the State
Philex Mining Corp. vs Commissioner of
Internal Revenue 1.Police Power
G.R. No. 125704, Aug. 28, 1998 2.Power of Eminent Domain
3.Power of Taxation
The Supreme Court held that: “We have
consistently ruled that there can be no offsetting Distinctions among the Three Powers
of taxes against the claims that the taxpayer may
have against the government. A person cannot Taxation Police Eminent
refuse to pay a tax on the ground that the Power Domain
government owes him an amount equal to or PURPOSE
greater than the tax being collected. The - levied for - exercised - taking of
collection of a tax cannot await the results of a the to promote property for
lawsuit against the government.” purpose of public public use
raising welfare thru
f.Tax Distinguished from other Terms. revenue regulations
AMOUNT OF EXACTION
1.Subsidy – a pecuniary aid directly granted by - no limit - limited to - no exaction,
the government to an individual or private the cost of compensation
commercial enterprise deemed beneficial to the regulations, paid by the
public. issuance of government
the license
or
2.Revenue – refers to all the funds or income surveillance
derived by the government, whether from tax or
BENEFITS RECEIVED
from whatever source and whatever manner.
- no special - no direct - direct benefit
or direct benefits but results in the
3.Customs Duties – taxes imposed on goods benefits a healthy form of just
exported from or imported into a country. The received economic compensation
term taxes is broader in scope as it includes but the standard of
customs duties. enjoyment society or
TAX ATION
San Beda College of LAW – ALABANG
of the “damnum 5.International Comity
privileges absque
of living in injuria” is b.Constitutional Limitations or those
an attained expressly found in the constitution or implied
organized from its provision
society
NON-IMPAIRMENT OF CONTRACTS
1.Due process of law
- the - contract - contracts may
impairment may be be impaired 2.Equal protection of law
rule subsist impaired 3.Freedom of Speech and of the press
TRANSFER OF PROPERTY RIGHTS 4.Non-infringement of religious freedom
- taxes paid - no transfer - property is 5.Non-impairment of contracts
become but only taken by the 6.Non-imprisonment for debt or non-payment
part of restraint on gov’t upon of poll tax
public the exercise payment of just 7.Origin of Appropriation, Revenue and Tariff
funds of property compensation
Bills
right exists
SCOPE
8.Uniformity, Equitability and Progressitivity of
Taxation
- affects all - affects all - affects only
persons, persons, the particular 9.Delegation of Legislative Authority to Fx Tariff
property property, property Rates, Import and Export Quotas
and excise privileges, comprehended 10.Tax Exemption of Properties Actually,
and even Directly, and Exclusively used for Religious
rights Charitable
BASIS 11.Voting requirements in connection with the
- public - public -public Legislative Grant of Tax Exemption
necessity necessity necessity, 12.Non-impairment of the Supreme Courts’
and the private property jurisdiction in Tax Cases
right of the is taken for 13.Tax exemption of Revenues and Assets,
state and public use including Grants, Endowments, Donations or
the public to Contributions to Education Institutions
self-
protection c. Other Constitutional Provisions related
and self- to Taxation
preservation
AUTHORITY WHICH EXERCISES THE POWER
1.Subject and Title of Bills
- only by - only by the - may be
the government granted to 2.Power of the President to Veto an items in an
governmen or its public service, Appropriation, Revenue or Tariff Bill
t or its political companies, or 3.Necessity of an Appropriation made before
political subdivisions public utilities money
subdivision 4.Appropriation of Public Money
s 5.Taxes Levied for Special Purposes
6.Allotment to LGC
III. Limitations on the Power of Taxation
Inherent Limitations
Limitations, Classified
A. Public Purpose of Taxes
a.Inherent Limitations or those which restrict 1.Important Points to Consider:
the power although they are not embodied in the a.If taxation is for a public purpose, the tax
Constitution [P N I T E] must be used:
a.1) for the support of the state or
1.Public Purpose of Taxes a.2) for some recognized objects of
2.Non-delegability of the Taxing Power governments or
a.3) directly to promote the welfare of
3.Territoriality or the Situs of Taxation the community (taxation as an implement of
4.Exemption of the Government from taxes police power)
TAX ATION
San Beda College of LAW – ALABANG
b.The term “public purpose” is synonymous
with “governmental purpose”; a purpose B. Non-delegability of Taxing Power
affecting the inhabitants of the state or
taxing district as a community and not 1. Rationale: Doctrine of Separation of
merely as individuals. Powers; Taxation is purely legislative,
Congress cannot delegate the power to
c. A tax levied for a private purpose others.
constitutes a taking of property without due
process of law. 2. Exceptions:
a. Delegation to the President (Art.VI. Sec.
d. The purposes to be accomplished by 28(2) 1987 Constitution)
taxation need not be exclusively public. Although The power granted to Congress under this
private individuals are directly benefited, the tax constitutional provision to authorize the President
would still be valid provided such benefit is only to fix within specified limits and subject to such
incidental. limitations and restrictions as it may impose,
tariff rates and other duties and imposts include
e. The test is not as to who receives the tariffs rates even for revenue purposes only.
money, but the character of the purpose for Customs duties which are assessed at the
which it is expended; not the immediate result of prescribed tariff rates are very much like taxes
the expenditure but rather the ultimate. which are frequently imposed for both revenue-
raising and regulatory purposes (Garcia vs
g. In the imposition of taxes, public purpose Executive Secretary, et. al., G.R. No. 101273, July
is presumed. 3, 1992)
b. Delegations to the Local Government
2. Test in determining Public Purposes in (Art. X. Sec. 5, 1987 Constitution)
tax It has been held that the general principle
against the delegation of legislative powers as a
a. Duty Test – whether the thing to be consequence of the theory of separation of
threatened by the appropriation of public revenue powers is subject to one well-established
is something which is the duty of the State, as a exception, namely, that legislative power may be
government. delegated to local governments. The theory of
non-delegation of legislative powers does not
b. Promotion of General Welfare Test – apply in maters of local concern. (Pepsi-Cola
whether the law providing the tax directly Bottling Co. of the Phil, Inc. vs City of Butuan, et .
promotes the welfare of the community in equal al., L-22814, Aug. 28, 1968)
measure.
c. Delegation to Administrative Agencies
with respect to aspects of Taxation not legislative
Basic Principles of a Sound Tax System in character.
(FAT) example: assessment and
collection
a. Fiscal Adequacy – the sources of tax revenue
should coincide with, and approximate the needs 3.Limitations on Delegation
of government expenditure. Neither an excess
nor a deficiency of revenue vis-à-vis the needs of a. It shall not contravene any
government would be in keeping with the Constitutional provisions or inherent limitations of
principle. taxation;
b. The delegation is effected either by the
b. Administrative Feasibility – tax laws should Constitution or by validly enacted legislative
be capable of convenient, just and effective measures or statute; and
administration. c. The delegated levy power, except when
the delegation is by an express provision of
c. Theoretical Justice – the tax burden should Constitution itself, should only be in favor of the
be in proportion to the taxpayer’s ability to pay local legislative body of the local or municipal
(ability-to-pay principle). The 1987 Constitution government concerned.
requires taxation to be equitable and uniform.
where b.2) In order that the functions of the imposition of the tax [S2 A P K A M]. TAX ATION San Beda College of LAW – ALABANG 4.Important Points to Consider: intervention of the state. and excise within the territory of the taxing power because: E.It is an inherent mandate that taxation absence of tax exemption provisions in their shall only be exercised on persons. 3 “No person shall be e.2) Property which is wholly and a. the elements that enter into the a. the government Administration .2) usage among states that when one c. A person may be taxed.Basis: Sec. Reasons for Exemptions: 2. another state receives none of the protection for which a tax is supposed to b.location of the subject matter of the tax 1. the the course of its operations.The grounds for the above rule are: be compensation. liberty or property without f. The means employed must be a. delegation is invalid.Due Process of Law c.citizenship of the person a. a. the government may tax itself in the absence of any 1.3) foreign government may not be sued there is between him and the taxing state. through which the government immediately and directly exercises its sovereign powers (Infantry Post Exchange vs Posadas.” occupation is being exercised Requisites : 1.1) sovereign equality among states b.Government-owned or controlled “place of taxation” depending on the nature corporations.Factors to Consider in determining Situs of Taxation Constitutional Limitations a. or tax government shall not be unduly impede. a without its consent so that it is useless to assess privity of relationship justifying the levy. under the jurisdiction of the latter even if he is outside the taxing state. 54 Phil 866) C. but if what is involved is 2. properties. a. . International Comity b. functions are generally subject to tax in the b.Unless otherwise provided by law. when performing proprietary of taxes being imposed.The property of a foreign state or exclusively within the jurisdiction of government may not be taxed by another. the steps taken for its assessment and a. Territoriality or Situs of Taxation 3.Every system of taxation would be taxing itself to raise money to consists of two parts: pay over to itself.4) reciprocity among states 2.Tax Legislation vis-à-vis Tax the tax so laid and thus. charters or law creating them. b. there is an right to tax is the capacity of the government implied understanding that the power does not to provide benefits and protection to the intend to degrade its dignity by placing itself object of the tax.1) Tax laws do not operate beyond a country’s territorial limit. The interest of the public generally D. business or due process of law x x x.place where the privilege.Important Points to Consider: b. regulation. 1 Art.1) To levy tax upon public property reasonably necessary to the would render necessary new taxes on accomplishment for the purpose other public property for the payment of and not unduly oppressive. the tax since it cannot be collected b.kind and Classification of the Tax b. the non-delegability rule exemption applies only to government entities is not violated.Notwithstanding the immunity.However.3) To reduce the amount of money that collection or tax administration has to be handed by the government in If what is delegated is tax legislation.domicile or residence of the person d. and and b. 1.Territoriality or Situs of Taxation means 4.Important Points to Consider: constitutional limitations. the fundamental basis of the enter into the territory of another. Exemption of the Government from Taxes as distinguished from those of a particular class require the 1.source of income deprived of life. the only tax administration.
passed abridging the freedom of speech. the obligation of contract shall be passed. VI. 2.Uniformity. just.Freedom of Speech and of the Press held that in order that due process of law must not be done in an arbitrary. and free exercise and enjoyment of religious 5.Equal Protection of the Law b. x x x” 3. Equal protection of the laws required for the sale or contribution of printed signifies that all persons subject to legislation materials like newspaper for such would be shall be treated under circumstances and imposing a prior restraint on press freedom conditions both in the privileges conferred and 3. 28(1) Art. discrimination or preference. 5 Art. Exercise of Religion clause does not prohibit b.Basis: Sec. The deprivation was done after 5. and SCRA 27) 4. However. capricious. Congress shall evolve a progressive system 2. 164 the constitution. The rule of actually in the nature of a condition or permit of taxation shall be uniform and equitable. Progressive system of Taxation b. Must play equally to all members of a profession and worship. Important Points to Consider: 1. (see the authority of a valid law or of Commissioner vs. Inequality which results in singling out those in the contract. A tax is uniform when the same force and effect in every place where the 6. 1. 235 SCRA 630) taxed at the same rate. (see Tolentino vs Secretary of or kinds or property of the same class shall be Finance. Lingayen Gulf Electric. Must not be arbitrary 5. Important Points to Consider: 2.Requisites for a Valid Classification 1. . made respecting an establishment of religion 4. License fees/taxes would constitute a restraint on the freedom of worship as they are a. or changing 4. shall be forever be allowed. III. “No law impairing and proportionate to one’s ability to pay. under the Constitution. Must not be based upon substantial distinctions a. because reasonable method of procedure this is hardly attainable. The only. The deprivation was done under infringes no constitutional limitation. In a string of cases. TAX ATION San Beda College of LAW – ALABANG 3. III. Must not be limited to exiting conditions or prohibiting the free exercise thereof.Important Points to Consider: places stress on direct rather than indirect taxes. Important Points to Consider: imposing a generally applicable sales and use tax 1. Equitability and b. reasonable a. b.Basis: Sec. a. prescribed by law. or dispenses with those one particular class for taxation or exemption expressed. “No law shall be 3. impairs the obligation. This doctrine prohibits class does not constitute a restraint on press freedom legislation which discriminates against some and since it is not imposed for the exercise of a favors others.Basis: Sec. despotic. privilege but only for the purpose of defraying part of cost of registration. without class. III. Important Points to Consider: Progressivity of Taxation 1.Non-impairment of Contracts subject of it is found. Uniformity (equality or equal on the sale of religious materials by a religious protection of the laws) means all taxable articles organization.1 Art. However.Basis: Sec. No law shall be or whimsical manner. of expression or of the pressx x x “ 2. the Constitution or the Free of taxation.Non-infringement of Religious Freedom 2. A law which changes the terms of the or on the taxpayers’ ability to pay contract by making new conditions. Must be germane to the purpose of law. an annual registration liabilities imposed fee on all persons subject to the value-added tax 2. the Supreme Court 4. Equitable means fair. The rule of uniformity does not call for compliance with fair and perfect uniformity or perfect equality. A business license may not be 1. 4 Art. 10 Art. There is curtailment of press a. 3 “ xxx Nor shall any freedom and freedom of thought if a tax is levied person be denied the equal protection of the in order to suppress the basic right of the people laws. The the exercise of the right.” 3.Basis: Sec.
and enumerated in Sec. however. prescribe.Non-imprisonment for non-payment of educational purposes shall be exempt from poll tax taxation. TAX ATION San Beda College of LAW – ALABANG 2. The prohibition is against facilities which are incidental to and reasonably “imprisonment” for “non-payment of poll tax”. and apportion the jurisdiction of the various subject to such limitations and restrictions as courts but may not deprive the Supreme it may impose. Voting Requirements in connection increase of the public debt.Basis: Sec. 101(9)(3). directly and exclusively used for religious. VI. VIII. However.Basis: Sec. Imports and Export Quotas Courts’ jurisdiction in Tax Cases a. the property b. building.Basis: Sec. Under the above provision. “No person shall be 1. violation of the community tax law other than for 5.Basis: Sec.Basis: Sec. other taxes as prescribed by law. The above provision requires the amendments” but also “to propose concurrence of a majority not of attendees amendments”. To be tax-exempt. revenue or tariff bills.Basis: Sec. 5 hereof. The only penalty for delinquency in the purposes mentioned. III. 28(3) Art. bills of local with the Legislative Grant for tax exemption application. orders of lower courts in x x x all cases Directly and Exclusively used for Religious. bill authorizing 11.Origin or Revenue. a. a person is subject to imprisonment for purposes. 28(4) Art. revise. involving the legality of any tax. 24 Art. import and export Court of its jurisdiction over cases quotas. the Senator’s members of the Congress. VI. payment is the payment of surcharge in the form 3. The exemption is not limited to date until it is paid. charitable or 7. Charitable and Educational Purposes .Delegation of Legislative Authority to 12. Appropriation and charitable and educational organizations would Tariff Bills nevertheless qualify for donor’s gift tax exemption. mosques.Tax Exemption of Properties Actually. of Finance. (Sec. tariff rates. “No law granting but the Senate may propose or concur with any tax exemption shall be passed without amendments. “The Congress Congress may. churches and parsonages or repeal by the Congress when the public interest convents appurtenant thereto.” power is not only to “only concur with b. The constitutional exemption non-payment of the tax and for non-payment of applies only to property tax. NIRC) a. (Sec. shall be added to the unpaid amount from due 4.” b. 5 (2b) Art. “The Supreme of the national development program of the Court shall have the following powers: x x government. Important Points to Consider: a. and improvements actually. constituting a quorum but of all members of supra) the Congress.” the concurrence of a majority of all the b. so requires. LGC) property actually indispensable but extends to 2. modify or affirm on appeal or certiorari x x x final judgments and 10. tonnage and wharfage dues. The word “exclusively” means of interest at the rate of 24% per annum which “primarily’. VI. VI “x x x The a. and private bills shall originate exclusively in the House of Representatives. it would seem that under existing law. 28(2) Art. Lest of the tax exemption: the use imprisoned for debt or non-payment of poll and not ownership of the property tax. Non-impairment of the Supreme Fix Tariff Rates. alteration or institutions. Important Points to Consider: must be actually. 20 Art. “All appropriation. (Tolentino vs Sec. does not apply to public utility franchise since a a. x(2) Review.” 2. The non-impairment rule. necessary for the accomplishment of said Thus. directly and exclusively used for 1. VIII. non-profit cemeteries.” other duties or imposts within the framework Sec. 161. 6. by law. gifts made in favor or religious 8. authorize the shall have the power to define. and all lands. and President to fix within specified limits. “Charitable franchise is subject to amendment. impost. 5 (2) Art. 9.
donations or contributions used library and school facilities. whether the educational institution is Appropriation. use must be school-related. The said constitutional provision granting 7716) was also questioned on the ground that tax exemption to non-stock. Religion (Sec. of proprietary (for profit) educational institutions require prior 2.” 3. and establishment of conditions prescribed by law. Important Points to Consider: Taxation 1. 29(1). and custom duties. in short.Basis: Sec.” operations like income from bank deposits. or toll or any penalty imposed in 3. .Power of the President to Veto items in legislative implementation. Revenue or Tariff bill but the veto proprietary or non-profit. Art. is limited to property tax. however. The tax exemption is not only limited to “No money shall be paid out of the revenues and assets derived from strictly school Treasury except in pursuance of an appropriation operations like income from tuition and other made by law. but it also extends to incidental 4. directly campus.” c. all grants. Constitution) stock. Assets. etc. school building expansion. paid or employed. VI of the 1987 2. church. library. VI of the 1987 Constitution) 6. The exemption granted to non-stock. 16. directly and exclusively for educational embrace only one subject which shall be purpose. “Subject to the faculty development. and improvements actually. property or donation must be used “Every Bill passed by Congress shall actually. VI of the 1987 DOF order governing the tax exemption of non. royalties. assets. Art. a. shall not affect the item or items to which he does not object. 29(2). dated Dec. fees. In the case. Their tax exemption is an Appropriation.Appropriation of Public Money for the income derived from canteen. and donor’s taxes.Necessity of an Appropriation made before money may be paid out of the The following are some of the highlights of the Treasury (Sec. the E-vat. including grants. Lands. benefit. (Sec. sectarian institution. directly. Income which is unrelated to school relation thereto. In the case or religious and charitable entities and non-profit cemeteries. TAX ATION San Beda College of LAW – ALABANG assessment.Department of Finance Order No. Canteens operated by mere or indirectly for the use. trust fund and similar arrangements. Buildings. applied. endowments. To be exempt from tax or duty. like the grant of scholarships. the exemption →in the Tolentino E-VAT case. professional chairs. Sect. non-profit the constitutional requirement on the title of a educational institution is self-executing. The use of the school’s income or assets donations or contributions to Educational must be in consonance with the purposes for Institutions which the school is created. directly and exclusively for educational purposes shall be exempt from tax.” Other Constitutional Provisions related to b. endowments.” miscellaneous feed such as matriculation. Constitution) the facilities mentioned must not only be owned and operated by the school itself but such ”No public money or property shall be facilities must be located inside the school appropriated. of incidental income. expressed in the title thereof. or system of religion or of any priest. or System of dormitory facilities. 1. denomination. 4(4) Art. bookstore and benefit of any Church. 4. 5. and exclusively used for “The President shall have the power to educational purposed are exempt from property veto any particular item or items in an tax. Tax Exemptions of Revenues and dividends and rental income are taxable. 27(2). actually. XIV. 1987 3. 137- 87. the revenue.Subject and Title of Bills (Sec. Tax exemptions. however. bill was not followed. 13. sect. Art. or the Expanded Value Added Tax Law (RA 4. non-profit educational institutions: 1. 26(1) property. preacher. Revenue or Tariff Bill not self-executing. ROTC. 1987 Constitution) 2. non- profit educational institution covers income. support of any concessionaires are taxable. supra.
preacher.Basic Rule – state where the subject to be Criteria in Fixing Tax Situs of Subject of taxed has a situs may rightfully levy and collect Taxation the tax a. The OPSF. of the owner. 104.” the constitutional mandate Example: shares of stock may have situs is not violated. Situs of Taxation and Double Taxation certain intangibles are not categorically spelled out.Double Taxation and the Situs Limitation (see later topic) of Taxation. this special fund is legislative jurisdiction exists.Legislative Power to Fix Situs If no constitutional provisions are violated. according to the for purposes of taxation in a state in which they court. and is for the purpose of taxation where neither the taxable only there. in the national taxes which shall be automatically Example: our law fixes the situs of released to them. Constitution the power of the legislative to fix situs is “Local Government units shall have a undoubted. 2. are or leprosarium.Persons – Poll tax may be levied upon •Some Basic Considerations Affecting persons who are residents of the State. and the insurance policy is delivered to the 29(3). et al. remains as a special fund subject to COA are permanently kept regardless of the domicile audit (Osmeňa vs Orbos. purpose for which a special fund was created has been fulfilled or abandoned the balance.. or the state in which he corporation 99886. In a decide case. there is room for applying the mobilia rule. This is Fund created under P. TAX ATION San Beda College of LAW – ALABANG minister. 1993) is organized. 6. 1956 to stabilize the merely a fiction of law and is not allowed to stand prices of imported crude oil. G. Art. or other religious teacher or dignitary as In the case of Manila Electric Co. Even though the fire insurance contract was executed outside the 5.Real Property – is subject to taxation in the State in which it is located whether the A legal situs cannot be given to property owner is a resident or non-resident.R. or government orphanage covering property situated in the Phils.D. 2. It the insurer is benefited thereby.Allotment to Local Governments →Basis: Sec. if any. Situs of Taxation 1.Situs of Taxation literally means the Place 4. Situs of Taxation 1. transferred from the general fund to a “trust liability account. Art. No.” the situs of personal →An example is the Oil Price Stabilization property is the domicile of the owner. the fund and paid out for such purpose only. This is because the Philippines Government must get something in return for the “All money collected or any tax levied protection it gives to the insured property in the for a special purpose shall be treated as a special Phils. (see Sec.” intangible personal property for purposes of the estate and gift taxes. X of the 1987 3. property nor the person is within the protection of the taxing state →Rule of Lex Rei Sitae .Protection b. the Supreme Court ruled that or dignitary is assigned to the armed forces or to insurance premium paid on a fire insurance policy any penal institution. 6. Phils.” According to this maxim. Mar. as determined by law. just share.Taxes levied for Special Purpose (Sec. 31. in the way of taxation of personalty in the place it was held that where under an executive where it has its actual situs and the requisite order of the President. which means ”movable follow the person.The maxim of Mobilia Sequuntur shall be transferred to the general funds of the Personam and Situs of Taxation government. vs Yatco such except when such priest. VI of the 1987 Constitution) insured therein. minister (69 Phil 89). 1997 NIRC) Note: In those cases where the situs for IV.” taxable in the Phils. and by reason of such protection.
1.Same purpose a situs elsewhere. (see Wells Fargo Bank v. Collector v. donee. January.A tax upon depositions in the bank for their deposits and a tax upon the bank for their V. is subject to taxation in several taxing two different states. 1961) 5.Multiple distinct relationship that may arise with respect to intangible personality. This happens due to: a. Double Taxation →Rule of Lex Rei Sitae Two (2) Kinds of Double Taxation 1.Gratuitous Transfer of Property – as a whole and upon the shareholders for their transmission of property from donor to shares. f.Exemption or allowance of deductions or deduction reduces taxable income while credit tax credit for foreign taxes reduces tax liability . principle.Permissive or Indirect Duplicate jurisdiction and even those who are neither Taxation (Double taxation in its broad sense) – residents nor citizens provided the income is This is the opposite of direct double taxation and derived from sources within the taxing state. 4.During the same taxing period 6.A tax upon the same property imposed by intangible. and 1.A tax on the mortgage as personal property when the mortgaged property is also taxed at its full value as real estate. is not legally objectionable. however. Taxation b. of the •Instances of Double Taxation in its Broad occupation is engaged in of the transaction Sense not place. and same subject of taxation. jurisdictions. or from a decedent to his heirs may 3. 4. like income or 6.Variance in the concept of “domicile” for •Means to Reduce the Harsh Effect of tax purposes. and Transaction – power to levy an excise tax depends upon the place where the business is done. 3. is not controlling when it is inconsistent with express provisions of Requisites: statute or when justice demands that it 1. the property is located. said taxed only once.Tax Deduction – subtraction from gross c.Same property is taxed twice should be. or where shares. Although the owner resides in another jurisdiction.Income – properly exacted from persons who are residents or citizens in the taxing 2.Enter into treaties with other states the state where it has actual situs – where it is physically located. Occupation.Tangible Personal property – taxable in b.Same taxing authority Collector 70 PHIL 325.Business. in accordance with the principle same property is taxed twice when it should be “MOBILIA SEQUUNTUR PERSONAM”. Multiplicity of Situs property in which such deposits are invested 5.Tax Credit – an amount subtracted from an protection of the laws of jurisdiction other than individual’s or entity’s tax liability to arrive at the the domicile of the owner total tax liability Remedy – taxation jurisdiction may provide: →A deduction differ from a tax credit in that a a.Same kind or character of tax e. as where the property has in fact 2.The use to which the property may have income in arriving a taxable income been devoted.An excise tax upon certain use of property There is multiplicity of situs when the and a property tax upon the same property.A tax upon a corporation for its capital stock be subject to taxation in the state where the as a whole and upon the shareholders for their transferor was a citizen or resident.Within the same jurisdiction 11622. 2.Obnoxious or Direct Duplicate Taxation d.Intangible Personal Property – situs or (Double taxation in its strict sense) .In the personal property is the domicile of the objectionable or prohibited sense means that the owner.A tax upon a corporation for its capital stock g. Fisher L. TAX ATION San Beda College of LAW – ALABANG c. The absence of one or more of the foregoing requisites of the obnoxious direct tax makes it indirect. all of which may receive the 2.
Exemptions which a tax is originally imposed. endeavors to recoup himself by improving his is something not favored. a. defined – the reduction in are different kinds of tax the price of the taxed object equal to the c. fiscally speaking. Such taxation. b.Evasion tantamount.Tax on manufacturer’s products and capitalized value of future taxes which the another tax on the privilege of storing exportable purchaser expects to be called upon to pay copra in warehouses within a municipality are imposed as first tax is different from the second 3. be avoided units of products at a lower cost.Transformation there are no proceeds. been imposed. should.Principle of Reciprocity which a tax burden finally rests or settles down.Backward Shifting – effected when Government and another by the city for the the burden of tax is transferred from the exercise of occupation or business as the taxes consumer or purchaser through the factors of are not imposed by the same public authority distribution to the factor of production (City of Baguio vs De Leon.Doubts as to whether double taxation has been imposed should be resolved in favor of the 4.Shifting coupled with overstatement of deduction. to the absence 5. and the incidence is the result. Relations among Shifting. Oct. 4. TAX ATION San Beda College of LAW – ALABANG Impact of taxation – is the point at 3. Kinds of Shifting: General Rule: Our Constitution does not a.Tax Avoidance – is the use by the taxpayer 1.Treaties with other States Incidence of Taxation – is the point on 5. and prevented.Exemption 5. 31. Impact and •Constitutionality Incidence of Taxation – the impact is the initial Double Taxation in its stricter sense is phenomenon. payment of a tax.Substantial underdeclaration of income tax Taxation returns of the taxpayer for four consecutive years 1.Capitalization. a license fee is manufacturer or producer upon whom the tax has imposed in the exercise of police power. it has process of production thereby turning out his been held. and • Six Basic Forms of Escape from b.When a Real Estate dealer’s tax is imposed the tax is shifted two or more times either for engaging in the business of leasing real estate forward or backward in addition to Real Estate Tax on the property leased and the tax on the income desired as they 2. settles on the ultimate purchaser or consumer a.Tax Evasion – is the use of the taxpayer of taxpayer. 2. a.The taxpayer may seek relief under the Uniformity Rule or the Equal Protection →Indicia of Fraud in Taxation guarantee. fearing the loss of his market if he should add the tax to the price. whenever possible. Evasion of Taxation is 4.Failure to declare for taxation purposes true Forms of Escape from Taxation and actual income derived from business for two consecutive years. else . it may not be tax is transferred from a factor of production invoked as a defense against the validity of tax through the factors of distribution until it finally laws.Avoidance of taxation.Shifting – Transfer of the burden of a tax by of legally permissible alternative tax rates or the original payer or the one on whom the tax method of assessing taxable property or income was assessed or imposed to another or someone in order to avoid or reduce tax liability. 1968) c. The reason is to avoid injustice and illegal or fraudulent means to defeat or lessen the unfairness.Where.Where a tax is imposed by the National b.Forward Shifting – the burden of prohibit double taxation. the shifting is the intermediate undoubtedly unconstitutional but that in the process.Capitalization →Evasion of the tax takes place only when 3. broader sense is not necessarily so.Transformation – The method whereby the d.Onward Shifting – this occurs when b. hence. 6. aside from the tax. pays the tax and Exception: Double Taxation while not forbidden.
Collector of Public interest would be subserved by the Internal Revenue vs. Acetylene vs CIR.As to basis a.May be based on some ground of public taxpayer has the legal right to decrease the policy. to encourage new amount of what otherwise would be his taxes and necessary industries. but equity can be used as a of the law means which maybe basis for statutory exemption.As to form a.It is generally revocable by the government deemed exempt as they fall outside the scope of unless the exemption is founded on a contract the taxing provision itself which is protected from impairment. (Sec 276. (Asiatic C.Tax Exemption – is a grant of immunity. properties or excises are 2. Feb.. 27. TAX ATION San Beda College of LAW – ALABANG →Tax Avoidance is not punishable by law. 1965) 3.Partial Exemption – One where collection government of its right to collect what otherwise of a part of the tax is dispensed with would be due to it.Kinds of Tax Exemptions the law 1. emanate from Legislation express or implied. or altogether avoid by means which the law 3. At times the law contrary to the intent authorizes condonation of taxes on equitable of the sponsors of the considerations.Total Exemption – Connotes absolute valid cause or consideration. June 29.May be created in a treaty on grounds of permits. 277.Principles Governing the Tax Exemption 4. 49 PHIL 466. 17. (CIR vs 2. 1968) Terminal vs CIR. and in this sense is prejudicial thereto. Local Government tax law but Code) nevertheless do not violate the letter of F.May be based on a contract in which case. 1967) . immunity 3.It implies a waiver on the part of the b. a a. Oct.He who claims exemptions should D. such as. for example. reciprocity or to lessen the rigors of international double or multiple taxation which occur where Distinction between Tax Evasion and there are many taxing jurisdictions.Statutory Exemptions – Those which A.Exemptions from taxation are highly the exemption has a reasonable foundation or disfavored by law. and he who claims an rational basis.Rationale of tax Exemption Petroleum vs Llanes. Manila Jockey Club.Equity.As to extent elements of contracts. Aug. Exemption from Taxation Constitution b. 31. 2.Express Exemption – Whenever expressly B. CIR vs PAL.Implied Exemption – Exist whenever grantee particular persons. (Visayan Cebu 1967. for example. L-19530. as in the Avoidance taxation of income and intangible personal property Tax Evasion vs Tax Avoidance E.Tax exemptions must be strictly construed supposed to receive a full equivalent therefore (Phil. the public represented by the Government is 4.Constitutional Exemptions – Immunities from taxation which originate from the VI. exemption must be able to justify by the clearest grant of organic or statute of law.It is not necessarily discriminatory so long as 1.He who claims an exemption must justify that the legislative intended to exempt him by Bothelo Shipping Corp. to particular persons or corporations from the obligations to pay taxes.Grounds for Tax Exemptions convincingly proved that he is exempt 1. L-21633. words too plain to be mistaken. G. 98 PHIL exemption allowed which the law-making body 670) considers sufficient to offset monetary loss entailed in the grant of the exemption. not a ground for Tax Exemption accomplished by accomplished by There is no tax exemption solely on the breaking the letter legal procedures or ground of equity. such as. but the contract must contain the other essential 3. L-20960. a 2.It is merely a personal privilege of the b. L-19707.Nature of Tax Exemption granted by organic or statute of law 1.
VII. except for the legislative intent. (Lealda Important Point to Consider Electric Co. are construed law itself. 130. charitable.The exemptions. 1999) 8. taxes therein imposed b. No. 1987. Imprescriptibility of Taxes such as tax amnesty and tax condonation) are not presumed and when granted are strictly General Rule: Taxes are imprescriptible construed against the grantee. vs CIR. unsettled tax liabilities should be pertinent only G.It is only when an act Exception: The language of the statute clearly complained of. (Collector vs UST.Exemptions from certain taxes granted under special circumstances to special classes of persons. TAX ATION San Beda College of LAW – ALABANG 5. directly involves the illegal retroactive effect.Constitutional grants of tax exemptions are measure.The exemptions (or equivalent provisions. was rejected by educational functions the Supreme Court. the exceptions to the Justice) law on prescription be strictly construed. much like a tax exemption is by prescription may be allowed to offset never favored or presumed by law (CIR vs CA. 1999) to taxes arising from the same transaction on 10.Deductions for income tax purposes partake of the nature of tax exemptions.The rule of strict construction against the government is not applicable where the language rule in the Constitution against the passage of the of the tax law is plain and there is no doubt as to ex post facto laws cannot be invoked. 108576. L-16428.Tax Exemptions are not presumed. G. 4. Exception: When provided otherwise by the tax 5. which may include legislative demands or express that it shall have a enactment. PHIL934) 2. performing strictly religious.R. saying that it was not convinced of the wisdom and proprietary thereof. and This doctrine. tax statutes are construed nature they are deemed laws of the occupied strictly against the government and liberally territory rather than the occupying enemy. they are Doctrine of Equitable Recoupment strictly construed against the tax payer It provides that a claim for refund barred 9. being a remedial 6. construed in favor of the taxpayer.Interpretation and Construction of Tax 1. legislative intention must be considered.In order to declare a tax transgressing the Statutes due process clause of the Constitution it must be Important Points to Consider: so harsh and oppressive in its retroactive 1.The rule of strict construction of tax which an overpayment is made and exemption should not be applied to organizations underpayment is due. 104 PHIL General Rule: Taxes must only be imposed 1062) prospectively Taxpayer’s Suit . Jan. (Hilado vs Collector.On the interpretation and construction of tax application (Fernandez vs Fernandez. however. 104171.A tax amnesty. . Important Points to Consider VIII.The law on prescription. should be liberally construed to afford self-executing (Opinion No. 100 PHIL 288) 3. Sec. Apr. CA. the penalty imposed.Tax laws not being penal in character. hence.R.Other Doctrines in Taxation and that it may work to tempt both the collecting agency and the taxpayer to delay and neglect Prospectivity of Tax Laws their respective pursuits of legal action within the period set by law. (CIR vs 7.When the law so provides for such liberal limitation in the assessment and collection of construction. 1963) 1. the 3. Feb. No. 99 statutes.In case of doubt. disbursement of public funds derived from taxation that the taxpayer’s suit may be allowed. Of protection as a corollary. 24. however. 30.Tax laws are neither political nor penal in 2. 20.Tax exemption are personal. liberally in favor of the grantee in the following: Example: NIRC provides for statutes of a.
. such and charges. The Commissioner of Customs and his The Government is not estopped by the subordinates with respect to the mistakes or errors of its agents. G. or in extent of tax enforcement duties are collecting any such liability. 1. TAX ATION San Beda College of LAW – ALABANG c. summoning. G. Provincial. Effecting and administering the supervisory and police powers conferred to it by the Tax Code or other Agencies Involved in Tax Administration laws. The head of the appropriate correct application of statutes (E. erroneous collection of national internal revenue application and enforcement of law by taxes on imported goods. 15 April 1988. government office and his Inc. those in favor of charitable institutions. Assessment and Collection of all political subdivisions. therewith. as. decided in its favor by the Court of Tax Appeals and the ordinary courts. 1968). Rodriguez. delegated to the Regional Directors and Revenue District Officers. the interpret provisions of the NIRC and non-application of estoppel to the government other tax laws. et. L-23041. Execution of judgment in all cases 7. Exclusive and original power to 6 Feb 1997 that like other principles of law.The power to tax is presumed to exist. estoppel does not apply to Commissioner with respect to receipt deprive the government of its right to raise of payments of internal revenue taxes defenses even if those defenses are being raised authorized to be made through banks.A. its b. al. Collector of Internal Revenue. national internal revenue taxes. subordinates with respect to the July 31. the preclude the subsequent findings on taxability following are constituted as agents of the (Ibid. Enforcement of all forfeitures. d.R.Exemptions in favor of the Government. TAX ADMINISTRATION AND ENFORCEMENT e. a. City and Municipal Government” assessors and treasures for local and real property taxes.) Bureau of Internal Revenue Exceptions: • Powers and Duties The Court ruled in Commissioner of Internal Revenue vs.) Commissioner: The principle of tax law enforcement is: a. al. It is the correctness of any return or in noteworthy to note that the BIR is determining the liability of any person largely decentralized in that a great for any internal revenue tax. 1969. 66838. public officers do not block the subsequent b. 12 of the 1997 NIRC. June 27. f. L- 19627. fees d. Nowhere is it more true than National Internal Revenue Taxes in the field of taxation (CIR vs. 117982. penalties and fines connected 6. Bureau of Internal Revenue and the examining and taking testimony of Bureau of Customs for internal revenue persons for purposes of ascertaining and customs law enforcement. No. Obtaining information. only for the first time on appeal (CIR vs Procter & Gamble Phil.) collection of energy tax. No. Estoppel does not apply to Under Sec.R.The tax laws are presumed valid. c.. and c. C. Abad. vs.Exemptions to traditional exemptees. Rule of “ No Estoppel Against the 2. the state cannot be estopped by the neglect of its Agents and Deputies for Collection of agents and officers.. et. subject to review by admits of exceptions in the interest of the Secretary of Finance. Banks duly accredited by the Similarly. It is a settled rule of law that in the performance of its governmental functions.
L-24213. is an assessment wherein the tax assessor has no power to act at all Estoppel Against the Taxpayer (Victorias Milling vs.R.R. CTA. The taxpayer did not file any Commissioner to assess will result in the return at all. therefore. to compel him to assess a tax after 2. 98 Phil 290) Nature and Kinds of Assessments In the absence of any proof of any irregularities in the performance of An assessment is the official action of official duties. The amount ascertained exceeds that which is shown as 3. (Sy Po. as where injustice will c. G. In CIR vs. acceding to the taxpayers request. vs. (Sec. 8 Aug 1988 may be the notice to the effect that the All presumptions are in favor of tax amount therein stated is due from the assessments (Dayrit vs. 23 Oct 1992). (Bisaya Land Failure to present proof of error in the Transportation Co. reinvestigation have the effect of placing him in estoppel. No. taxpayer that the payment of the tax or 26 Sept.This result to the taxpayer. the power to assess but errs in the Suyac. postponed the collection Principles Governing Tax Assessments of its liability. 1988) deficiency stated therein. vs CIR. 13 Mar 1968) While the principle of estoppel may not be d. G. assess. an assessment will not an administrative officer determining the be disturbed.Tax is assessed by A party challenging an appraiser’s the taxpayer himself. 56 [B] ]1] encroachment on executive functions and [2] 1997 NIRC) (Meralco Secuirities Corp.C.This is an assessment made by the tax assessor 2.) requests for the reinvestigation of its tax liabilities such that the government. L- 36181 and L-36748. Mandamus to compel the 3. this is not assessment wherein the assessor has necessarily true in case of the taxpayer. No amount is shown in the investigation if he finds no ground to return or. Self-assessment. No amount of tax due from a taxpayer. CTA. TAX ATION San Beda College of LAW – ALABANG justice and fair play. Cruz. 104151 and 105563. Illegal and Void Assessments. actual facts. CIR. assessed for the following reasons: 1. 10 July 1998) b. Erroneous Assessment – This is an invoked against the government. (Sec. G. 10 Mar 1995) a. L-39910. value is (Caltex vs. 105 Phil 1338) assessment will justify judicial affirmation of said assessments. Vs. Savellano.C. 56 [A] {1]. Mandamus will not lie return. Deficiency Assessment. Assessments are prima facie inasmuch as his previous requests for presumed correct and made in good faith. Assessment is discretionary on the part tax by the taxpayer in his of the Commissioner. 1997 NIRC) 104781. the taxpayer made several exercise of that power (Ibid. The liability test of judicial scrutiny it must be based on is determined and is. In order to stand the investigation is conducted.R. The taxpayer cannot later on be permitted to raise the defense of prescription 1. The amount is finding of value is required to prove reflected in the tax return that is filed not only that the appraised value is by him and the tax is paid at the time erroneous but also what the proper he files his return. The taxpayer has the duty of proving otherwise (Interprovincial Autobus vs. C. (CIR Classifications: vs C. No. 104 Phil 819. . or it 81446. Assessments should not be based on whereby the correct amount of the tax presumptions no matter how logical the is determined after an examination or presumption might be.
inquiry G. the same may be (Sec. L- 21108. Although Sec. employers. assessments cannot be delegated. (Cu Unjieng. vs. the administrator should be the party to whom the assessment should be sent (Republic vs. 1966). When the inspection of the return is to assess taxes may be delegated. Assessment Based on the Best Evidence the decedent Obtainable Means Employed in the Assessment of Taxes The law authorizes the Commissioner to assess taxes on the basis of the best evidence obtainable in the following cases: A. if a person fails to file a return or other document at the time prescribed by The Tax Code requires that after the return law. dela Rama. etc. Best Evidence Obtainable refers to any statement or declaration has in the meantime data. al. certain exceptions. and in behalf of the Commissioner of 2. clients or patients. 8 June 1993).R. 29 Nov. the exercise of his discretion there is evidence of arbitrariness and grave abuse of discretion as to go beyond The aforesaid rule. 33 of the settled that the power to make final Secretary of Finance. Assessments must be directed to the right himself (Vera vs Cusi L-33115. 1997 NIRC) modified. (City Lumber vs. within three (3) days from facie correct and sufficient for all legal purposes. (Sec gathered by internal revenue officers from 6[A]. the date of such filing. Examination of Returns: Confidentiality Rule 1. Any his knowledge and from such information as he return. Posadas. When inspection is authorized under Internal Revenue is valid. the taxpayer 1979). 71 of the 1997 NIRC vendees and from all other sources. record. with whom provides that tax returns shall constitute public the taxpayer had previous transactions or from . When the production or inspection thereof is authorized by the taxpayer 5. TAX ATION San Beda College of LAW – ALABANG Except: records. it is necessary to know that these are confidential in nature and may not be inquired The BIR Commissioner may be into in unauthorized cases under pain of penalty compelled to assess by mandamus if in of law provided for in Sec 270 of the 1997 NIRC. if for example. and not the heirs of B. into the income tax returns of taxpayers may be authorized: 4. in the result. is subject to statutory authority (Maceda vs. he willfully or otherwise files a false or representative shall examine the same and fraudulent return or other document. However. 8829. however. However. Domingo. When the production of the tax return person to whom a duty is delegated is material evidence in a criminal case cannot lawfully delegate that duty to wherein the Government is interested another. changed or amended. L-18611. An authorized upon the written order of assessment signed by an employee for the President of the Philippines. the upon notice and demand from the Commissioner Commissioner makes or amends the return from or from his duly authorized representative. it is the Finance Regulation No. or is filed. No. papers. the Commissioner or his duly authorized 2. The 3. statement or declaration filed in any office can obtain through testimony or otherwise. being assessed is an estate of a decedent. The tax or the deficiency of the tax so assessed shall be paid When the method is used. 6 [B]. et. The authority vested in the Commissioner 1. 58 Phil 360) 4. provided that no notice for audit or investigation of such return. In the following cases. or any evidence been actually served upon the taxpayer. documents. 1997 NIRC) government offices or agencies. Hence. Macaraig. corporations. assess the correct amount of tax. tenants. 29 June party. 30 Jan 1964). authorized to receive the same shall not be Assessments made as such are deemed prima withdrawn. lessees.
the application for compromise shall not be considered unless and until he waives in .A. In that case. the value of the property shall be inventory-taking of goods of any taxpayer as whichever is the higher of : (1) the fair market a basis for assessment. is not declaring his correct income. of his financial incapacity to pay his tax liability. 6 [C]. the penalties prescribed unless paid within the assessed the corresponding deficiency income time fixed in the demand made by the and specific taxes. value as determined by the Commissioner. on the basis of the preceding year or quarter. That he intends to leave the that a report required by law as basis for the Philippines or remove his property assessment of any internal revenue tax has not therefrom. Notwithstanding any contrary provisions of R. 1997 NIRC) appeal. TAX ATION San Beda College of LAW – ALABANG whom he received any income. of taxpayers. That the taxpayer hides or conceals his any such report is false. Fixing of Real Property Values The Commissioner is authorized at any time For purposes of computing any internal during the taxable year to order the revenue tax. and of a taxpayer terminated at any time when it shall come to his knowledge: 2. The finding made in the surveillance may be used as a basis for Examination of bank deposits enables the assessing the taxes for the other months or Commissioner to assess the correct tax liabilities quarters of the same or different taxable years. That he performs any act tending to A case in point on the use of the best obstruct the proceedings for the evidence obtainable is Sy Po vs CTA. been filed or when there is reason to believe that c. 1405. upheld the legality of the assessment. collection of the tax for the past or there was a demand made by the Commissioner current quarter or year or to render the on the Silver Cup Wine Company owned by same totally or partly ineffective petitioner’s deceased husband Po Bien Seng. That the taxpayer is retiring from under Sec. Inquiry into Bank Deposits observation or surveillance. 204 (A) (@) of the Tax Code by reason business subject to tax. after ascertaining b. Inventory-Taking. his business operation may be placed under F. the immediate payment of the tax for the period so declared terminated and the tax for the The investigators. The unless such proceedings are begun demand was for the taxpayer to submit to the BIR immediately. However. C. or such portion thereof wines seized and the sworn statements of the as may be unpaid. on Commissioner (Sec. a decedent to determine his gross The Commissioner shall declare the tax period estate.A. 6 [d]. 1997 NIRC) confidential under R. bank deposits are (Sec. the Commissioner is authorized to inquire into the bank deposits of. incomplete or erroneous. 1997 NIRC). In this case. so BIR investigators raided the The written decision to terminate the tax factory and seized different brands of alcoholic period shall be accompanied with a request for beverages. property. or (2) the fair market value as shown in the schedule of values of the Provincial and City Assessors for If there is reason to believe that a person real tax purposes (Sec 6 [E]. Said taxes shall be due and factory’s employees on the quantity of raw payable immediately and shall be subject to all materials consumed in the manufacture of liquor. D. any taxpayer who has filed an application for compromise of his tax liability a. 1405 and other general or special laws. sales or receipts for internal revenue tax purposes. Surveillance and Presumptive Gross Sales and Receipts E. The Supreme Court. for examination the factory’s books of accounts and records. Termination of Taxable Period 1. or d.
reason to believe that any such report is false. Conviction in such cases. the to be maintained. This authority has been upheld by the not prove the specific source of courts in a long line of cases. 1405. (Perez vs. he Net Worth Method in Investigation refuses to produce them (Inadequate Records). as in any incomplete or erroneous. the need for evidence of a obtainable whenever a report required by law as likely source of income becomes a basis for the assessment of any national internal prerequisite for a successful revenue tax shall not be forthcoming within the prosecution. Basic Concept and Theory (b) That there is evidence of a possible source or sources of The method is an extension of the basic income to account for the increase accounting principle: assets minus liabilities in net worth or the expenditures equals net worth. 1997 NIRC. rests on proof beyond reasonable doubt. otherwise known as “inventory method of proof where the few records method of income tax verification” is a very of the taxpayer were destroyed. provides However. when the taxpayer for a broad and general investigatory power to is criminally prosecuted for tax assess the proper tax on the best evidence evasion. courts are unanimous in unexplained increase in net worth of a taxpayer is holding that when the tax case is civil presumed to be derived from taxable sources. or the taxpayer has no books. notable among income. 103 assumption that most assets are Phil 1167. . to effective method of determining taxable income require more would be tantamount to and deficiency income tax due from a taxpayer. 1997 NIRC). The theory is that the matter. 43. 6[B]. in civil cases. supra) Moreover. or if he has books. This reasonable on the basic which is the leading case of Perez vs. or when there is always with the Government. for. The increase or decrease in net worth is adjusted by adding all non-deductible items and subtracting therefrom In all leading cases on this non-taxable receipts. TAX ATION San Beda College of LAW – ALABANG writing his privilege under R. holding that skillful concealment is an inevitable barrier to proof. taxpayer is in a position to explain the discrepancy. in nature. CTA.A. CTA. The method is a practical necessity if a derived from a taxable source and fair and efficient system of collecting revenue is that when this is not true. Court. This method of forced to resort to the net worth investigation. criminal case. 43-72. 6[F]. accounts do not clearly reflect his income. The taxpayer’s net worth is (Need for evidence of the sources determined both at the beginning and at the end of income). the assessor need 1997 NIRC. Sec. net worth method and other indirect methods of As stated by the Supreme establishing taxable income is found in Sec. of the same taxable year. The basis of using the Net Worth Method of investigation is Revenue Memorandum The Government may be Circular No. The burden of proof is time fixed by law or regulation. The Legal Source of authority for use of burden of proof is upon the taxpayer the Method to show that his net worth increase The Commissioner’s authority to use the was derived from non-taxable sources. and such waiver shall constitute the authority of the Commissioner to inquire into bank deposits of the taxpayer (a) That the taxpayer's books of (Sec. direct proof of sources of income is not essential-that the government is not required to negate all possible non-taxable sources of the alleged net worth increases. or under Conditions for the use of the method other general or special laws.
that the validity of the result of any 4. 1969) taxable items. They are: This is an essential condition. losses from sales or exchanges refusal or failure to pay taxes and/or other of property between members violations of taxing provisions. sweepstakes winnings. opening net worth. adjustments to avoid the inclusion of what otherwise are non-taxable receipts. inheritance and gift Additions to the tax consist of the: taxes. The Statutory Offenses and Penalties following non-deductibles. as the case may be. compensation for injuries or The courts have uniformly stressed sickness. personal. 5. vs. the 2. (c) That there is a fixed starting point 10. election expenses and other (1) civil penalty. non-taxable capital gains. and the like or opening net worth. living or family Additions to the tax are increments expenses. to the basic tax incident due to the 2. as surcharge. (Proper adjustments to conform to the income tax laws) Enforcement of Forfeitures and Penalties Proper adjustments for non- deductible items must be made. whole superstructure usually fails. 6. Inc. non-taxable taxpayer’s financial condition can items should be deducted therefrom. gifts and bequests the starting point or opening net received. non-deductible contributions. which may either be 25% or . gifts to others. considered to be the cornerstone of a net worth case. CIR. If 1. premiums paid on any life taxpayer’s non-compliance with certain insurance policy. 6. erroneously listed although equitable credit adjustments were already paid. L-21551. TAX ATION San Beda College of LAW – ALABANG 8. will depend entirely upon a correct 5. 7. worth is proven to be wrong. legal requirements. like the taxpayer’s 3. must be added to the increase or decrease in the net worth: 1. net capital loss. inheritance. the taxpayer’s entries in the books deductible expenditures were relating to indebtedness to certain made and correct. a date beginning with a taxable year or prior to it. interest on government securities and the like (d) That the circumstances are such that the method does not reflect Increase in net worth are not the taxpayer’s income with taxable if they are shown not to be the reasonable accuracy and certainty result of unreported income but to be and proper and just additions of the result of the correction of errors in personal expenses and other non. other non-deductible taxes. otherwise known expenses against public policy. Additions to the Tax 1. 30 Sept. fair and creditors. at which time the On the other hand. of the family. income taxes paid. 3. (Fernandez Hermanos given by way of eliminating non. 9. estate.. proceeds of life insurance investigation under this method policies. be affirmatively established with These items are necessary some definiteness.e. 4. i.
show b. Co. interest per annum on the delinquency Republic Cement Corp. 8 May 1996). C. The amount so added to the tax the instances when the imposition of the shall be collected at the same time.A. does not authorize where such return or list is voluntarily the Commissioner to extend the time filed by the taxpayer without notice prescribed for the payment of taxes or to from the CIR or other officers. In one case. and it is accept them without the additional shown that the failure to file it in due time was due to a reasonable cause. (Connel Bros. 6 Aug. 1188794. No. 30. In the case of failure to make and file a Chinese on certain dates. If the withholding agent is the 1. 26 Dec. A Subsequent reversal by the BIR of a liable for the additions to the tax prior ruling relied upon by the taxpayer prescribed (Sec. G. Where a doubt existed on the part of the Bureau as to whether or not R. applicable regulations thereby or a government owned or controlled resulting in delay in the payment of corporation. G. Supreme Court held that the fact that on 60126. 1997 NIRC). 25 Sept. Posadas. L- responsible for the withholding and 15470. General Considerations on the Addition to tax An extension of time to pay taxes granted by the Commissioner does not a. (CIR vs. in 25% surcharge had been waived: the same manner. 5431 abolished the income tax exemptions of corporations (including Surcharge electric power franchise grantees) The payment of the surcharge is except those exempt under Sec. 1975) imposed in the Tax Code.(Philippine Refining Company vs. 1985) account of riots directed against the 4. 247[b]. 1997 NIRC) Government. L-35677. L-26869. 27 mandatory and the Commissioner of (now. vs CIR. 248 and 249 [C]. and charges Cu Unjieng. revenue taxes on time. . (CIR vs. CA. 1983) 3. 10 (Secs. supra). they were return or list within the time prescribed prevented from paying their internal by law. the employee thereof taxes. a mistake in the interpretation of the political subdivisions or instrumentalities. with any authority to waive or dispense with the collection therof.A. vs. fees.. tax apply to all taxes. however. Where the taxpayer in good faith made government or any of its agencies. No. 460) (2) interest either for a deficiency The Commissioner is not vested tax or delinquency as to payment. (Secs. TAX ATION San Beda College of LAW – ALABANG 50 % of the tax depending upon the penalty (Lim Co Chui vs.. Additions to the tax or deficiency excuse payment of the surcharge (CIR vs. 1997 NIRC) Aug. not due to willful neglect. CIR. The following cases. 47 Phil nature of the violation. and as part of the tax. Sec. 1963) remittance of the tax shall be personally 2. The penalty and interest are not (3) other civil penalties or penal but compensatory for the administrative fines such as for failure to concomitant use of the funds by the file certain information returns and taxpayer beyond the date when he is violations committed by withholding supposed to have paid them to the agents. 1997 NIRC) such may also be a ground for dispensing as the 25% surcharge and the 20% with the 25% surcharge. c. the Internal Revenue is not vested with any imposition of the surcharge may be authority to waive or dispense with the dispensed with (Cagayan Electreic collection thereof.R. the Power & Light Co.R. 247 to 252.
249 [A]. VAT Interest is classified into: 4. 1997 NIRC) 1. Administrative 1. or 1. or amount of tax due on the return. Failure of a Withholding Agent to twenty percent (20%) per annum. Civil Action (3) A deficiency tax. Compromise 5. Sources of revenues: (Sec. but .Income tax 2.Seizure by the government of personal property. if the taxes are not 3. Other Administrative any return required to be filed. in order to avoid the before the date prescribed for its payment. Levy of Real Property This kind of interest is imposed in case 3. Failure of a Withholding Agent to Collect and Remit Taxes This is an increment on any unpaid amount of tax. Forfeiture (1) The amount of the tax due on 6. as the 7. (Sec. shall be subject to the interest of 20% per annum. 249[d].Other as imposed and provided by BIR term is defined in this code. or imposition of the surcharge. Interest on Extended Payment voluntarily paid. 249 [B]. Administrative Offenses 1. assessed at the rate of 3. or any 2. from the date prescribed for payment until the amount is fully paid. Imposed when a person required to pay the tax is qualified and elects to pay the tax on KINDS installment under the provisions of the Code. reasonable causes for failure to file the 1997 NIRC) return on time in the form of an affidavit. TAX ATION San Beda College of LAW – ALABANG no surcharge will be added to the fails to pay the tax or any installment thereof. Excise tax 1. Distraint of Personal Property 2. to be followed by its public sale. tangible or intangible. the where the Commissioner has authorized an taxpayer must make a statement extension of time within which to pay a tax or a showing all the facts alleged as deficiency tax or any part thereof. Estate Tax and dono’r tax 3. Failure to File Certain Information Returns Interest 2. Other percentage taxes 5. to enforce the payment of faces. REMEDIES OF THE GOVERNMENT or such higher rate as may be prescribed by rules and regulations. Judicial which no return is required. Deficiency interest 6. which shall be assessed and collected from the date prescribed for its payment until the full • Enumeration of the Remedies payment thereof (Sec. 1997 NIRC) I. Documentary stamp taxes Any deficiency in the tax due. In any part of such amount or installment on or such case. Distraint. Delinquency interest 2. Remedies or (2) The amount of the tax due for II. or such Refund Excess Withholding Tax higher rate as may be prescribed y rules and regulations. Criminal Action surcharge or interest thereon on the due date appearing in • Distraint of Personal Property the notice and demand of the Commissioner. Tax Lien of failure to pay: 4. which should be attached to the return.
at An immediate step for Such immediate step is the dwelling or place of business collection of taxes not necessary. signed by the officer. manager. Requisites: 2. requisite no. 1. tax due and with someone of suitable age where amount due is may not be definite or and discretion definite. Taxpayer is delinquent in the payment of a. 4. Taxpayer must fail to pay delinquent tax at president. 1 is not essential (see b.000. of distraint or or by leaving a list of left either with the owner or person garnishment. c. abatement of the collection of tax as the cost of c. Disposition of proceeds of the sale. b. other responsible officer of the 4. 1. 205 TC). Constructive – The owner is merely place of sale and the articles distrained. taxpayer whether or less delinquent or not There is actual taking or Taxpayer is merely possession of the prohibited from How Actual Distraint Effected property.000.000. same from whom property was taken. Bank Accounts – garnishment same might even be more than P100. association. Actual – There is taking of possession 1. authority for such person to pay In keeping with the provision on the CIR his credits or debts. taxpayer’s personal property. Copy of an account of the property or by service or warrant receipt of the property distrained. treasurer or time required. Constructive Distraint 1. warrant upon taxpayer and upon 3. Time and place of sale. In case of Tangible Property: Effected by having a list Effected by requiring of the distraint property the taxpayer to sign a a. commissioner or his due In excess of Made on the property May be made on the authorized representative P1.00 taxpayer. company or yet prescribed. Procedure: treasurer or responsible officer of the bank. 2. Stocks and other securities tax. Period with in to assess or collect has not issuing corporation. Serve warrant upon taxpayer and president. In case of intangible property. Service of warrant of distraint upon of personal property out of the taxpayer or upon person in possession of taxpayer into that of the government. Posting of notice is not less than two Taxpayer is also diverted of the power places in the municipality or city and of control over the property notice to the taxpayer specifying time and b. TAX ATION San Beda College of LAW – ALABANG a. RDO P1. Where amount involved does not exceed 2. it is being questioned. Warrant shall be sufficient P100 (Sec. manager. prohibited from disposing of his 3. In case of intangible property: 1. Statement of the sum demanded. Serving a copy of the 2. Debts and credits Sec. disposing of his property. Who may effect distraint Amount Involved Actual vs. . Sale at public auction to highest bidder personal property. 206 TC) 1. Leaving a copy of the warrant with the person owing the debts When remedy not available: or having in his possession such credits or his agent.000. Subsequent demand for its payment. • In case of constructive distraint.00 only of a delinquent property of any 2.
enforceable through out the Philippines a. The taxpayer. In the presence of two witnesses of levy is made. Possession pending redemption – owner simply seizes so much of the deposit with not deprived of possession out having to know how much the deposits d. Both cannot be availed of where amount national government. Both are summary remedies for collection the CIR or his deputy may purchase the of taxes. Price: Amount of taxes. refuses to sign: . 1. leave 3. When the amount of the bid for the property under distraint is not equal to the Distraint and Levy compared amount of the tax or is very much less than the actual market value of articles. a. Obligate him to preserve the same properties. Advertisement of the time and place of Grounds of Constructive Distraint sale. Taxpayer is retiring from any business 6. 5. Officer shall write upon the certificate a property distrained. 3. 5. Taxpayer acts tending to obstruct a. sufficient age and discretion. Levy – Act of seizure of real property in order to How constructive Distraint Effected enforce the payment of taxes. Philippines. violating the confidential nature of bank . the taxes are not voluntarily to paid.Cannot be extended by the courts. him b. Procedure: c. Where Taxpayer or person in possession c. Require taxpayer or person in possession after seizure. If at any time prior to the consummation on said purchase price at 15% per annum of the sale. and property is located. The property may be sold at public sale. Taxpayer is intending to leave the owner. accounts for no inquiry is made. Redemption of property sold or forfeited 4. Bank accounts may be distrained with out sale or declaration of forfeiture. BIR c. the redemption. The excess shall be turned over to 2. subject to tax. . Service of written notice to: a copy in the premises where a. a. Bank shall turn over to CIR so much of the bank accounts as • Levy of Real Property may be sufficient. Prohibit him from disposing the property from disposing the 1. Amount of tax and 2. or 3. Time to redeem: one year from date of Note: sale or forfeiture . penalties and are or where the money or any part of it interest thereon from date of delinquency came from. b. goods distrained shall be restored to the owner. b. if 1. description of the property upon which b. Taxpayer hides or conceals his property. RD where property is located.Begins from registration of the deed of 1. Sale at public auction to highest bidder. International Revenue officer shall prepare property in any manner. with out a duly authenticated certificate showing the authority of the CIR. involved is not more than P100. Officer shall prepare list of the 2. Penalty due. Person entitled: Taxpayer or anyone for collection proceedings. Sign a receipt covering property • The requisites are the same as that of distrained distraint. TAX ATION San Beda College of LAW – ALABANG 2. distrained property on behalf of the 2. 1. all proper charges are paid to from date of purchase to date of the officer conducting the same. 4. Name of taxpayer b. Disposition of proceeds of sale. to the date of sale together with interest 2. To remove his property there from.
1. provided Levy – forfeiture by government Enforcement of Tax Lien vs. in distraint the property seized must be that taxes. 1. Taxpayer must have a tax liability. demonstrates a clear inability to pay the 3. Levy – Taxpayer can redeem properties regardless of its owner. Destruction of the property subject to the than the prescribed minimum lien. Duration: 1. to transfer the was served but from the time the tax was title to the property with out of an order due and demandable. Distraint authorized where there is no bidder or the A tax lien is distinguished from disttraint in highest bid is not sufficient to pay the that.000. Attaches not only from time the warrant declaration of forfeiture. the taxpayer is still liable. in default of the payment of taxes. by collected.000. This is superior to judgment claim of 1. Prescription of the right of the government cases. Philippines when a person liable to pay a tax neglects or fails to do so upon When taxes may be compromised: demand. When basic tax involved exceeds office of register of Deeds. levied upon and sold/forfeited to the government. TAX ATION San Beda College of LAW – ALABANG 3. Payment or remission of the tax b. Those already filed in court 4. Upon all property and rights to property 3. • Enforcement of Tax Lien Requisites: Tax Lien: A legal claim or charge on property. It is the duty of the Register of Deeds private individuals or parties concerned upon registration of the 2. 2. Effectivity against third persons: b. rates. Only when notice of such lien is filed by the CIR in the Register of Deeds Limitations: concerned.00 or judgment creditor. The financial position of the taxpayer and costs. purchases or P1. Distraint – forfeiture by government. of the taxpayer. with interests. Minimum compromise rate: Extinguishment of Tax Lien a. 1 and 2. penalties 2. avoid litigation or put an end to one already commenced. to assess or collect. from a competent court 2. 2. . a. Distraint – Taxpayer no given the right of property in respect to the tax is assessed. Criminal violations. Note: Note: 1. of an amount to be paid by taxpayer. Distraint – personal property In case Nos. There must be an offer by taxpayer or CIR. penalties and costs. established by law as a security 2. Failure to file notice of such lien in the a. There must be acceptance of the offer in A lien in favor of the government of the settlement of the original claim. real or personal. except: belonging to the taxpayer. including all expenses. b. is Compromise: A contract whereby the parties. Under nos. Where settlement offered is less 4. Nature: 3. 40% of basic tax assessed – other 2. either 1. although it need not be the 5. Extent: assessed tax. reciprocal concessions. A reasonable doubt as to the validity if the Exists from time assessment is made by claim against the taxpayer exists. 10% of the basic tax assessed – in case of financial incapacity. Subject to approval of Evaluation Board 3. Tax redemption lien is directed to the property subject to the tax. 1. there is no Levy – real property more tax liability. the CIR until paid. Those involving fraud. The remedy of distraint or levy may be • Compromise repeated if necessary until the full amount. not 4. 3 and 4.
a return of the taxes and penalties. (wine. manufactured oils. In case of personal property – by the Revenue Collection Officer seizure and sale or destruction of e. enforce the compromise. cigars regional offices involving basic taxes of P 500 K or 4. or about the illicit production 2. b. Personal entitled – taxpayer or exposed for sale. plus the proceeding is duly made. cigarettes. Note: judgment of condemnation and The Register of Deeds is duty sale in a legal action or proceeding. liquors compromise the assessment issued by the 3. It is pain in lieu of a criminal prosecution. If highest bid is for an amount b. Where to be sole: also having the property transferred to another a. Effect of failure to redeem – the specific forfeited property. miscellaneous products. year from forfeiture penalties and costs. TAX ATION San Beda College of LAW – ALABANG injurious to the public health or Delegation of Power to Compromise prejudicial to the enforcement of the law: (at least 20 days after GR: The power to compromise or abate shall not seizure) be delegated by the commissioner. When available: 6. manufactured products of tobacco Remedy in case of failure to comply: 5. notice of not less than 20 days. It is a certain amount of money which the exercise tax. To be destroyed – by order of the • Other Administrative Remedies CIR when the sale for consumption or use of the following would be . products. necessity of an order from a competent 4. labels and tags. Public sale: provided. In case of real property – by a 7. To whom paid – Commissioner or a. 2. When forfeited property to be destroyed court. All other articles subject to 1. Private sale: provided. or sold: a. All apparatus used in or 1. Amount to be paid – full amount of . there is with out the consent of the owner and wrongdoer. tags. 1. How enforced: d. forfeiture shall become absolute.With in two days thereafter. Dies for printing or making IR stamps. Since it is voluntary in character. interest and cost of the sale 3. and other less. distilled spirits E: The Regional Evaluation Board may 2. Forfeiture: Implies a divestiture of property with in imitation of or purport to out compensation. 3. Enforcement of forfeiture 2. b. Right of Redemption: a. the same non-essential items a may be collected only if the taxpayer is petroleum products) willing to pay them. in consequence of a default or be lawful stamps. taxpayer pays to compromise a tax automobile. the original demand. Regard it as rescinded and insists upon of such articles. 2. bound to transfer the title of property civil or criminal. No bidder for the real property a. b. manufactured or removed in violation of the Tax Code. playing cards The CIR may either: 6. Time to redeem – with in one (1) insufficient to pay the taxes. Includes the idea of not only losing but 5. as the case may forfeited to the government with our require. mineral violation. labels or offense. Finance. To be sold or destroyed – depends upon the discretion of CIR Compromise Penalty 1. anyone for him b. c. Effect: Transfer the title to the specific the approval of the Secretary of thing from the owner to the government. it is with 1.
after decision on taxes. b. the judgment of which shall not his tax liability shall have only impose the penalty but also order become final and executory. Dispute same by filing protest with 6. Brought in the name of the issued. Inquiring into bank deposit on past of taxpayers to evade payment. collected or P1. 3. or enforcement of a fine. Making arrest.000. government to collect internal revenue 5. provided there is a prima must be preserved. 8. search and seizure taxes in regular courts (RTC or MTCs. Deportation in case of aliens – on CIR the following grounds b. generally facie showing of willful attempt to evade. or receipt: a. business or occupation or Civil and Criminal Actions: to practice a profession can be 1. Must be with the approval of the surcharges or fees recovered CIR. Exporter’s bond by reasons of financial d.00 per penalty or forfeiture. become final and executory for failure or committed with in the view of the taxpayer to: Internal Revenue Officer or EE. Limited to violations of any depending on the amount involved) penal law or regulation When assessment made has administered by the BIR. Knowingly and fraudulently CTA evades payment of IR taxes. does not arise from 11. Civil Action 4. Requiring proof of filing income tax returns • Judicial Remedies Before a license to engage in trade. Requiring filing of bonds – in the a. 7. in case of action. A. Appeal adverse decision of CIR to a. Any taxpayer who filed b. Giving reward to informers – Sum 2. TAX ATION San Beda College of LAW – ALABANG 1. whichever is lower. case. Manufacturer’s and incapacity his tax liability. A deceased person to following instances: determine gross estate a. 2. a. Inventory – Taking of stock-in-trade action. Use of National Tax Register Does not exonerate taxpayer his civil 9. Government of the Philippines. for recovery and/or fine or penalty imposed and of taxes. independent of any attempt 13. 000. Estate and donor’s tax b. Inspection of books An assessment of a tax deficiency Books of accounts and other is not necessary to a criminal prosecution accounting records of taxpayer for tax evasion. Registration of Taxpayers. and making surveillance. Reason to believe that records do not correctly Will not operate to extinguish taxpayer’s reflect declaration in return. 3. Conducted by Legal Officer of BIR equivalent to 10% of revenues. payment of taxes. Excise taxes application for compromise c. Prescribing real property values imposed by statute. Willfully refuses to pay such B. importer’s bond 14. Imposition of surcharge and Actions instituted by the interest. criminal liability since the duty to pay the tax is 12. Obtaining information on tax liability to pay the tax due. Person failed to issue Effect of Satisfaction of Tax Liability on Criminal receipts and invoices Liability b. Reason: Tax is an obligation. accounts of . Prescribing presumptive gross sales a criminal act. the liability of any person government may still collect the tax in the same 10. Criminal Action tax and its accessory A direct mode of collection of penalties. Thus. within three years after date the tax return was due or was filed Effect of Acquittal on Tax Liability: whichever is later.
1974) amended return (CIR vs. The fraud contemplated by law is prescribed by law for the filing thereof actual and not constructive. Prescription of Government’s Right to Deceitful with the aim of evading the Assess Taxes: deviation from truth of A. 29. 1966) • A return filed before the last day b. 4 SCRA 872) become final and executory. General Rule: correct tax due. Commissioner 21. 222 ic) the grounds for the extinction of criminal action. CA April 30. . The filing thereof is intended and It merely implies a I. Internal Revenue Taxes shall be fact whether intentional. • Instances/Circumstances negating fraud: June 29. Commissioner. Republic the taxpayer. 30. Dec. ( CIR vs. False return Taxes. assessment. Collector.within ten (10) • PRESCRIPTIVE PERIODS/STATUTE OF years after the date of discovery of the LIMITATION omission. It shall be considered as filed on such last must amount to intentional day. • Fraud may be established by the following the law does not require that the : (Badges of Fraud) demand/notice be received within the a. 1964) Note: The satisfaction of civil liability is not one of B. statue of from the discovery of falsity or fraud. 1. c. (Aznar shall commence from the filing of the case. in case it is filed a. Intentional and substantial • An affidavit executed by a revenue office overstatement of deductions of indicating the tax liabilities of a taxpayer exemption and attached to a criminal complaint for c. Kei & Co. Sept. Recurrence of the foregoing tax evasion. A fraud assessment which has 1965. assessed within three (3) years after the last day prescribed by law for the filing of the return or from the day the • Nature of Fraud: return was filed. When the Commissioner fails • A transcript sheets are not returns. impute fraud in the assessment because they do not contain information notice/demand for payment. TAX ATION San Beda College of LAW – ALABANG This is true in case the criminal action is necessary and required to permit the based on the act to taxpayer of filing a false and computation and assessment of taxes fraudulent tax return and failure to pay the tax. A mere mistake the government right to assess the tax is not a fraudulent intent. circumstances consisting it must be (Section 203 of the Tax Code) alleged and proved to exist by clear & convincing evidence Note: (Republic vs. Fraud is never presumed and the beyond the period prescribed thereof. vs. However. avoiding the tax. wrongdoing with the sole object of • In case a return is substantially amended. SCRA 17. the latter is deemed made taken cognizance of in the civil or when notice to this effect is released. cannot be deemed an circumstances. limitation is primarily designed to protect the rights of the taxpayer’s against unreasonable Note: investigation of the taxing authority with respect • Fraudulent return to assessment and collection of Internal Revenue vs. (Basilan Estates. May 20. understatement of tax liability of vs. 23. Where no return was filed . Where a return was filed but the same was Purpose: false or fraudulent – within ten (10) years For purposes of Taxation. (Sinforo Alca vs. Keir. Pascoi Realty Corp. Intentional and substantial prescriptive period. 222 paragraph (a)) correct address of the taxpayer. the • In computing the prescriptive period for fact of fraud shall be judicially assessment. (Sec. Aug. 1999) a.) Exceptions: (Sec. Phoenix. vs. 2. Inc. 1987) b. criminal action for the collection mailed or sent by the Commissioner to the thereof.
. Exceptions: • Limitations: 1. Ret. A. less than that granted by law. tax is imprescriptible. When the Commissioner failed to (Carmen vs. Waiver of statute of limitations – any internal revenue tax. Where the law does not provide for any agreed upon. which has C) Imprescriptible Assessments: been assessed within the period 1. the ordinary 5-year period (now Note: 3 years) would apply (Rep. vs. “not 1.. Where no assessment was made 3. unless there distraint or levy or by proceeding in is a sufficient evidence shaving court within 5 years following the fraudulent intent. 3. Where no return is required by law. 21. When the taxpayer omits to file a lapse of the prescriptive period. Where an assessment was made – sure” as to the real amount of the Any internal revenue tax which has taxpayer’s net income. whichever is later. documentary stamp tax. 1962) a. upon in writing before the 2. may be collected be particular period of assessment. 2. When the Commissioner raised the question of fraud only for the first II. Prescription of Government’s Right to time in his memorandum which Collect Taxes was filed the CTA after he had rested his case. A mere understatement of income limitation may be collected by does not prove fraud. been assessed within the period of e. In such case. Nov. before the expiration of the same is not fraudulent or false. Note: B. without assessment. at anytime c. was filed. General Rule: d. Where the BIR itself appeared. .the three (3) year period of limitation have tax should be collected within 3 agree in writing to the extension of said years after the return was due or period. The waiver to be valid must be executed by the parties before the 2. Where a fraudulent/false return a. return – a court proceeding for the b. of the period previously agreed upon. without assessment. Note: 4. TAX ATION San Beda College of LAW – ALABANG b. Where the commissioner and the and a return was filed and the taxpayer. c. the expiration of 5-year period. Ayala Securities Corp. A waiver is inefficient I it is executed collection of such tax may be filed beyond the original three year. The commissioner can not valid agree within 10 years after the discovery to reduce the prescriptive period to of the omission. 3. Assessment of compensating and the case is appealed to the CTA. March • Limitations: 31. where the Note: bases of which is not required by law to be • Distinction reported in a return such as excise taxes. The agreement extending the period of with intent to evade taxes was filed prescription should be in writing and a proceeding in court for the duly signed by the taxpayer and the collection of the tax may be filed commissioner. allege in his answer to the 1980) taxpayer’s petition for review when 4. The agreement to extend the same within ten years after the discovery should be mode before the expiration of the falsity or fraud. Assessment of unpaid taxes. date of assessment. the tax distinct or levy of by a proceeding sought to be assessed becomes in court within the period agreed imprescriptible. at anytime b. appears that there was an assessment. Where there is a written waiver or • The 10-year prescriptive period for renunciation of the original 3-year collector thru action does not apply if it limitation signed by the taxpayer.
TAX ATION San Beda College of LAW – ALABANG a. (RTC) shall be suspended for the period. If not known. Where assessment of the commissioner is protected & appealed a. of be valid. Where a tax obligation is secured court. During which the to the CTA – the collection begin when Commissioner is prohibited the government file its answer to from making the assessment taxpayer’s petition for review. The running of statute of limitations levy procedure. writing to its assessment after such time. When a proceeding is instituted from the last assessment. Interruption of the Prescriptive Period between the commission and the taxpayer – the prescriptive period 1. (Rep. forfeit a bond and enforce such b. 7. b. or beginning distraint/levy or . the tax may be assessed prior 1. Day of the commission of the violation. by a surety bond – the government . if know. may be raised: a. Collection by summary remedies – It is to the expiration of the period agreed effected by summary methods when upon. lower court but pending decision on appeal. the government avail of distraint and 2. Rules of Prescription In Criminal Cases Prescription. Agreement to extend period of vs. It must be made before the period of prescription A. b. vs. from the time of 4. Rule: All violations of any provision of the Expiration of the period agreed upon to tax code shall prescribe after five (5) an agreement waiving the defense years. Agreement renouncing III. both the commissioner C. Collection by judicial action – The beginning of distraint/levy or a collection begins by filing the proceeding in court for collection complaint with the proper court. March 30. on making an assessment and the 2. 1963) b. it is bailed permanently. When the offender is absent from the Philippines. Note: Prescription is till binding to the • When it should commence? : The five (5) year prescriptive period shall begin to run Taxpayer although made beyond from the such a. Where the action is brought to enforce a compromise entered into IV. time prescribed for the assessment of the tax.If can not be raised for the first time on may proceed thru a court action to appeal. taxpayer – the prescriptive period • When it is interrupted: for collection should be counted a. against the guilty person Lopez. In criminal case – It can be raised even contractual obligation within a if the case has been decided by the period of ten years. 3. In civil case – If not raised in the lower 6. • When it should run again : When the proceeding is dismissed for reason not 5. the period for collection is counted • When does the defense of prescription from the last revised assessment. Where before the expiration of the is ten years. Where the government makes discovery and the institution of judicial another assessment on the basis of proceeding for its investigation and reinvestigation requested by the punishment. Where the assessment is revised Constituting because of an amended return – jeopardy. When tax is deemed collected for and the taxpayer have consented in purposes of the prescriptive period. prescriptive period.
e. Philippines. Filing of claim for tax refund. e. otherwise it is b. When the taxpayer requests deemed waived. taxpayer b. When the taxpayer is out of Judicial the Philippines. from filing an ordinary • Reason: No requirement for assessment action to collect the tax. The assessment does not suspend the criminal commissioner is prevented action. A mere request for 4. Filing of claim for tax credit located. The law on prescription remedial measure proof that its collection may should be interpreted liberally in order to jeopardizes the government protect the taxpayer. When the warrant of distraint reconsideration or or levy is duly served upon reinvestigation (Administrative any of the following person: Protest). with sufficient discretion and and no property could be b. of the tax before the criminal action may When CTA suspends the be instituted. In the event that the collection of the tax the running of the prescriptive has already prescribed. and as defense it must be raised reasonably otherwise it is deemed Note: waived. Entering into compromise 2. When the taxpayer cannot be located in the address given TAXPAYER’S REMEDIES by him in the return. jurisdictional. c. 1. Note: Administrative If the taxpayer informs the Commissioner of any change in (1) Before Payment address the statute will not be suspended. The prescriptive provided in the tax code reinvestigation without any over ride the statute of non-claims in the action or the part of the settlement of the deceased’s estate. for reinvestigation which is 3. a. (1) Civil action 3. Commissioner does not interrupt 5.g. TAX ATION San Beda College of LAW – ALABANG a proceeding in court and for the offender is absent from the 60 days thereafter. and /or the taxpayer. Filing of a petition or request for d. The question of prescription is not granted by commissioner. Appeal to the Court of Tax Appeals . The defense of prescription must be raised by the taxpayer on time. cannot invoke the principle of Equitable The request must not be a recumbent by setting.off the prescribed mere pro-former. Filing a petition for review in Note: the CTA from the decision of • A petition for reconsideration of a tax the Commissioner. In criminal cases for violation of tax code – the period shall not run when a. the government period. 2. Substantial tax against a tax refused to which the issues must be raised. taxpayer is entitled. collection of tax liability of the taxpayer pursuant to Nota Bene: Section 11 of RA 1125 upon 1. his authorized representative (2) After Payment 3. Member of his household a.
inclusive of the newly-discovered or additional evidence that a applicable penalties (3. and period was determined to have carried c. of the letter of demand showing the following: (a) Assessment Notice shall not be required in the his name. 12-99 dated Sept. traded or Request for reconsideration. shall be considered in default. 6.4. he or both. Procedure otherwise. Action for Damages over and automatically applied the same amount claimed against the (2) Criminal Action estimated tax liabilities for the taxable quarter or quarters of the succeeding a. or erring Bureau of Internal d. TAX ATION San Beda College of LAW – ALABANG b. capital ADMINISTRATIVE PROTEST equipment. vehicles. rules and regulations. and (d) date of receipt a. Revenue Regulations No. 6.2. in which case. It may involve a question of fact or law (15) days from the date of receipt of the PAN. When the finding for the deficiency tax thereof. such as. or Taxpayer or his duly authorized representative c. and spare parts. has been sold. the formal letter of demand and assessment notice shall be void.a plea for the transferred to non-exempt persons.1. When a discrepancy has been Disputed Assessment determined between the tax withheld and the amount actually remitted by the withholding agent. the computation of the tax as appearing on the face of the return. re-evaluation of an assessment on the basis of existing records without need of additional If the taxpayer fails to respond within fifteen evidence. may be. Action to contest forfeiture of creditable withholding tax for a taxable chattel. or employees. Issuance of a Formal Letter of Demand and Assessment Notice issued by the Commissioner Issuance of Assessment or his duly authorized representative. (c) designation and following cases: authority to act for and in behalf of the taxpayer.a plea for shall be caused to be issued. 12-99 is the result of mathematical error in dated Sept. (3. reinvestigation. e. A valid PAN shall be in writing stating the law and facts on which the assessment is made. but not limited to. as the case registered mail or personal delivery. a formal letter of demand and assessment notice Request for reinvestigation. It may also involve question of fact or law or both. calling for payment reinvestigation of an assessment on the basis of of the taxpayer’s tax liability. 228 of the 1997 NIRC) If sent by personal delivery. (b) signature. When the excise tax due on excisable Revenue officials and articles has not been paid. Revenue Regulations taxpayer intends to present in the No.1. or b. the taxpayer or his duly authorized representative shall acknowledge receipt thereof in the duplicate copy Under Sec. if acknowledged or received by a person other than the taxpayer himself. Filing of complaint against taxable year. 1999). 1999). Shall state the facts. 228 of the 1997 NIRC a Pre. machineries. (Sec. or jurisprudence on which the assessment is based. When an article locally purchased or imported by an exempt person. Issuance of written a Preliminary Assessment Notice (PAN) after review and evaluation by the Formal Letter of Demand and Assessment Assessment Division or by the Commissioner or Notice shall be sent to the taxpayer only by his duly authorized representative. When a taxpayer who opted to claim a may administratively protest against a Formal refund or tax credit of excess . the laws.
f. and Assessment Notice Number. Date of receipt of assessment notice or Scope of Claims letter of demand. Nature of request whether reinvestigation or reconsideration specifying newly discovered evidence Legal Principle of quasi-contracts or that he intends to present it it is a solutio indebiti (see Art. the from receipt of the assessment notice. Name of the taxpayer and address for the immediate past three taxable years. Amounts and kind/s of tax involved. if the taxpayer fails to file an administrative protest within the reglementary 30-day Failure of taxpayer to state the facts. For this purpose. 27. Itemized statement of the findings to which the taxpayer agrees. upon the filing of the protest. taxpayer only disputes/protests validity of some If the taxpayer fails to comply with this of the issues requirement. applicable law. the protest shall not be deemed validly filed unless payment of If the protest is denied in whole or part. rules and regulations. Documentary evidence as it may deem necessary and relevant to support its protest to be submitted within sixty Several issues in the assessment notice but (60) days from the filing of the protest. No action shall be taken on the disputed Effect of taxpayer’s failure to file an issues until payment of deficiency taxes administrative protest or to appeal BIR’s decision on undisputed issues to the CTA Prescriptive period for assessment or collection of taxes on disputed issues shall be suspended. jurisprudence on which his protest is based shall After the lapse of the 30-day period. and decision shall become final and executory i. the render his protest void and without force and assessment can no longer be disputed effect. reinvestigation of an assessment shall be Collection letter to be issued calling for accompanied by a waiver of the Statute of the payment of deficiency tax. including Limitations in favor of the Government. the assessment shall become final (Revenue Regulation No. the taxpayer g. Assessed already tax collectible. or is the agreed portion of the tax is paid not acted upon within one hundred eighty (180) first. 2142 & 2154 of the Civil request for reinvestigation. which the Commissioner may credit or refund taxes: . Fireman’s assessment. Contents: a. 1985. as a Under Sec. receipt of the said decision. applicable surcharge and/or interest. As provided in Sec. Code). Taxpayer required to pay the deficiency 12-85. Legal Basis b.) tax or taxes attributable to the undisputed A request for reconsideration or issues. if any. Statement of facts and/or law in one hundred (180)-day period: otherwise. days from submission of documents. 228 of the Tax Code. the support of the protest. dated Nov. Itemized schedule of the adjustments adversely affected by the decision or inaction with which the taxpayer does not may appeal to the CTA within 30 days from agree. or from lapse of the h. Taxable periods covered by the principle of solutio indebiti (CIR vs. or assessment becomes final. Fund Insurance Co) d. 204 and 209 of the 1997 NIRC basis for computing the tax due. e. The Government is within the scope of the c. TAX ATION San Beda College of LAW – ALABANG Letter of Demand and Assessment notice within amount should be paid immediately thirty (30) days from date of receipt thereof. either administratively or judicially through an appeal in the CTA.
categorical language. interpretation of the taxpayer’s charter 28. 819) . Written claim for refund or tax credit the tax memo covering the filed by the taxpayer with the Commissioner amount determined to be reimbursable This requirement is mandatory. (Sec. L-16626. and which therefore. vs. Inc. independent single act of voluntary Suspension of the 2-yaer prescriptive payment of a tax believed to be due. (CIR vs. CTA Case No. Li Yao. 107 Phil 232). therefore. Nov. Refers not only to the “administrative” Necessity of Proof for Refund Claims claim that the taxpayer should file within 2 years from date of payments with the BIR. period may be had when: collectible and accepted by the (1) there is a pending litigation government. TAX ATION San Beda College of LAW – ALABANG is made. vs. 1997 (a) Erroneously or illegally assessed or NIRC). 1962). 229. commenced in court within two (2) years from date of payment of tax or penalty (b) Penalties imposed without authority regardless of any supervening event. Categorical demand for reimbursement fact. 29. which can be applied Reasons: (a) to afford the commissioner after proper an opportunity to correct the action of verification. Collector of the face of the return upon which payment Internal Revenue 103 Phil. 1963). (c) Any sum alleged to have been 204 (c) & 229 1997 NIRC) excessive or in any manner wrongfully collected The value of internal revenue stamps Requirement a condition precedent and when they are returned in good condition by the non-compliance therewith bars recovery purchaser may also be redeemed. Dec. CIR 87 Phil 96). Claim for refund or tax credit must be A tax is illegally collected if filed or the suit proceeding thereof must be payments are made under duress. such notice (2) the commissioner in that litigated should then be borne in mind in case agreed to abide by the decision of estimating the revenue available for the Supreme Court as to the collection expenditure (Bermejo vs. (Phil. but also the judicial claim or the action for Refund claim partakes of the nature of an refund the taxpayer should commence exemption which cannot be allowed unless with the CTA (see Gibbs vs. and TAX REFUND TAX CREDIT Statutory Requirements for Refund Claims There is actually a The government reimbursement of issues a tax credit a. Acetylene Co. 1966).. Commissioner. Oct.. Collector of granted in the most explicit and Internal Revenue. collected internal revenue taxes Taxpayer pays under the mistake of b. Johnson and Taxpayer may file an action for refund in Sons the CTA even before the Commissioner Failure to discharge burden of giving proof decides his pending claim in the BIR is fatal to claim (Commissioner of Internal Revenue vs. of taxes relative thereto (Panay Except: Tax credit or tax refund where on Electric Co. L-11875. in relation to the disputed tax. 1321. Inc. as for instance in a case where he is not aware of the existing exemption in his favor at the time payments were made c. against subordinate officer and (b) to notify the any sum that may be government that the taxes sought to be due and collectible refunded are under form the taxpayer question and that. 7. become between the two parties (government part of the state moneys subject to and taxpayer) as to the proper tax to expenditure and perhaps already spent or be paid and of the proper appropriated (CIR vs.. such payment appears clearly to have been erroneous. It must be shown that payment was an Palanca Jr. (Sec.
taxpayer may appeal the same within thirty (30) days after receipt. No. L-16683. otherwise. American Life Ins. May 29..A. 15. No. 29. Jan. Jr. But where Palanca. supra) an appeal. the decision payment of the last installment (CIR vs becomes final and executory. Tax assessed has not been paid. Jan.. Suit or proceeding in the CTA is made 1. (CIR vs. Taxes payable in installment (Sec. but from the end of the taxable Motion for reconsideration suspends the year (Gibbs vs. Must advance new grounds not previously alleged to toll the reglementary period. In case of Income Tax withheld on special circumstances. 18 SCRA 861) to the BIR. TAX ATION San Beda College of LAW – ALABANG Even if the 2-year period has lapsed the Victorias Milling Corp. R. 1125) Appeal equivalent to a judicial action 2-year period is counted form the In the absence of appeal. d. Interest on Tax Refund b. a. suspended for reasons of equity and other 2. he could not appeal the same to the CTA within 30 Withholding Taxes days from notice. Refund or credit after such time earn following: interest at the rate of 6% per annum. it would be merely pro VAT Registered Person whose sales are zero-rated forma. starting after the lapse of the 3-month period to the date the reund or credit is made ( Sec 79 (c) (2) 1997 Corporations NIRC) 2-year prescriptive period for overpaid quarterly income tax is counted not from the date the corporation files its quarterly APPEAL to the CTA income tax return.R. disputed assessment or claim for tax refund or credit. The Commissioner acted with within 30 days from receipt of the patent arbitrariness decision Arbitrariness presupposes inexcusable or obstinate disregard of legal provisions (CIR vs. Final decision or ruling has been unless: rendered on such petition. 11. Hence. 112 (A) Assessment 1997 NIRC).R. pay interest on taxes refunded to the taxpayer c. but from the date the final adjusted return is filed after the taxable year (Commissioner of Internal Adverse decision or ruling rendered by the Revenue vs. the wages of employees. Inc. Effect of Failure to Appeal Assessment . it could not Prescriptive period counted not from become final and executory. (Republic vs. Phil. the date the tax is withheld and remitted De la Rama.. 2-year period computed from the end of the taxable quarter when the sales Requirements for Appeal in Disputed transactions were made (Sec. 105208. Inc. No. 31. Commissioner of Internal running of the 30 –day period of perfecting Revenue. (Roman Catholic Archbishop vs. Nov. G. L-19607. same is not jurisdictional and may be 1966). or effectively zero-rated Coll. 1995). Co.. 1962). Commissioner of Internal Revenue in 83736. Any excess of the taxes withheld over the 2-year prescriptive period for filing of tax tax due from the taxpayer shall be returned or refund or credit claim computed from date credited within 3 months from the fifteenth (15th) of payment of tax of penalty except in the day of April. TMX Sales. supra) the taxpayer adversely affected has not received the decision or ruling. 1992). G. Taxpayer has filed with the Commissioner of Internal Revenue a petition for the reconsideration or The Government cannot be required to cancellation of the assessment..
(see Secs. OFFICIALS 8) allowing or conspiring or colluding with another to allow the unauthorized withdrawal or recall of any return or Taxpayer may file an action for damages statement after the same has been against any internal revenue officer by reason of officially received by the BIR. FILING OF CRIMINAL COMPLAINT AGAINST REVENUE OFFICERS Requirements for Appeal in Refund and Tax Credit A taxpayer may file a criminal complaint against any official. down or rejected any of his offers 229 1997 NIRC). from using defense of excessive or illegal assessment. or b. agent or employee of the BIR a. any act done in the performance of official duty 9) Having knowledge or information of any or neglect of duty. taxpayer’s recourse is under Art 27 of the such knowledge or information to their Civil Code. 7) Making or signing any false entry or entries in any book. In case of willful neglect of violation of the Tax Code. TAX ATION San Beda College of LAW – ALABANG Revenue officer acting negligently or in bad faith or with willful oppression would be a. 3) Knowingly demanding or receiving sums or compensation not authorized or ACTION CONTESTING FORFEITURE OF prescribed by law. Before sale or destruction of the property examination of the books of account or tax to recover the property from the person liability. government. Taxpayer barred. Taxpayer has filed with the CIR a enforcement of the provisions of the Tax Code written claim for refund or tax credit who commits any of the following offenses: within 2 years from payment of the tax or penalty. Sec. failure to report duty. ND . 5. He ceases to be an officer of the collection of the tax by the law and becomes a private wrongdoer. After the sale and within 6 months to conspiring or colluding with another or recover the net proceeds realized at the others to defraud the revenues or sale (see. b. 1997 NIRC) otherwise violate the provisions of the tax Action is partakes of the nature of an ordinary code. CHATTEL 4) Willfully neglecting to give receipts as by law required or to perform any other duties enjoined by law. period of two years from the date of 2) Willful oppression and harassment of a payment regardless of any taxpayer who refused. consideration or compensation. 231. Suit or proceeding is instituted in the 1) Extortion or willful oppression through the CTA also within the same prescriptive use of his office. 204. Tax has been paid. in an action for personally liable. file claim for forfeiture. superior officer. or return. civil action for recovery of personal property or 6) Neglecting or by design permitting the the net proceeds of its sale which must be violation of the law or any false certificate brought in the ordinary courts and not the CTA. or as otherwise required by law. turned supervening cause. declined. mentioned in no. and c. or nay false certificate ACTION FOR DAMAGES AGAINST REVENUE or return. or any other agency charged with the b. or offering or undertaking to seizing the property or in possession submit a report or assessment less than thereof upon filing of the proper bond to the amount due the government for any enjoin the sale. In case of seizure of personal property under 5) Offering or undertaking to accomplish. the owner desiring to contest or submit a report or assessment on a the validity of the forfeiture may bring an action: txpayer without the appropriate a. Assessment is considered correct.
or accepting money or other things of value fore the compromise or settlement b. on missing packages. b. Sec. Claim for refund—a written claim for refund may be submitted by the importer: a. arrival. B. articles lost or destroyed after such conditions. no longer in Customs Custody. TAX ATION San Beda College of LAW – ALABANG 10) Without the authority of law. articles entered under of any charge or complaint for any warehousing entry not violation of the Tax Code. Property in the customs custody shall be subject to sale under the following c. b. Sale of Property packages or shortage before arrival of the goods in the Philippines. abandoned articles. . in the hands or under the control of the importer or a. (see. 269. administrative fine or forfeiture may be affected only. after the tax due. for the satisfaction of the same. Taxpayer’s Remedies In the case of attempted Administrative Recourse importation. In abatement uses such as: b. the provision of this code: and regardless of the ownership while still in the custody or control of the d. Enforcement or tax lien administrative or judicial proceedings in conformity with A tax lien attaches on the goods. TCC) imposed when the importation is unlawful and it may be exercised This is availed of when the tax lien is lost even where the articles are not or by the release of the goods. Seizures The tax liability of the importer constitutes Generally applied when the penalty a personal debt to the government. or 1. demanding a. respectively of the taxpayer Note: Goods in the collector’s This is availed of when the possession or of Customs authorities importation is neither nor pending payment of customs duties improperly made are beyond the reach of attachment. Extrajudicial sale shall have been established by proper 1. A. seized property. withdrawn nor the duties and 1997 NIRC) taxes paid thereon within the Remedies under the period provided under Section Tariff and Customs Code 1908. unless the importation is merely attempted. Government Remedies: c. 1204. other than contraband. person who is aware thereof. TCC. Judicial Action 2. deficiencies in the contents of 3. while the goods are still within the customs jurisdiction. taxes or other charges collectible by the Proceeds of sale are applied to the Bureau of Customs. Any deficiency or excess is expiration of the period allowed for the account or credit. Any articles subject to a valid government lien for customs duties. is fine or forfeiture which is enforceable by action (Sec. after liability to a.
Protest 6. and 1. TCC) 2. dead or injured animals. fees or Made on the property property of any other money charges. property. for manifest classical errors. Forfeiture a. tangible or intangible. . Taxpayer is merely There is actual taking or prohibited from c) fines forfeitures or other penalties possession of the disposing of his imposed in relation thereto. Levy of Real Property 2. Civil Action see earlier discussion on the 8. Note: The owner or importer may c. Distraint of Personal Property f. only of a delinquent taxpayer whether b) seizures. TAX ATION San Beda College of LAW – ALABANG d. (see section 1701-1708. In seizure cases 7. property. detention or release of taxpayer. articles lost or destroyed Administrative e. Other Administrative Remedies see the earlier discussions on “Customs Protest Cases” Judicial b. In case of thus relieving himself of the tax intangible property. Compromise are re-exported 5. Effected by having a list Effected by requiring d) other matters arising under the of the distraint property the taxpayer to sign a customs Law or other laws or by service or warrant receipt of the property administered by the Revenue of of distraint or or by leaving a list of Customs. Constructive Distraint May be made on the a) liability for customs duties. Constructive – The owner is merely of Appeals which has exclusive prohibited from disposing of his personal jurisdiction to review decisions of the property. Taxpayer is also liability but not from the possible diverted of the power of control over the criminal liability. tax due where amount due is may not be definite or Enumeration of the Remedies definite. Criminal Action subject Distraint of Personal Property c. delinquent or not property affected.Seizure by the government of property personal property. it is being questioned. Tax Lien In drawback cases where the goods 4. Settlement of case by the payment of fine or redemption of forfeited Distraint. Commissioner of Custom in cases involving: Actual Distraint. to be followed by see earlier discussions on the its public sale. Judicial relief 3. same An immediate step for Such immediate step is Remedies of the Government collection of taxes not necessary. to enforce the payment of faces. garnishment. Actual – There is taking of possession of abandon either expressly or By personal property out of the taxpayer into importation in favor of the Government that of the government. and property. if the taxes are not voluntarily subject paid. The taxpayer may appeal to the Court d.
company or association. 3. b. Disposition of proceeds of the sale.000. 205 TC). Taxpayer is delinquent in the payment of tax. Period with in to assess or collect has not yet prescribed. Time and place of sale. Prohibit him from disposing the property from disposing the property in a. Service of warrant of distraint upon taxpayer or upon person in possession of 4. Statement of the sum demanded. Subsequent demand for its payment. Obligate him to preserve the same How Actual Distraint Effected properties. requisite no. c. In case of constructive Serving a copy of the warrant upon distraint. with out the authority of distrained. Require taxpayer or person in possession authorized representative P1. at the dwelling or place of business Requisites: and with someone of suitable age and discretion 5. (see Sec.000. Posting of notice is not less than two places in the municipality or city and c. Debts and credits on the abatement of the collection of tax as the cost of same might even be more than P100. 1 is not essential taxpayer and upon president. Taxpayer must fail to pay delinquent tax at 4. Copy of an account of the property any manner. 4. 3. 6. 8. RDO or less a.00 4. treasurer or other responsible officer of the issuing When remedy not available: corporation. In keeping with the provision b. left either with the owner or person . Where amount involved does not exceed P100 (Sec. 6.000. authority for such person to pay CIR his credits or debts. the CIR. a. Warrant shall be sufficient taxpayer’s personal property. 206 TC) manager. Bank Accounts – garnishment notice to the taxpayer specifying time and place of sale and the articles distrained.000. signed by the officer. Sign a receipt covering property distrained b. commissioner or his due In excess of 3. Serve warrant upon taxpayer and president. 5. Sale at public auction to highest bidder treasurer or responsible officer of the bank. manager. Bank shall turn over to CIR so much of the bank accounts as may be sufficient. In case of intangible property: time required. TAX ATION San Beda College of LAW – ALABANG from whom property was taken. Amount How constructive Distraint Effected Who may effect distraint Involved 3. 3.00 to P1. In case of Tangible Property: c. 7. 7. Stocks and other securities 8. Leaving a copy of the warrant with the person owing the debts Procedure: or having in his possession such credits or his agent.
d. BIR simply seizes so much of the deposit with The excess shall be turned over to owner. Philippines. 10. Service of written notice to: 8. penalties and Levy of Real Property interest thereon from date of delinquency to the date of sale together with interest Levy – Act of seizure of real property in on said purchase price at 15% per annum order to enforce the payment of taxes. all proper charges are paid to the officer conducting the same. Officer shall prepare list of the a duly authenticated certificate showing property distrained. Disposition of proceeds of sale. Cannot be extended by the courts. Taxpayer acts tending to obstruct collection proceedings. If at any time prior to the consummation him of the sale. The taxpayer. Penalty due. Officer shall write upon the certificate a description of the property upon which 7. Name of taxpayer b. TAX ATION San Beda College of LAW – ALABANG 4. leave a b. and 9. The requisites are the same as that of distraint. Taxpayer is intending to leave the levy is made. or 9. enforceable through out the Philippines 6. out having to know how much the deposits are or where the money or any part of it Redemption of property sold or forfeited came from. the f. Person entitled: Taxpayer or anyone for 5. a. Note: 11. c. 8. Time to redeem: one year from date of goods distrained shall be restored to the sale or forfeiture owner. property under distraint is not equal to the amount of the tax or is very much less . accounts for no inquiry is made. Advertisement of the time and place of sale. e. 10. Where Taxpayer or person in possession Procedure: refuses to sign: 7. Possession pending redemption – owner distrained property on behalf of the not deprived of possession national government. . h. Sale at public auction to highest bidder. Amount of tax and copy in the premises where property is located. Taxpayer hides or conceals his property. To remove his property there from. The from date of purchase to date of property may be sold at public sale. if after redemption. Taxpayer is retiring from any business subject to tax. c. 4. Bank accounts may be distrained with out violating the confidential nature of bank 12. seizure. RD where property is located. Distraint and Levy compared . In the presence of two witnesses of sufficient age and discretion. When the amount of the bid for the sale or declaration of forfeiture. International Revenue officer shall prepare a. Grounds of Constructive Distraint . than the actual market value of articles. the CIR or his deputy may purchase the g. the taxes are not voluntarily paid. Price: Amount of taxes. Begins from registration of the deed of 6.
Tax repeated if necessary until the full lien is directed to the property subject to the tax. Note: Enforcement of Tax Lien 3. amount. penalties and costs. collected. Failure to file notice of such lien in the office of register of Deeds. Distraint concerned upon registration of the declaration of forfeiture. . Under nos. Both cannot be availed of where amount involved is not more than P100. is regardless of its owner. This is superior to judgment claim of Tax Lien—a legal claim or charge on private individuals or parties property. Distraint – Taxpayer no given the right of judgment creditor.\ or put an end to one already commenced. although it need not be the 6. not Extinguishment of Tax Lien provided 5. In case Nos. 2. 5. to transfer the A tax lien is distinguished from disttraint in title to the property with out of an order that. Upon all property and rights to property belonging to the taxpayer. 7. Attaches not only from time the warrant taxes. 3 and 4. established by law as a security in default of the payment of 4. The remedy of distraint or levy may be property in respect to the tax is assessed. in distraint the property seized must be that from a competent court of the taxpayer. levied upon and sold/forfeited to the government. Distraint – forfeiture by government. Taxpayer must have a tax liability. It is the duty of the Register of Deeds Enforcement of Tax Lien vs. Nature: Compromise A lien in favor of the government of the Philippines when a person liable to pay a Compromise—a contract whereby the tax neglects or fails to do so upon parties. 1 and 2. taxes. 8. the CIR until paid. 5. there is no more tax liability. with interests. Prescription of the right of the government highest bid is not sufficient to pay the to assess or collect. penalties and costs. 7. purchases or 10. Extent: 6. the taxpayer Note: is still liable. 3. There must be an offer by taxpayer or CIR. Payment or remission of the tax Levy – forfeiture by government authorized where there is no bidder or the 6. Distraint – personal property Only when notice of such lien is filed by the CIR in the Register of Deeds Levy – real property concerned. was served but from the time the tax was due and demandable. either real or personal. avoid litigation demand. redemption 8. TAX ATION San Beda College of LAW – ALABANG 7. 9. Both are summary remedies for collection of taxes. Duration: Requisites: Exists from time assessment is made by 4. of an amount to be paid by taxpayer. including all expenses. Effectivity against third persons: 8. Destruction of the property subject to the Levy – Taxpayer can redeem properties lien. by reciprocal concessions.
Effect: Transfer the title to the specific thing from the owner to the government. Criminal violations. of a default or offense. In case of personal property – by Delegation of Power to Compromise seizure and sale or destruction of the specific forfeited property. judgment of condemnation and sale in a legal action or proceeding. as the case may may compromise the assessment issued by the require. No bidder for the real property b. If highest bid is for an amount 4. When basic tax involved exceeds P1. It is a certain amount of money which the When taxes may be compromised: taxpayer pays to compromise a tax violation. c. Subject to approval of Evaluation Board insufficient to pay the taxes. To be destroyed – by order of the CIR when the sale for consumption 3. There must be acceptance of the offer in Compromise Penalty settlement of the original claim. 10% of the basic tax assessed – in case of financial incapacity. Where settlement offered is less than the prescribed minimum 10. cases. in consequence b.000. except: Enforcement of forfeiture a. How enforced: rates. It is pain in lieu of a criminal prosecution. 11. Those involving fraud. Since it is voluntary in character. Minimum compromise rate: 8. enforce the compromise. The financial position of the taxpayer 6. 3. It includes the idea of not only losing but also having the property transferred to another with out the consent of the Limitations: owner and wrongdoer. penalties and costs. or or use of the following would be injurious to the public health or 4. willing to pay them. 5. regional offices involving basic taxes of P 500 K or less. d. 6. 40% of basic tax assessed – other exposed for sale. . When forfeited property to be destroyed Remedy in case of failure to comply: or sold: The CIR may either: c. 4. 9.000. When available: a. In case of real property – by a commissioner. 4. General Rule: The power to compromise or abate shall not be delegated by the d. TAX ATION San Beda College of LAW – ALABANG 6. b. a return of the proceeding is duly made.00 or . Those already filed in court Forfeiture—implies a divestiture of property with out compensation. Regard it as rescinded and insists upon prejudicial to the enforcement of the original demand. Exception: The Regional Evaluation Board civil or criminal. the same demonstrates a clear inability to pay the may be collected only if the taxpayer is assessed tax. c. 5. With in two days thereafter. A reasonable doubt as to the validity if the claim against the taxpayer exists. a.
and other government with our necessity of an order from a manufactured products of competent court. tobacco Other Administrative Remedies 5. Estate and donor’s tax b. products) manufactured or business or occupation or to practice a removed in violation of the Tax profession can be issued. the approval of the Secretary of committed with in the view of the Internal Finance. Inspection of books . automobile. miscellaneous products. whichever is lower. plus and executory. Where to be sold: 7. liquors 3. 2. Requiring filing of bonds – in the following 6. Excise taxes d. To whom paid – Commissioner or seizure) the Revenue Collection Officer 1. Requiring proof of filing income tax returns oils. labels and tags. after decision on h. Dies for printing or making IR 6. To be sold or destroyed – depends upon the discretion of CIR c. Imposition of surcharge and interest. Willfully refuses to pay such tax and its accessory penalties. Private sale: provided. Manufacturer’s and importer’s bond exercise tax. playing cards 4. 4.000. mineral products. Time to redeem – with in one (1) year from forfeiture d. Exporter’s bond 3. search and seizure notice of not less than 20 days. non-essential items a petroleum Before a license to engage in trade. 000. All apparatus used in or about instances: the illicit production of such articles. Right of Redemption: 9. Public sale: provided.00 per case. 12. Giving reward to informers – Sum stamps. Making arrest. 13. manufactured 5. Limited to violations of any penal law or d. Revenue Officer or EE. a. Amount to be paid – full amount of his tax liability shall have become final the taxes and penalties. in equivalent to 10% of revenues. g. cigars Note: The Register of Deeds is duty bound to transfer the title of property forfeited to the 4. surcharges imitation of or purport to be or fees recovered and/or fine or penalty lawful stamps. Effect of failure to redeem – forfeiture shall become absolute. All other articles subject to d. cigarettes. labels or tags. interest and cost of the sale 10. it is with regulation administered by the BIR. Knowingly and fraudulently evades payment of IR taxes. Personal entitled – taxpayer or anyone for him c. c. Deportation in case of aliens – on the following grounds f. there is 8. distilled spirits j. TAX ATION San Beda College of LAW – ALABANG the law: (at least 20 days after i. imposed and collected or P1. Code. (wine.
Prescribing real property values government may still collect the tax in the same action. on past of taxpayers to evade payment. Dispute same by filing protest with CIR 11. independent of any attempt 17. provided there is a prima c. 2. c. Obtaining information on tax liability of any person D. Brought in the name of the Government of Note: The satisfaction of civil liability is not one of the Philippines. Reason to believe that records do not correctly reflect declaration in return. Appeal adverse decision of CIR to CTA 12.\ Does not exonerate taxpayer his civil liability to pay the tax due. Must be with the approval of the CIR. in case of action. Criminal Action A direct mode of collection of taxes. generally within three years after date the When assessment made has become final tax return was due or was filed whichever and executory for failure or taxpayer to: is later. c. or enforcement of a fine. the grounds for the extinction of criminal action. 1. invoices Effect of Acquittal on Tax Liability: d. A deceased person to determine gross estate Effect of Satisfaction of Tax Liability on Criminal Liability d. Any taxpayer who filed application for compromise by reasons of financial Will not operate to extinguish taxpayer’s incapacity his tax liability. Judicial Remedies This is true in case the criminal action is based on the act to taxpayer of filing a false and Civil and Criminal Actions: fraudulent tax return and failure to pay the tax. the 15. statue of limitation Actions instituted by the government to is primarily designed to protect the rights of the collect internal revenue taxes in regular taxpayer’s against unreasonable investigation of . Person failed to issue receipts and facie showing of willful attempt to evade. TAX ATION San Beda College of LAW – ALABANG courts (RTC or MTCs. Statute Of Limitation Purpose: C. Civil Action For purposes of Taxation. Thus. does not arise from a criminal act. the penalty but also order payment of taxes. penalty or Prescriptive Periods / forfeiture. the 13. Inquiring into bank deposit accounts of Reason: Tax is an obligation. for recovery of taxes. Conducted by Legal Officer of BIR 3. Registration of Taxpayers. Prescribing presumptive gross sales or receipt: An assessment of a tax deficiency is not necessary to a criminal prosecution for tax evasion. 14. criminal liability since the duty to pay the tax is imposed by statute. 16. depending on the Books of accounts and other accounting amount involved) records of taxpayer must be preserved. Inventory – Taking of stock-in-trade and judgment of which shall not only impose making surveillance. Use of National Tax Register d.
May 20. (Section 203 of the Tax Code) Sept. Republic vs. 1964) b. taxpayer.within ten (10) question of fraud only for the first time years after the date of discovery of the in his memorandum which was filed omission. Recurrence of the foregoing tax evasion. The fraud contemplated by law is actual and not constructive. (Basilan Estates. However. June 29. A return filed before the last day amount to intentional wrongdoing with prescribed by law for the filing thereof the sole object of avoiding the tax. 4 SCRA 872) collection thereof. When the Commissioner raised the 5. Intentional and substantial demand/notice be received within the understatement of tax liability of the prescriptive period. assessment. TAX ATION San Beda College of LAW – ALABANG the taxing authority with respect to assessment and collection of Internal Revenue Taxes. because they do not contain information a. 222 paragraph (a)) 3. c. Commissioner 21. Exceptions: (Sec. Commissioner. A transcript sheets are not returns. Where no return was filed . It must 1. 6. (Aznar case. 30. In case a return is substantially amended. Fraud may be established by the mailed or sent by the Commissioner to the following : (Badges of Fraud) correct address of the taxpayer. in case it is alleged and proved to exist by clear & filed beyond the period prescribed thereof. vs. 1966) Note: b. 1974) 2. the fact of fraud shall commence from the filing of the shall be judicially taken cognizance of amended return (CIR vs. 29. 1987) e. A shall be considered as filed on such last mere mistake is not a fraudulent day. In computing the prescriptive period for assessment. Dec. (Sinforo Alca vs. Kei & Co. When the Commissioner fails impute necessary and required to permit the fraud in the assessment computation and assessment of taxes notice/demand for payment. When the Commissioner failed to allege in his answer to the taxpayer’s petition for review when the case is appealed to the CTA. Phoenix. the law does not require that the d. Aug. Fraud is never presumed and the prescribed by law for the filing of the return or circumstances consisting it must be from the day the return was filed. A fraud assessment which has become the government right to assess the tax final and executory. convincing evidence (Republic vs. the CTA after he had rested his case. cannot be deemed an circumstances. intent. 1999) Instances/Circumstances negating fraud: 5. in the civil or criminal action for the 1965. Keir. 23. . the latter is deemed made when notice to this effect is released. 222 ic) c. Intentional and substantial overstatement of deductions of 4. Inc. SCRA 17. Where a return was filed but the same was false or fraudulent – within ten (10) years Prescription of Government’s Right to from the discovery of falsity or fraud. An affidavit executed by a revenue office exemption indicating the tax liabilities of a taxpayer and attached to a criminal complaint for f. Assess Taxes: Nature of Fraud: General Rule: Internal Revenue Taxes shall be assessed within three (3) years after the last day a. vs. ( CIR vs. Pascoi Realty Corp. Collector. CA April 30. (Sec.
if it appears that there was an assessment. General Rule: Note: Limitations: 1. Ayala Securities Corp. which has been bases of which is not required by law to be assessed within the period agreed . 7. 1980) taxpayer’s net income. Nov. does not prove fraud. The agreement to extend the same 2. D. at anytime within 2. omission. d. “not (Carmen vs. Where no return is required by law. Where there is a written waiver or return was due or was filed. following the date of assessment. the tax 10 years after the discovery of the is imprescriptible. sure” as to the real amount of the 21. unless there is a sufficient evidence shaving fraudulent intent. 4. Assessment of unpaid taxes. at anytime within ten e.. Assessment of compensating and e. the ordinary 5-year period (now 3 years) Imprescriptible Assessments: would apply (Rep. Where the commissioner and the taxpayer. or fraud. E. vs. The agreement extending the period of assessed within the period of limitation prescription should be in writing and may be collected by distraint or levy or duly signed by the taxpayer and the by proceeding in court within 5 years commissioner. In such case. where the internal revenue tax. Where a fraudulent/false return with d. Ret. Where an assessment was made – Any internal revenue tax which has been c. collection of such tax may be filed without assessment. whichever renunciation of the original 3-year is later.. Exceptions: Note: Limitations: 8. the tax 9. Where no assessment was made and a should be mode before the expiration return was filed and the same is not of the period previously agreed upon. f. Waiver of statute of limitations – any 3. Where the BIR itself appeared. the tax may be filed without assessment. limitation signed by the taxpayer. A waiver is inefficient I it is executed years after the discovery of the falsity beyond the original three year. d. TAX ATION San Beda College of LAW – ALABANG reported in a return such as excise taxes. When the taxpayer omits to file a sought to be assessed becomes return – a court proceeding for the imprescriptible. fraudulent or false. before the expiration of the Prescription of Government’s three (3) year period of limitation have Right to Collect Taxes agreed in writing to the extension of said period. Where the law does not provide for any particular period of assessment. 1962) 1. The waiver to be valid must be intent to evade taxes was filed a executed by the parties before the proceeding in court for the collection of lapse of the prescriptive period. 10. The commissioner can not valid agree Note: The 10-year prescriptive period to reduce the prescriptive period to for collector thru action does not apply less than that granted by law. A mere understatement of income documentary stamp tax. March 31.the tax should be collected within 3 years after the 8.
the government avail of distraint and levy procedure. 13. 1963) c.g. Where before the expiration of the time complaint with the proper court. When the offender is absent from the the last revised assessment. When it should commence? . In civil case – If not raised in the lower court. 14. Where assessment of the have consented in writing to its commissioner is protected & appealed assessment after such time. purposes of the prescriptive period. In criminal case – It can be raised even if 4. if can not F. Day of the commission of the violation. When it is interrupted: March 30. c. TAX ATION San Beda College of LAW – ALABANG upon. Rule: All violations of any provision of the tax code shall prescribe after five (5) years. Where a tax obligation is secured by a surety bond – the government may When it should run again: proceed thru a court action to forfeit a bond and enforce such contractual When the proceeding is dismissed for obligation within a period of ten years. Interruption of the Prescriptive Period 5. may be collected be distinct or The five (5) year prescriptive period shall levy of by a proceeding in court within begin to run from the: the period agreed upon in writing before the expiration of 5-year period. The running of statute of limitations on making an assessment and the beginning of distraint/levy or a proceeding in court Rules of Prescription in Criminal Cases for collection shall be suspended for the period. vs. During which the Commissioner is prohibited from making the assessment or Note: beginning distraint/levy or a proceeding in court and for 60 days thereafter. if know. from the time of discovery reinvestigation requested by the and the institution of judicial proceeding taxpayer – the prescriptive period for for its investigation and punishment. Collection by judicial action – The collection begins by filing the 4. Where the action is brought to enforce When does the defense of a compromise entered into between prescription may be raised: the commission and the taxpayer – the prescriptive period is ten years. taxpayer’s petition for review. the tax may to the CTA – the collection begin when be assessed prior to the expiration of the the government file its answer to period agreed upon. Lopez. c. collection should be counted from the last assessment. Philippines. When tax is deemed collected for be raised for the first time on appeal. Where the assessment is revised the guilty person because of an amended return – the period for collection is counted from d. Where the government makes another assessment on the basis of d. Collection by summary remedies – It is the case has been decided by the lower effected by summary methods when court but pending decision on appeal. 5. reason not Constituting jeopardy. it is bailed permanently. d. (Rep. e. If not known. both the commissioner and the taxpayer 6. When a proceeding is instituted against 12. 11. (RTC) prescribed for the assessment of the tax.
fees. . The law on prescription remedial measure tax. and charges. Powers and Duties of the suspended. When CTA suspends the collection of tax liability of the taxpayer pursuant to 7. recumbent by setting. 5. commissioner. 4. and as defense it must be c. The defense of prescription must be raised Section 11 of RA 1125 upon proof that by the taxpayer on time. . Chief Officials of the Bureau of Internal Revenue.The power to interpret the for assessment of the tax before the provisions of this Code and other tax laws criminal action may be instituted. cannot invoke the principle of Equitable Substantial issues must be raised. Reason: No requirement Cases. . his authorized representative and fines connected therewith. __________________________________________________ _____SOME IMPORTANT PROVISIONS ON THE TAX Note: If the taxpayer informs the REFORM ACT OF 1997 Commissioner of any change in address the statute will not be SEC. The property could be located. 3. should be interpreted liberally in order to protect the taxpayer. Filing a petition for review in the CTA from the decision of the Commissioner. Power of the Commissioner to tax assessment does not suspend the Interpret Tax Laws and to Decide Tax criminal action. government and /or the taxpayer. including the execution of judgments in all cases 6. hereinafter referred to as the the Philippines. When the warrant of distraint or the supervision and control of the levy is duly served upon any of the Department of Finance and its powers and following person: duties shall comprehend the assessment and collection of all national internal 4. penalties. or the part of the Commissioner does not interrupt the running of 10. Bureau of Internal Revenue. SEC.The Bureau of Internal Revenue shall be under e. When the taxpayer is out of the conferred to it by this Code or other laws. The question of prescription is not jurisdictional. Bureau shall give effect to and administer the supervisory and police powers f. and the enforcement of all forfeitures. located in the address given by him in the return. the government must not be a mere pro-former. When the taxpayer requests for raised reasonably otherwise it is deemed reinvestigation which is granted by waived. shall be under the exclusive and original . Philippines. When the taxpayer cannot be taxpayer is entitled. 9. TAX ATION San Beda College of LAW – ALABANG a. The request has already prescribed. In the event that the collection of the tax the prescriptive period. Note: A petition for reconsideration of a SEC. Commissioner and four (4) assistant chiefs to be known as Deputy Commissioners. taxpayer revenue taxes. In criminal cases for violation of tax Internal Revenue shall have a chief to be code – the period shall not run known as Commissioner of Internal when the offender is absent from Revenue.off the prescribed tax against a tax refused to which the d. 2. otherwise it is its collection may jeopardizes the deemed waived.The Bureau of g. The prescriptive provided in the tax code Note: A mere request for over ride the statute of non-claims in the reinvestigation without any action settlement of the deceased’s estate. b. Nota Bene: The commissioner is prevented from filing an ordinary action to collect the 6. Member of his household with decided in its favor by the Court of Tax sufficient discretion and no Appeals and the ordinary courts. 8.
or in determining (E) To cause revenue officers and the liability of any person for any internal employees to make a canvass from revenue tax. to appear before the matters arising under this Code or other Commissioner or his duly laws or portions thereof administered by authorized representative at a time the Bureau of Internal Revenue is vested and place specified in the in the Commissioner. or from any office or nothing in this Section shall be officer of the national and local construed as granting the governments. That failure to (C) To summon the person liable for file a return shall not prevent the tax or required to file a return. and financial (A) Examination of Returns and statements of corporations. paper. authorized representative may associations. records. or other data which may be revenue tax. and to Summon. 5. any information such as. the correct amount of tax: Provided. papers.After a fund companies. or in evaluating tax compliance. under oath. or in making a return when none has been made. -controlled corporations. management or possession of any object with respect to which a tax (B) To obtain on a regular basis is imposed. from any person other than the person whose internal revenue tax The provisions of the foregoing liability is subject to audit or paragraphs notwithstanding. and their members. . or any imposed in relation thereto. may be liable to pay any internal record. subject person. . as Examine.In ascertaining the correctness inquiry. TAX ATION San Beda College of LAW – ALABANG jurisdiction of the Commissioner. or region and inquire after and the Commissioner is authorized: concerning all persons therein who (A) To examine any book. subject to the summons and to produce such exclusive appellate jurisdiction of the books. Make assessments and Prescribe receipts or sales and gross additional Requirements for Tax incomes of taxpayers. or other other person. refunds of internal revenue entries relating to the business of taxes. Power of the Commissioner to to. possession. and all persons relevant or material to such owning or having the care. inquiry. or any person having to review by the Secretary of Finance. costs and volume of production. and Take Testimony of may be relevant or material to such Persons. and to give testimony. or care of the books of accounts and other The power to decide disputed accounting records containing assessments. or other Court of Tax Appeals. addresses. 6. custody. insurance return has been filed as required companies. person concerned. inquire into bank deposits other including the Bangko Sentral ng than as provided for in Section 6(F) Pilipinas and government-owned or of this Code. or Commissioner from authorizing the any officer or employee of such examination of any taxpayer. but not limited SEC. regional operating under the provisions of this Code. and of any return. and the Administration and Enforcement. Power of the Commissioner to (D) To take such testimony of the Obtain Information. however. penalties the person liable for tax. fees or other charges. joint accounts. or in collecting any such time to time of any revenue district liability. government Commissioner the authority to agencies and instrumentalities. mutual Determination of Tax Due. SEC. investigation. headquarters of multinational the Commissioner or his duly companies. data. - names. . joint ventures of authorize the examination of any consortia and registered taxpayer and the assessment of partnerships.
or Period. In case a person fails to file a required return or other document at (D) Authority to Terminate Taxable the time prescribed by law. incomplete or erroneous. tax liabilities of such person. . statement of declaration and such assessment shall be filed in any office authorized to deemed prima facie correct. shall declare the tax period of such at any time during the taxable year. records do not correctly reflect the statement or declaration has in the declarations made or to be made in meantime been actually served a return required to be filed under upon the taxpayer. the provisions of this Code. That no notice for audit or that the books of accounts or other investigation of such return. believe that such person is not and said taxes shall be due and declaring his correct income. income other Documents. unless paid within the as the basis for assessing the taxes time fixed in the demand made by for the other months or quarters of the Commissioner. a taxpayer is retiring from business the Commissioner shall make or subject to tax.The Commissioner may. together with a determining his internal revenue tax request for the immediate payment liabilities. surveillance and to Prescribe unless such proceedings are begun Presumptive Gross Sales and immediately. the same or different taxable years . receipts. the same totally or partly ineffective taking. the same may be modified. performing any act tending to which shall be prima facie correct obstruct the proceedings for the and sufficient for all legal purposes. receive the same shall not be When it is found that a person has withdrawn: Provided. receipts. collection of the tax for the past or current quarter or year or to render (C) Authority to Conduct Inventory. under observation or preceding year or quarter. Reports and account the sales. changed. or is through testimony or otherwise. the Commissioner Receipts. or when there is reason to believe further. the and such amount so prescribed shall Commissioner shall assess the be prima facie correct for purposes proper tax on the best evidence of determining the internal revenue obtainable. after taking into Returns. That within failed to issue receipts and invoices three (3) years from the date of such in violation of the requirements of filing. sales payable immediately and shall be or receipts for internal revenue tax subject to all the penalties hereafter purposes. TAX ATION San Beda College of LAW – ALABANG Any return. Sections 113 and 237 of this Code. Statements. or amended: Provided. or such surveillance if there is reason to portion thereof as may be unpaid. the (B) Failure to Submit Required Commissioner. taxpayer terminated at any time and order inventory-taking of goods of shall send the taxpayer a notice of any taxpayer as a basis for such decision. natural or terminated and the tax for the juridical. .When it shall come to the willfully or otherwise files a false or knowledge of the Commissioner that fraudulent return or other document.When a report or other taxable base of other required by law as a basis for the persons engaged in similar assessment of any national internal businesses under similar situations revenue tax shall not be or circumstances or after forthcoming within the time fixed considering other relevant by laws or rules and regulations or information may prescribe a when there is reason to believe minimum amount of such gross that any such report is false. or is intending to amend the return from his own leave the Philippines or to remove knowledge and from such his property therefrom or to hide or information as he can obtain conceal his property. or may place the business of the tax for the period so declared operations of any person. The findings may be used prescribed. . sales and taxable base.
(2) any taxpayer who has filed an application for (H) Authority of the Commissioner to compromise of his tax Prescribe Additional Procedural or liability under Sec. Register Tax Agents. The subject to such limitations and restrictions Commissioner shall accredit and as may be imposed under rules and register. the value of the designate from among the senior property shall be. 1405 or under other general or The Commissioner may delegate the special laws. That the following . protests. and appellant. representatives who are denied accreditation by the Commissioner (F) Authority of the Commissioner and/or the national and regional to inquire into Bank Deposit accreditation boards may appeal Accounts. subordinate officials with the rank (G) Authority to Accredit and equivalent to a division chief or higher. the Bureau for taxpayers. before. upon and moral fitness. determine the fair Commissioner shall create national market value of real properties and regional accreditation boards. TAX ATION San Beda College of LAW – ALABANG (E) Authority of the Commissioner to and their representatives who Prescribe Real Property Values. application shall not be considered unless and SEC. For the members of which shall serve purposes of computing any internal for three (3) years. . however. . 1405 and other general or appeal within sixty (60) days from special laws. individuals and recommendation of the Commissioner: general professional partnerships Provided. Commissioner is hereby authorized statements. . upon consultation with competent Within one hundred twenty (120) appraisers both from the private and days from January 1. reports. Authority of the until he waives in writing his privilege under Commissioner to Delegate Power.Notwithstanding any such denial to the Secretary of contrary provision of Republic Act Finance. located in each zone or area. integrity Secretary of finance. or recommendation of the (2) the fair market value as Commissioner. and to divide the Philippines into other papers with or who appear different zones or areas and shall. the public sectors. 1998.The (2) of this Code by reason of Commissioner may prescribe the financial incapacity to pay manner of compliance with any his tax liability. 204 (A) Documentary Requirements. documentary or procedural In case a taxpayer files an application to requirement in connection with the compromise the payment of his tax liabilities on submission or preparation of his claim that his financial position demonstrates financial statements accompanying a clear inability to pay the tax assessed. who shall rule on the No. based on their regulations to be promulgated by the professional competence. the Commissioner is receipt of such appeal. shown in the schedule of Individuals and general professional values of the Provincial and partnerships and their City Assessors. and such waiver shall constitute the powers vested in him under the pertinent authority of the Commissioner to inquire into the provisions of this Code to any or such bank deposits of the taxpayer.The prepare and file tax returns. one (1) higher of: chairman and two (2) members for each board. and shall revenue tax. his the tax returns. subject to such rules (1) the fair market value as and regulations as the Secretary of determined by the Finance shall promulgate upon the Commissioner. . - Republic Act No. 7. whichever is the officials of the Bureau. Failure of the hereby authorized to inquire into Secretary of Finance to rule on the the bank deposits of: Appeal within the prescribed period shall be deemed as approval of the (1) a decedent to determine application for accreditation of the his gross estate.
a change unused stamps that have been rendered return filed before the last day prescribed by law unfit for use and refund their value upon proof of for the filing thereof shall be considered as filed destruction. in his discretion. Provided. TAX ATION San Beda College of LAW – ALABANG powers of the Commissioner shall not be Compromise. Officer having jurisdiction over the taxpayer. No credit or refund of taxes or on such last day. 204. . be compromised by a regional Where the basic tax involved exceeds One million evaluation board which shall be pesos (P1.000) or where the settlement composed of the Regional Director offered is less than the prescribed minimum as Chairman. Authority of the Commissioner to credit or refund within two (2) years after the payment of the tax or penalty: Provided. Assessment and Collection composed of the Commissioner and the four (4) Divisions and the Revenue District Deputy Commissioners. return. abate. a minor criminal violations. . and no proceeding in court without assessment for the collection of such taxes shall (C) Credit or refund taxes erroneously or illegally be begun after the expiration of such period: received or penalties imposed without authority. and. and (B) Abate or Cancel a Tax Liability. discovered by forty percent (40%) of the basic regional and district officials. (b) The power to issue rulings of (1) A reasonable doubt as to the validity first impression or to reverse. when: (d) The power to assign or reassign internal revenue officers to (1) The tax or any portion thereof appears establishments where articles to be unjustly or excessively assessed. Abate and Refund or Credit delegated: Taxes. when: Finance. may assessed tax. a minimum recommendation of the compromise rate equivalent to Commissioner. as members. 203.The Commissioner may - (a) The power to recommend the promulgation of rules and (A) Compromise the Payment of any regulations by the Secretary of Internal Revenue Tax. 204 (A) and (B) of this Code. . redeem or return was filed. or (b) those involving fraud. any tax liability: Provided. the Assistant rates. the compromise shall be subject to the Regional Director. the three they are returned in good condition by the (3)-year period shall be counted from the day the purchaser. penalties shall be allowed unless the taxpayer files in writing with the Commissioner a claim for SEC. internal revenue taxes All criminal violations may be shall be assessed within three (3) years after the compromised except: (a) those already last day prescribed by law for the filing of the filed in court. Period of Limitation Upon amount due. That The compromise settlement of any tax assessments issued by the regional liability shall be subject to the following offices involving basic deficiency minimum amounts: taxes of Five hundred thousand pesos (P500. under Sec. That in a case where a return is filed refund the value of internal revenue stamps when beyond the period prescribed by law. Assessment and Collection. however.000) or less.000. of the claim against the taxpayer exists. or subject to excise tax are produced (2) The administration and collection or kept. as may minimum compromise rate be determined by rules and equivalent to ten percent (10%) of regulations to be promulgated by the basic assessed tax. For purposes of this Section. and the Secretary of finance.Except as provided in Section 222. costs involved do not justify the collection of the SEC. demonstrates a clear inability to pay the (c) The power to compromise or assessed tax. or revoke or modify any existing (2) The financial position of the taxpayer ruling of the Bureau. the heads of the approval of the Evaluation Board which shall be Legal. and For cases of financial incapacity. upon For other cases.
(6) months. every six improvements thereon. verification and cancellation: Provided. That in no case shall a tax refund be given The Bureau of Internal Revenue shall resulting from availment of incentives granted advance the amounts needed to defray pursuant to special laws for which no actual costs of collection by means of civil or payment was made. amount may place under constructive distraint the involved. Any request for conversion into refund of unutilized tax credits may be allowed. and any increment thereto resulting same intact and unaltered and not to dispose of from delinquency shall be: the same . where the property distrained is located. proceedings for collecting the tax due or which CHAPTER II may be due from him.To safeguard the addresses of taxpayers whose cases have been interest of the Government. Constructive Distraint of the facts and information. That a return filed showing an Either of these remedies or both overpayment shall be considered as a written simultaneously may be pursued in the claim for credit or refund. a report on the exercise of his powers under this Section. in the presence of two (2) witnessed. (a) By distraint of goods. bank be placed under constructive distraint refuses or accounts and interest in and rights to fails to sign the receipt herein referred to. 205. in his opinion. credits. without the express authority of the Commissioner. as well as of real property and Senate and House of Representatives. chattels. for which the taxpayer is directly liable. stating therein the following SEC. or is intending to leave Oversight Committee in Congress that shall be the Philippines or to remove his property constituted to determine that said powers are therefrom or to hide or conceal his property or to reasonably exercised and that the government is perform any act tending to obstruct the not unduly deprived of revenues. That the remedies of distraint provisions of this Code may be applied against and levy shall not be availed of where the any internal revenue tax. criminal action. CIVIL REMEDIES FOR COLLECTION OF TAXES The constructive distraint of personal property shall be affected by requiring the taxpayer or any SEC. the Commissioner the subject of abatement or compromise. and by levy upon real revenue officer effecting the constructive property and interest in rights to real distraint shall proceed to prepare a list of such property. fees or distrained and obligate himself to preserve the charges. further. the personal property. . including stocks and possession and control of the property sought to other securities. That the original copy of the Tax Credit order payment of the taxes subject of the Certificate showing a creditable balance is criminal case as finally decided by the surrendered to the appropriate revenue officer for Commissioner. That taxpayer who. among others: names and Property of a Taxpayer. after which the said property shall be deemed to have been placed under constructive distraint. or effects. and property and. One hundred pesos (P100). amount compromised or abated. A Tax Credit Certificate validly issued under the however. . including the preservation or transportation of personal property The Commissioner shall submit to the Chairmen distrained and the advertisement and sale of the Committee on Ways and Means of both the thereof. and other personal property of In case the taxpayer or the person having the whatever character. excluding withholding amount of tax involve is not more than taxes. 206. Remedies for the Collection of person having possession or control of such Delinquent Taxes. TAX ATION San Beda College of LAW – ALABANG however.in any manner whatever. and property of a delinquent taxpayer or any reasons for the exercise of power: Provided. discretion of the authorities charged with the collection of such taxes: Provided. leave a copy thereof in the premises (b) By civil or criminal action. subject to The judgment in the criminal case shall the provisions of Section 230 of this Code: not only impose the penalty but shall also Provided. debts.The civil remedies for the property to sign a receipt covering the property collection of internal revenue taxes. . is retiring from any the said report shall be presented to the business subject to tax.
in sufficient quantity to satisfy the Within ten (10) days after receipt of the warrant. .000) or less. That the Commissioner or his duly Finance. 208. chattels or effects. real property may be property were taken. further. interests in and rights to personal property of such persons . 207. . or if he be absent from the authority to the person owning the debts or . duly authorized representative shall prepare a duly authenticated certificate showing the name Stocks and other securities shall be distrained by of the taxpayer and the amounts of the tax and serving a copy of the warrant of distraint upon penalty due from him. or at the dwelling or place levied upon.000). or the personal property of the taxpayer is not sufficient Revenue District Officer. debts. and thirty (30) days after execution of the distraint. together with any increment a report on any levy shall be submitted by the thereto incident to delinquency. Levy shall be affected by writing upon said certificate a description of the property upon Debts and credits shall be distrained by leaving which levy is made. account of the goods. subject to rules Commissioner. however.Upon the in question. manager. upon recommendation of the authorized representative shall. days from receipt of the warrant. city where the property is located and upon the The warrant of distraint shall be sufficient delinquent taxpayer. within ten (10) Commissioner as often as necessary: Provided.The officer serving the warrant required by the Commissioner as often as of distraint shall make or cause to be made an necessary. chattels. upon recommendation of the provisions hereof. if the amount involved is to satisfy his tax delinquency. or upon the Register of Deeds for the province or with his agent. . and the excess of One million pesos (P1. or effects or other personal prescribed in this Section. .000. At the same time. (B) Levy on Real Property. chattels. shall have the authority to lift and regulations promulgated by the Secretary of warrants of levy issued in accordance with the Finance. within and distraint any goods. or charge. a copy of the warrant of distraint. That a consolidated SEC. be submitted by further. tax. the Commissioner or his duly authorized issued before or simultaneously with the warrant representative. credits. written with the person owing the debts or having in his notice of the levy shall be mailed to or served possession or under his control such credits. effects or other personal property distrained. company or association. operate with the force of a legal execution treasurer or other responsible officer of the throughout the Philippines. have the power to lift such order of distraint: Provided. Procedure for Distraint and report by the Revenue Regional Director may be Garnishment. That the Commissioner or his duly the distraining officer to the Revenue District authorized representative. subject to rules and Officer. TAX ATION San Beda College of LAW – ALABANG Philippines. before simultaneously or after the of business of such person and with someone of distraint of personal property belonging to the suitable age and discretion. to which list shall be delinquent. Said certificate shall the taxpayer and upon the president. the personal property.After the signed by himself. if the amount involved is in of distraint on personal property. subsequent sale. That a consolidated report by the Revenue Regional Director may be required by the A report on the distraint shall. and to the Revenue Regional Director: regulations promulgated by the Secretary of Provided. or if there be none. failure of the person owing any delinquent tax or delinquent revenue to pay the same at the time In case the warrant of levy on real property is not required. shall seize or his duly authorized representative shall. shall be left either with the expiration of the time required to pay the owner or person from whose possession such delinquent tax or delinquent revenue as goods. to the occupant of the property (A) Distraint of Personal Property. corporation. and the levying officer to the Commissioner or his duly expenses of the distraint and the cost of the authorized representative: Provided. bank accounts. which issued the said stocks or securities. including stocks and other proceed with the levy on the taxpayer's real securities. Commissioner. To this end. any internal revenue added a statement of the sum demanded and officer designated by the Commissioner or his note of the time and place of sale. and property. Summary Remedies. the Commissioner One million pesos (P1. business in respect to which the liability arose.000. to his agent or the manager of the SEC. a copy of which.
the Commissioner or his deputy may The time of sale shall not be less than twenty (20) purchase the same in behalf of the national days after notice.by transfer the stocks or other securities sold in the publication once a week for three (3) weeks in a name of the buyer. district in which the real estate lies and . if required to do so. company or period of a least thirty (30) days. and no charge shall be imposed for the Commissioner the amount of such debts or services of the local internal revenue officer or his credits. manager. including expenses. If he does not do so. and a short pay the entire claim. Property so purchased may be resold by the Commissioner or his deputy. Sale of Property Distrained and the sale.The Revenue District a report of his proceedings in writing to the Officer or his duly authorized representative. or other personal property. 213. twenty (20) days after levy. . the goods or effects distrained shall be over to the Commissioner so much of the bank restored to the owner. according to rules and regulations prescribed by the Secretary of Finance. 211. the officer making the same shall make Disposition of Proceeds. the actual market value of the articles offered for time and place of sale and the articles distrained. Commissioner and shall himself preserve a copy other than the officer referred to in Section 208 of of such report as an official record. 209. the advertise the property or a usable portion thereof officer making the sale shall execute a bill of sale as may be necessary to satisfy the claim and cost which he shall deliver to the buyer. penalties such notice shall be at the Office of the Mayor of and costs due thereon. accounts as may be sufficient to satisfy the claim of the Government. The advertisement shall contain a statement of the amount of taxes and penalties so due and the time and place of sale. Report of Sale to Bureau of Internal Revenue. forthwith Upon Distraint. The before the day fixed for the sale. deputy. newspaper of general circulation in the the corresponding certificates of stock or other municipality or city where the property is located. penalties and interest. public auction. this Code shall. and a copy of sale. Bank accounts shall be garnished by serving a SEC. At any time returned to the owner of the property sold. securities. the corporation. and such advertisement shall cover a thereof furnished the corporation. the net proceeds therefrom shall be or effects. .Within two (2) days after SEC. . to the highest bidder for cash.When the amount bid for the cause a notification to be exhibited in not less property under distraint is not equal to the than two (2) public places in the municipality or amount of the tax or is very much less than the city where the distraint is made. Upon receipt of charges are paid to the officer conducting the the warrant of garnishment. subject to the rules At the time and place fixed in such notice. Finance. the taxpayer expenses chargeable upon each seizure and sale may discontinue all proceedings by paying the shall embrace only the actual expenses of seizure taxes. Upon receipt of the copy of the bill of entrance of the municipal building or city hall and sale. TAX ATION San Beda College of LAW – ALABANG having in his possession or under his control any and preservation of the property pending .the credits belonging to the taxpayer to pay to the sale. including remitted to the National Treasury and accounted stocks and other securities so distrained.If at any time upon the president. the bank shall tun sale. specifying. at for as internal revenue. the city or municipality in which the property is distrained. Release of Distrained Property warrant of garnishment upon the taxpayer and Upon Payment Prior to Sale. SEC. . upon SEC. One place for the posting of Government for the amount of taxes. 210.Within duly licensed commodity or stock exchanges. company or association in public and conspicuous place in the barrio or shall make the corresponding entry in its books. . the and regulations prescribed by the Secretary of said revenue officer shall sell the goods. the name of the taxpayer Any residue over and above what is required to against whom taxes are levied. It shall be association which issued the stocks or other effectuated by posting a notice at the main securities. 212. or with the approval of the Commissioner. Advertisement and Sale. sale. through SEC. chattels. the officer conducting the proceedings shall proceed to In the case of Stocks and other securities. . shall be description of the property to be sold. treasurer or other prior to the consummation of the sale all proper responsible officer of the bank. and issue. Purchase by Government at Sale recommendation of the Commissioner.
217. shall giving of not less than twenty (20) days notice. . . shall be entered upon the records of the Revenue the Internal Revenue Officer conducting the sale Collection Officer. Further Distraint or Levy. . Redemption of Property Sold. the excess from a competent court.The certificate from the said Revenue District Officer remedy by distraint of personal property and levy that he has thus redeemed the property. . city hall. Want of Bidder. in consultation with the question and within two (2) days thereafter. and such payment shall Commission on Audit. the Revenue District officer and shall declare the property forfeited to the the Revenue Regional Director. entitle the person paying to the delivery of the certificate issued to the purchaser and a SEC. 215. Taxes. both in cases of personal and real property including improvements found SEC. but if the property be not thus redeemed. In his monthly collection reports. have the right of paying to the Revenue District sell and dispose of the same of public auction or Officer the amount of the public taxes. showing the proceedings of the sale. and the on realty may be repeated if necessary until the Revenue District Officer shall forthwith pay over full amount due. transfer the title of the property forfeited to the however. fee or charge imposed by this Code. Forfeiture to Government for determine and as the notice of sale shall specify. be deprived of the restrain the collection of any national internal possession of the said property and shall be revenue tax. penalties and interest: Provided. In either to the date of sale. together with interest on said case. upon the delinquent taxpayer. entitled to the rents and other income thereof . advance an amount sufficient to Commissioner or the latter's Revenue Collection defray the costs of collection by means of the Officer the full amount of the taxes and penalties. and said property thereafter shall be free form the lien of SEC. penalties and costs. . or any one for him. out of his redeem said property by paying to the collection. Restrain Collection of Tax.the preservation or transportation in sale. case of personal property. 218. however. summary remedies provided for in this Code. The Revenue Government in satisfaction of the claim in Collection Officer. It shall be the duty of the Register of describing the property sold stating the name of Deeds concerned. and said Commissioner may. and the advertisement the forfeiture shall become absolute. is to the purchaser the amount by which such collected. property has thus been redeemed. including all expenses. together with interest thereon and the costs of including . 214. the therefore. Injunction not Available to such taxes and penalties. penalties. the taxpayer. and interest thereon from the date of delinquency dispose of the same at private sale. as the officer conducting the proceedings shall SEC. That in case the proceeds of the sale Government without the necessity of an order exceeds the claim and cost of sale. and an accounting of (15%) per annum from the date of purchase to the same shall rendered to the Chairman of the the date of redemption. or in compromise or adjustment of any claim Within one (1) year from the date of sale. the Philippines in payment or satisfaction of taxes.The Commissioner shall have charge of such advances shall be reflected and supported any real estate obtained by the Government of by receipts. 216. or any one for him may the Revenue District Officer may. shall Revenue district Officer. upon approval by forfeiture. to of all taxes. and subsequent sale. penalties or costs arising under this Code SEC. TAX ATION San Beda College of LAW – ALABANG the sale shall proceed and shall be held either at until the expiration of the time allowed for its the main entrance of the municipal building or redemption. with prior approval of the Secretary of Finance.No court shall have the authority to grant an injunction to The owner shall not.In case there is no bidder for real property exposed for sale as herein above Within five (5) days after the sale. a return by the provided or if the highest bid is for an amount distraining or levying officer of the proceedings insufficient to pay the taxes. or on the premises to be sold. Resale of Real Estate Taken for on the latter. upon registration with his the purchaser and setting out the exact amount office of any such declaration of forfeiture. of his office. Within one (1) year from the date of such The Revenue Collection Officer. shall be turned over to the owner of the property. shall then make out and make a return of his proceedings and the deliver to the purchaser a certificate from his forfeiture which shall be spread upon the records records. the proceeds of the sale shall be deposited purchase price at the rate of fifteen percent with the National Treasury.
shall be SEC. with interests. the fact of fraud shall be is duly served upon the taxpayer. That nothing in the the recovery of taxes or the enforcement of any immediately preceding and paragraph (a) fine. subject to the the making of assessment and the beginning of approval of the Commissioner. the amount shall be a lien in favor agreed upon may be extended by of the Government of the Philippines from the subsequent written agreement made time when the assessment was made by the before the expiration of the period Commissioner until paid. his authorized judicially taken cognizance of in the civil or representative. . 223. Commissioner. and when the taxpayer is out of the prescribed in Section 203 for the Philippines. Form and Mode of Proceeding in hereinabove. The period so after demand. Nature and Extent of Tax Lien. when the taxpayer requests for a return with intent to evade tax or of failure reinvestigation which is granted by the to file a return. into any tax return filed in accordance with the provisions of any tax amnesty law or SEC. and no property could (b) If before the expiration of the time be located. previously agreed upon. distraint or levy a proceeding in court for collection. in respect of any deficiency. 222. . joint. the Commissioner of any change in address. the fraud or omission: Provided. if the taxpayer informs years after the discovery of the falsity.If assessment of the tax. Internal Revenue but no civil or criminal action for (e) Provided. the tax may be assessed. . the tax may be assessed within revenue tax. . 220. neglects or refuses to pay the same the period agreed upon. with sufficient discretion. . corporation. and costs that may accrue in addition thereto (c) Any internal revenue tax which has upon all property and rights to property belonging been assessed within the period of to the taxpayer: Provided. may be collected by distraint Actions Arising under this Code. assessment or beginning distraint or levy or a proceeding in court and for sixty (60) days (a) In the case of a false or fraudulent thereafter. both the any person. 221. association or agreed in writing to its assessment after insurance company liable to pay an internal such time. as the Limitations provided in Sections 203 and 222 on particular situation may require. when the warrant of distraint or levy and executory. penalties. this Code or other law enforced by the Bureau of The period so agreed upon may be Internal Revenue shall be brought in the name of extended by subsequent written the Government of the Philippines and shall be agreements made before the expiration of conducted by legal officers of the Bureau of the period previously agreed upon. Statutory Penal Provisions. been assessed within the period agreed upon as provided in paragraph (b) SEC. 219.The remedy for SEC. Suspension of Running of Statute enforcement of statutory penalties of all sorts of Limitations. however.Civil and or levy or by a proceeding in court within criminal actions and proceedings instituted in the period agreed upon in writing before behalf of the Government under the authority of the expiration of the five (5) -year period. That this lien shall not limitation as prescribed in paragraph (a) be valid against any mortgagee purchaser or hereof may be collected by distraint or judgment creditor until notice of such lien shall be levy or by a proceeding in court within five filed by the Commissioner in the office of the (5) years following the assessment of the Register of Deeds of the province or city where tax. the property of the taxpayer is situated or (d) Any internal revenue tax. penalty or forfeiture under this Code shall be hereof shall be construed to authorize the filed in court without the approval of the examination and investigation or inquiry Commissioner. or a member of his household criminal action for the collection thereof. when the taxpayer cannot be or a proceeding in court for the collection located in the address given by him in the return of such tax may be filed without filed upon which a tax is being assessed or assessment. partnership.The running of the Statute of shall be by criminal or civil action. Remedy for Enforcement of decree. that. TAX ATION San Beda College of LAW – ALABANG SEC. That in a running of the Statute of Limitations will not be fraud assessment which has become final suspended. Exceptions as to Period of suspended for the period during which the Limitation of Assessment and Collection of Commissioner is prohibited from making the Taxes. which has located. Commissioner and the taxpayer have account (cuentas en participacion). at any time within ten (10) collected: Provided. .
or same. costs. any . a penalty the Commissioner or his authorized deputies as equivalent to twenty-five percent (25%) of the taxes themselves are required to be paid. which have political subdivisions or instrumentalities. enforcement of the law. . been manufactured or removed in violation of this or a government-owned or controlled Code. shall be accounted (1) Failure to file any return and for and dealt with the same way. fees and charges imposed in by order of the Commissioner. specific forfeited property. civil or criminal. 227. The forfeiture of real property shall be enforced by a judgment of No such judgment. other manufactured products of tobacco. upon forfeiture. General Provisions. The Amount so added to the tax the same for consumption or use would be shall be collected at the same time. of the repaid or reimbursed to him. upon forfeiture. Forfeitures. (A) There shall be imposed. Satisfaction of Judgment this Code or rules and regulations Recovered Against any Internal Revenue on the date prescribed. or destruction. or if removable fixtures of any sort shall be enforced the same be paid by the person used shall be by the seizure and sale. SEC. and the amount due. - Distilled spirits. 225. or costs shall be condemnation and sale in a legal action or paid or reimbursed in behalf of a person who has proceeding. cigarettes. Civil Penalties. and all (a) The additions to the tax or deficiency apparatus used I or about the illicit production of tax prescribed in this Chapter shall apply such articles may. in addition to forfeitures. fines and penalties shall be paid to the tax required to be paid.When an action is brought against any (2) Unless otherwise authorized by Internal Revenue officer to recover damages by the Commissioner. damages. be destroyed to all taxes. 248. Remedy for Enforcement of action shall be satisfied by the Commissioner. and the Commissioner is notified of other than those with whom the such action in time to make defense against the return is required to be filed. 224. damages or costs recovered in such SEC. SEC. be sold or destroyed liable for the additions to the tax in the discretion of the Commissioner. in the injurious to public health or prejudicial to the same manner and as part of the tax. so far as STATUTORY OFFENSES AND PENALTIES practicable. - recovered and received for taxes. employee or member is under a duty to SEC. . when the sale of this Code. or Officer. 226. oppression. includes an officer or employee least twenty (20) days after seizure. of a corporation who as such officer. Forfeitures. as well as dies for the printing or making of corporation. filing a return reason of any act done in the performance of with an internal revenue officer official duty. as used in this Forfeited property shall not be destroyed until at Chapter. When Property to be Sold or Destroyed.all judgments and monies SEC. the employee thereof internal revenue stamps and labels which are in responsible for the withholding and imitation of or purport to be lawful stamps.The forfeiture of chattels and upon approval of the Secretary of Finance. in the same manner and under the same conditions as the public notice and the time CHAPTER I and manner of sale as are prescribed for sales of ADDITIONS TO TAX personal property distrained for the non-payment of taxes. . All other articles subject to excise tax. (c) the term "person". TAX ATION San Beda College of LAW – ALABANG judgment. Disposition of funds Recovered in perform the act in respect of which the Legal Proceedings or Obtained from violation occurs. (b) If the withholding agent is the Government or any of its agencies. pay the tax due thereon as required under the provisions of SEC. liquors. 247. or with willful require. through the Solicitor General.Sales of forfeited chattels and TITLE X removable fixtures shall be effected. or remittance of the tax shall be personally labels may. as the case may acted negligently or in bad faith. cigars. . in the following cases: except as specially provided. prescribed herein.
further. or not for its payment until the full payment thereof. however. or keep any failure to report sales. interest at the rate of twenty percent (20%) per annum. . or any part of such fifty percent (50%) of the tax or of the amount or installment on or before the date deficiency tax. there shall be assessed and underdeclaration of taxable sales. as mentioned herein. That a substantial or any part thereof. Interest. but fails to pay the tax or made. Provided. That information return. and a prescribed therefor. as the term is defined in this Code. or where the been made on the basis of such return Commissioner has authorized an extension of before the discovery of the falsity or fraud: time within which to pay a tax or a deficiency tax Provided.000). Failure of a Withholding Agent to such higher rate as may be prescribed by rules Collect and Remit Tax. which interest shall be liable upon conviction to a penalty equal to the assessed and collected from the date prescribed total amount of the tax not withheld.Any pay: . any payment has prescribed for its payment. as determined by the part thereof unpaid from the date of notice and Commissioner pursuant to the rules and demand until it is paid. (B) In case of willful neglect to file the (D) Interest on Extended Payment. 251. TAX ATION San Beda College of LAW – ALABANG (3) Failure to pay the deficiency tax (1) The amount of the tax due on any within the time prescribed for its return to be filed. or in elects to pay the tax on installment under the case a false or fraudulent return is willfully provisions of this Code.Any person required to and regulations. statement or list. willful neglect. shall. 252.There shall be assessed and (P25.Any deficiency in the abets in any manner to evade any such tax or the tax due. or no return is required. shall payment thereof. keep or supply the same. or account for and remit such tax. of tax due for which no return is interest at the rate prescribed in required to be filed. upon notice and shall render the taxpayer liable for demand by the Commissioner. . SEC. or supply any information required by this in an amount exceeding thirty percent Code or by the Commissioner on the date (30%) of that declared per return. regulations to be promulgated by the Secretary of Finance. in addition to other be subject to the interest prescribed in penalties provided for under this Chapter. there shall be assessed and regulations. Failure of a Withholding Agent to (C) Delinquency Interest. be imposed for all such failures during a calendar year shall not exceed Twenty-five thousand pesos (A) In General. be paid by the substantial underdeclaration of sales. be Subsection (A) hereof. receipts collected interest at the rate hereinabove or income. and remit any tax imposed payment until the amount is fully paid. which interest shall form part of payment. or any surcharge or the amount of tax shown on any interest thereon on the due date return required to be filed under appearing in the notice and demand of the the provisions of this Code or rules Commissioner. or SEC. from the date prescribed for withhold. . account for. on or before Subsection (A) hereof until the amount is the date prescribed for its fully paid. . 249. the penalty to be imposed shall be any installment hereof. person failing to file. That the aggregate amount to SEC. by this Code or who willfully fails to withhold such tax. or aids or (B) Deficiency Interest.In the case of each failure to file an fraudulent return: Provided. .In case of failure to refund Excess Withholding Tax. in case. .If any return within the period prescribed by this person required to pay the tax is qualified and Code or by rules and regulations.000) for each failure: deductions. or payment in the notice of (2) The amount of the tax due for which assessment. collected on any unpaid amount of tax. receipts or income record. Failure to File Certain Information prima facie evidence of a false or Returns. 250. accounted for and remitted. there shall. receipts or income or for overstatement of One thousand pesos (1. . the tax. shall constitute SEC. or a substantial overstatement prescribed on the tax or deficiency tax or any of deductions. or (4) Failure to pay the full or part of (3) A deficiency tax. or the full amount and collected on the unpaid amount. . unless it is shown that such claim of deductions in an amount failure is due to reasonable cause and not to exceeding (30%) of actual deductions.
Thus. As between CASES and DOCTRINES taxation and religion. would be paralyzed for lack of the motive power buildings and improvements used exclusively for to activate and operate it. every (Abra Valley College vs. the government convents. (Lutz vs Araneta 98 Phil 148) (Lladoc vs. the petitioner as purpose cannot be upheld. in addition 101 PHIL 386) to the penalties provided in this Title. is expected to respond in the form of The phrase “used exclusively for educational tangible and intangible benefits intended to purposes” is not limited to property actually improve the lives of the people and enhance their indispensable therefor but extends to facilities. Commissioner of Internal If objective and methods are alike constitutionally Revenue 14 SCRA 292) valid. VI of the attainment. the latter prevails. substituted by the Head of the Diocese. churches. which refers to lots used as home of the priest who preside over the church must include not only the lot actually occupied by the church but also the adjacent ground destined to meet the ordinary incidental uses of man. no reason is seen why the state may not levy taxes to raise funds for their prosecution and The exemption under Sec. Aquino 162 SCRA person who is able to must contribute his share in 106) the running of the government. This symbiotic which are incidental to and reasonably necessary relationship is the rationale of taxation and to the accomplishment of said purposes should dispel the erroneous notion that it is an arbitrary method of exaction by those in the seat of power. City of Manila to refund excess withholding tax shall. Hence. what’s being assessed was a limitation. churches. VI of the Constitution only covers property taxes assessed It is said that taxes are what we pay for on cemeteries. It is cemeteries. The government for its part. Therefore. despite the religious purposes. These taxes are property from a singling out of one particular class for taxes as contra-distinguished from excise taxes. the contention of plaintiff tax is not within the exempting provision of the that the Act was promulgated not for public constitution. specifically the right to disseminate religious information. taxation or exemption infringe no Constitutional In the case at bar. be liable to a penalty to the total amount of refunds which It was contended that said ordinances imposing was not refunded to the employee resulting from license fee on the distribution and sale of bibles any excess of the amount withheld over the tax and other religious literature. (Bishop of Nueva Segovia vs. impair the free actually due on their return exercise of religion. 22(3) Art. protection and of the properties. 22(3) Art.” donee’s gift tax not on the properties themselves. (CIR vs Algue 158 SCRA 9) The exemption under Sec. natural reluctance to surrender part of one's hard earned income to the taxing authorities. and parsonages or inherent in the power to tax that a State be free convents. appurtenant thereto and all lands. Without taxes. upon the exercise of the advancement therefore redound greatly to the privilege of receiving the properties. Province of Ilocos Norte 51 PHIL 352 Exemption from payment of land tax. Taxation may be made the Constitution only covers taxes assessed on implement of the state's police power. appurtenant thereto and all lands. and parsonages or civilized society. . to select the subjects of taxation and it has been buildings and improvements used exclusively for repeatedly held that “irregularities which result religious purposes. This kind of general welfare. is liable to pay the said gift tax. TAX ATION San Beda College of LAW – ALABANG employer/withholding agent who fails or refuses (American Bible Society vs. moral and material values. The gift tax was an excise tax upon the use made The sugar industry’s promotion.
specific period. whereas that which Held: is imposed by the ordinance is a typical tax or The filing of the criminal complaint with revenue measure. Memo Circ. the DOJ cannot be construed as a formal assessment. The G. not to On March 1. Inc. 1993. the Commissioner denied private Subject Matter: Criminal Action respondent’s request for reconsideration (reinvestigation on the ground that no formal assessment has been issued which the latter CIR V CA elevated to the CTA on a petition for review. 1987 and tax due and a demand to private respondents for 1988. 1. It did not state a demand or period Facts: for payment. No. file a criminal complaint for tax evasion. in such tax evasion cases. same purpose. dismissed the petition. with the criminal complaint. The CA sustained the CTA decision and Cebu/Cebu Portland Cement Co. 1999) merely contained a computation of respondent’s tax liability. or to do both. or to file a received a subpoena from the DOJ in connection criminal case against the taxpayer. The revenue officer’s affidavit (GR No. CIR had. On July 1. Naga. 1993 respondent was denied by CTA and ordered the to investigate tax liabilities of manufacturers Commissioner to file an answer but did not engaged in tax evasion schemes. 1993. it was not meant to be a notice of Development Corp. (Fortune) as foreign brands subject report as assessment which may be appealed to to a higher tax rate. They joint affidavit examine the books of accounts and other was meant to support the criminal complaint for accounting records of Pascor Realty and tax evasion. On August 3.65 and P3. Such evasion may be instituted. al. and not to private assessment of P7.434. TAX ATION San Beda College of LAW – ALABANG (San Miguel Brewery. Cebu February 20. The examination resulted in the payment thereof. 1995. vs. 128315. 1996 Commissioner’s motion to dismiss on the ground of the CTA’s lack of jurisdiction inasmuch as no Facts: formal assessment was issued against private A task force was created on June 1. respectively. Whether or not the criminal complaint for there is double taxation only when the same tax evasion can be construed as an person is taxed by the same jurisdiction for the assessment. Whether or not an assessment is business tax is a license tax to engage in the necessary before criminal charges for tax business of wholesale liquor in Cebu City. 1995.015.R. 1973) Issues: This is because double taxation is not prohibited by the Constitution.236. the annual 2. criminal complaint for tax evasion against PRDC.35 respondent. private respondents whether to issue an assessment. 119322. and must demand payment of the taxes described therein within a CIR V PASCOR REALTY & DEV’T CORP et. An assessment is not necessary before its president and treasurer before the DOJ. 37-93 which abuse of discretion and lack of jurisdiction on the reclassified certain cigarette brands part of CTA for considering the affidavit/report of manufactured by private respondent Fortune the revenue officers and the endorsement of said Tobacco Corp. In a letter dated. June 29. discretion on On March 23. May 17. June 4. 1995. Private criminal charges can be filed.498. Neither the Tax Code nor the revenue regulations governing the protest assessments provide a specific definition or form Subject Matter: Criminal Action. license tax constitutes a regulatory measure in the exercise of police power. (PRDC) for 1986. Tax of an assessment. Furthermore. No. In the first case. shows that commissioner intended to for 1986 and 1987. A criminal charge respondents filed immediately an urgent request need not only be supported by a prima facie for reconsideration on reinvestigation disputing showing of failure to file a required return. Fortune . instead filed a petition with the CA alleging grave the CIR issued Rev. vs. The fact that the complaint recommendation for the issuance of an was sent to the DOJ. It was addressed to the Secretary of The CIR authorized certain BIR officers to Justice not to the taxpayer. Commissioner filed a issue an assessment. The the tax assessment and tax liability. City of he CTA. Assessment An assessment must be sent to and received by the taxpayer.
duties in the regular course in ensuring that the In the meantime. The CTA found dismissed/set aside or alternatively. On April 1. that AZNAR’s returns were false because the under-declaration of income constituted a Held: deviation from the truth. If there was the ordinary prescriptive period of 5 years (now 3 fraud on willful attempt to evade payment of ad years) would apply under normal circumstances valorem taxes by private respondent through the but whenever the government is placed at a manipulation of the registered wholesale price of disadvantage as to prevent its lawful agent from the cigarettes. 1993. the Commissioner 1993 directing private respondent to submit their ordered the investigation of the case on the basis counter-affidavits. AZNAR appealed to the CTA. 1951. it must have been with the making a proper assessment of tax liabilities due connivance of cooperation of certain BIR officials to false or fraudulent returns intended to evade and employees who supervised and monitored payment of taxes or failure to the returns. 1974) non-payment of the correct income. a motion to suspend but declarations of income were discovered. Meanwhile 256. ruling that the Commissioner to assess AZNAR’s deficiency tax liability of private respondents first be settled income taxes for 1946. the fact that a tax is due must on September 7. The court stated that Fraud cannot be presumed. The trial court granted the petition for a writ of preliminary injunction to enjoin the Issues: preliminary investigation on the complaint for tax Whether or not the right of the evasion pending before the DOJ. The complaint was referred to Facts: the DOJ Task Force on revenue cases which found Matias Aznar died on May 15. there is the 8. of BIR personnel’s equal protection of laws. tax delinquency of P723. the court opined for fraudulent tax evasion can be initiated. private respondents filed reduced to P381. All motions filed thereafter were denied. TAX ATION San Beda College of LAW – ALABANG questioned the validity of said reclassification as correct taxes were paid. private respondent moved for to evade or defeat any tax under Secs. its corporate officers and 9 other corporations and their respective corporate officers for alleged fraudulent tax evasion for AZNAR CASE (August 23. 1947 and 1948 had before any complaint for fraudulent tax evasion prescribed at the time the assessment was made. 1997 NIRC. November 28. complaint and prosecutor’s orders be 1955. correct taxes were paid by Fortune. on August 3. But it filed a verified motion to of the net worth method. that the that AZNAR made substantial under-declarations preliminary investigation be suspended pending of his income as follows: he under-declared his determination by CIR of Fortune’s motion for income for 1946 by 227%.66 which was later January 4. His sufficient basis to further investigate the charges income tax returns from 1945 to 1951 were against Fortune. ad valorem and VAT for 1992. 1952. Substantial under- dismiss or alternatively. complaint with the DOJ against private respondent Fortune. much less evidence. On September 12. 1994. it cannot be correctly asserted within 30 days from receipt. AZNAR’s properties prayer for preliminary injunction praying the CIR’s were placed under distraint and levy. ad Before the tax liabilities of Fortune are valorem and VAT for 1992 with payment due finally determined. for 1948. can be initiated. 1953. the BIR notified AZNAR of a affidavit. Doubting the truth of the A subpoena was issued on September 8. 1993. The CTA. But there is no being violative of the right to due process and allegation. 564% for 1947.032.096. Held: Issue: On the issue of prescription the count Whether the basis of private respondent’s applied the 10-year prescriptive period and ruled tax liability first be settled before any complaint that prescription had not set in. Fortune was assessed deficiency income. 1958.07 upon reinvestigation. 95% reconsideration/reinvestigation of the August 13. On was denied and thus treated as their counter. on September malfeasance at the very least. 486% for 1949. 946% 1950. examined by the BIR. that private respondents have willfully attempted 1993. 254 and reconsideration of said assessment. income that he had reported. the Commissioner filed a first be proved. 1993 resolved that said reclassification was of presumption that BIR personnel performed their doubtful legality and enjoined its enforcement. 490% 1993 assessment of taxes due. a petition for certiorari and prohibition with On February 20. the Fortune’s production activities to see to it that the period of 10 years provided for in the law from .
TAX ATION San Beda College of LAW – ALABANG the discovery of the falsity. fraud or omission even seems to be inadequate and should be the one enforced. . | https://www.scribd.com/doc/158353465/17906784-Tax-1-Reviewer | CC-MAIN-2018-51 | refinedweb | 38,805 | 59.3 |
Following on from this previous post, the WPF and Silverlight code that I’ve been running tries to access a MeshObject ( containing a DataFeed of photos ) that the code itself creates at initialisation time.
What I wasn’t sure about at all was how that’d work if I wanted to make the same data available to another person altogether.
As it stands, my WPF code runs up and does;
- Check local mesh for “photos” MeshObject.
- If not present, check cloud mesh for the same.
- If not present, create it.
If I want to share my photos with lots of other users of the same application then is that what I want? All my users will end up with their own MeshObjects with their own photos and none of them will ever see each other.
So…I set about trying to figure out what the “shared data story” is.
There’s a sample in the walkthroughs called MeshageBoard ( no, really 🙂 ) which helps quite a lot with this in that it shows the way in which one user can send invitations to another.
In order to experiment with this, I decided that it was time to grab myself a secondary Live ID so that I could log in to Live more than once and to run that Live ID through the registration process for the Live Framework CTP ( luckily, I found that I had a little card at the bottom of my desk drawer from PDC with 2 Live Framework invitation codes on it so that I could get an invitation for my second account ).
What the sample taught me is about inviting users “to” a MeshObject. I wrote a bit of code to play with this – just a simple console application that exercises a few API’s;
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.LiveFX.Client; using System.Net; using Microsoft.LiveFX.ResourceModel; class Program { static void Main(string[] args) { while (!exit) { ReadAndExecuteOption(); } } static void ReadAndExecuteOption() { var options = new[] { new { OptionName = "loginLocal", OptionFn = new Action( () => OnLoginLocal() ) }, new { OptionName = "loginCloud", OptionFn = new Action( () => OnLoginCloud() ) }, new { OptionName = "createMo", OptionFn = new Action( () => OnCreate() ) }, new { OptionName = "contacts", OptionFn = new Action( () => OnContacts() ) }, new { OptionName = "exit", OptionFn = new Action( () => OnExit() ) }, new { OptionName = "displayMo", OptionFn = new Action( () => OnDisplay() )}, new { OptionName = "invite", OptionFn = new Action( () => OnInvite() ) } }; Console.Write("Options:"); foreach (var option in options) { Console.Write("[{0}] ", option.OptionName); } Console.WriteLine(); string input = Console.ReadLine(); var opt = options.Where( o => string.Compare(input, o.OptionName, true) == 0).SingleOrDefault(); if (opt != null) { try { opt.OptionFn(); } catch (Exception ex) { Console.WriteLine("Sorry, that didn't work - message is \n[{0}]\n", ex.Message); } } } static void OnCreate() { Console.WriteLine("Enter name of mesh object to create"); string name = Console.ReadLine(); MeshObject mo = new MeshObject(name); loe.Mesh.MeshObjects.Add(ref mo); } static void OnLoginLocal() { loe = new LiveOperatingEnvironment(); loe.ConnectLocal(); } static void OnLoginCloud() { Console.Write("Username:"); string userName = Console.ReadLine(); Console.Write("Password:"); string password = Console.ReadLine(); loe = new LiveOperatingEnvironment(); loe.Connect(new NetworkCredential(userName, password)); } static void OnContacts() { Console.WriteLine("Contacts..."); foreach (Contact c in loe.Contacts.Entries) { Console.WriteLine("\tContact: Display Name [{0}] LiveId [{1}]", c.Resource.DisplayName, c.Resource.Emails.Count == 0 ? "None" : c.Resource.WindowsLiveId); } } static void OnExit() { exit = true; } static void OnDisplay() { Console.WriteLine("MeshObjects..."); loe.Mesh.MeshObjects.Load(); foreach (MeshObject mo in loe.Mesh.MeshObjects.Entries) { Console.WriteLine("\tMesh Object: Title [{0}]", mo.Resource.Title); } } static void OnInvite() { Console.Write("Mesh Object Name:"); string meshObjectName = Console.ReadLine(); Console.Write("Live Id to Invite:"); string liveId = Console.ReadLine(); MeshObject mo = loe.Mesh.MeshObjects.Entries.Where( m => m.Resource.Title == meshObjectName).Single(); Invitation invitation = new Invitation(); invitation.Expires = DateTimeOffset.UtcNow.Add(new TimeSpan(1, 0, 0)); invitation.Email = string.Format("Would you like to join mesh object {0}", meshObjectName); Member member = new Member(liveId); member.Resource.PendingInvitation = invitation; member.Resource.Role = RoleType.Reader; mo.Members.Add(ref member); mo.Update(); } static LiveOperatingEnvironment loe; static bool exit; }
and with that in place I can go and run it…
The console window on the left shows me logging in to the cloud as mtaulty@hotmail.com and then creating a MeshObject called “TestObject”.
The console window on the right shows me logging in to the cloud as mtaulty@live.co.uk and first displaying that I only have one MeshObject called “Foo”.
In the console window on the left, I then go and invite mtaulty@live.co.uk into that MeshObject called “TestObject”.
Then ( in the background ) I (mtaulty@live.co.uk) go and accept the email invitation to the object called “TestObject” and so the next time I display my MeshObjects in the right hand window, that new object has shown up in my Mesh.
Very cool – it surprised me as to how easy this was. From the code above, I only gave the invited Member a role of Reader but I could have given them more control.
This makes me realise that I need to re-write my sketchy photo sharing “application” … 🙂 | https://mtaulty.com/2009/01/07/m_10995/ | CC-MAIN-2021-25 | refinedweb | 831 | 51.55 |
is there similar pytorch function as model.summary() as keras?
repr(model) gives something fairly close.
or easier to remember:
print(model)
gives the same result as repr(model)
Also, if you just want the number of parameters as opposed to the whole model, you can do something like:
sum([param.nelement() for param in model.parameters()])
Yes, you can get exact Keras representation, using this code.
Example for VGG16
from torchvision import models from summary import summary vgg = models.vgg16() summary(vgg, (3, 224, 224)) ---------------------------------------------------------------- Layer (type) Output Shpae Param # ================================================================ Conv2d-1 [-1, 64, 224, 224] 1792 ReLU-2 [-1, 64, 224, 224] 0 Conv2d-3 [-1, 64, 224, 224] 36928 ReLU-4 [-1, 64, 224, 224] 0 MaxPool2d-5 [-1, 64, 112, 112] 0 Conv2d-6 [-1, 128, 112, 112] 73856 ReLU-7 [-1, 128, 112, 112] 0 Conv2d-8 [-1, 128, 112, 112] 147584 ReLU-9 [-1, 128, 112, 112] 0 MaxPool2d-10 [-1, 128, 56, 56] 0 Conv2d-11 [-1, 256, 56, 56] 295168 ReLU-12 [-1, 256, 56, 56] 0 Conv2d-13 [-1, 256, 56, 56] 590080 ReLU-14 [-1, 256, 56, 56] 0 Conv2d-15 [-1, 256, 56, 56] 590080 ReLU-16 [-1, 256, 56, 56] 0 MaxPool2d-17 [-1, 256, 28, 28] 0 Conv2d-18 [-1, 512, 28, 28] 1180160 ReLU-19 [-1, 512, 28, 28] 0 Conv2d-20 [-1, 512, 28, 28] 2359808 ReLU-21 [-1, 512, 28, 28] 0 Conv2d-22 [-1, 512, 28, 28] 2359808 ReLU-23 [-1, 512, 28, 28] 0 MaxPool2d-24 [-1, 512, 14, 14] 0 Conv2d-25 [-1, 512, 14, 14] 2359808 ReLU-26 [-1, 512, 14, 14] 0 Conv2d-27 [-1, 512, 14, 14] 2359808 ReLU-28 [-1, 512, 14, 14] 0 Conv2d-29 [-1, 512, 14, 14] 2359808 ReLU-30 [-1, 512, 14, 14] 0 MaxPool2d-31 [-1, 512, 7, 7] 0 Linear-32 [-1, 4096] 102764544 ReLU-33 [-1, 4096] 0 Dropout-34 [-1, 4096] 0 Linear-35 [-1, 4096] 16781312 ReLU-36 [-1, 4096] 0 Dropout-37 [-1, 4096] 0 Linear-38 [-1, 1000] 4097000 ================================================================ Total params: 138357544 Trainable params: 138357544 Non-trainable params: 0 ----------------------------------------------------------------
Actually, there’s a difference between keras model.summary() and print(model) in pytorch. print(model in pytorch only print the layers defined in the init function of the class but not the model architecture defined in forward function. Keras model.summary() actually prints the model architecture with input and output shape along with trainable and non trainable parameters.
I haven’t found anything like that in PyTorch. I end up writing bunch of print statements in forward function to determine the input and output shape.
If you check the repo, that summary is only printing what’s in init function not the actual forward function where you will apply batch normalization, relu, maxpooling, global max pooling like stuff.
VGG model is printing because its implemented that way, meaning ReLu layer is defined in init function instead of Functional relu. I faced huge problem when implementing UNet, and that’s just one example.
Check this from the repo
import torch import torch.nn as nn import torch.nn.functional as F from torchsummary import summary, dim=1) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # PyTorch v0.4.0 model = Net().to(device) summary(model, (1, 28, 28)) ---------------------------------------------------------------- ----------------------------------------------------------------
This summary absolutely doesn’t make any sense.
The summary would still give you all parameters, no?
If you are interested in printing the graph, have a look at e.g. this topic.
I just want a easy function call to print the model summary the way Keras do. PyTorch should have added that. I should not be doing all kind of tricks just to see my model summary with input and output shapes of every layer. I love working in PyTorch that’s why I am looking for that type of function that would make model development easy.
pytorch-summary should yield the same output as Keras does.
What are you missing?
pytorch-summary can’t handle things like lists of tensors in forward(). Pytorch should definitely have a summary() function which can handle any operations done inside the model.
you can try this library pytorch-model-summary. I rewrote to support scenario you described, adding other options as well
This worked for me
!pip install torchsummary from torchsummary import summary summary(your_model, input_size=(channels, H, W))
Really love your work ! works perfectly. thank you.
For a given input shape, you can use the
torchinfo (formerly
torchsummary) package:
Torchinfo provides information complementary to what is provided by
print(your_model)in PyTorch, similar to Tensorflow’s
model.summary()…
Example:
from torchinfo import summary model = ConvNet() batch_size = 16 summary(model, input_size=(batch_size, 1, 28, 28)
========================================================================================== Layer (type:depth-idx) Output Shape Param # ========================================================================================== ├─Conv2d (conv1): 1-1 [5, 10, 24, 24] 260 ├─Conv2d (conv2): 1-2 [5, 20, 8, 8] 5,020 ├─Dropout2d (conv2_drop): 1-3 [5, 20, 8, 8] -- ├─Linear (fc1): 1-4 [5, 50] 16,050 ├─Linear (fc2): 1-5 [5, 10] 510 ========================================================================================== Total params: 21,840 Trainable params: 21,840 Non-trainable params: 0 Total mult-adds (M): 7.69 ========================================================================================== Input size (MB): 0.05 Forward/backward pass size (MB): 0.91 Params size (MB): 0.09 Estimated Total Size (MB): 1.05 ==========================================================================================
Note: Unlike Keras, PyTorch has a dynamic computational graph which can adapt to any compatible input shape across multiple calls e.g. any sufficiently large image size (for a fully convolutional network).
As such, it cannot present an inherent set of input/output shapes for each layer, as these are input-dependent, and why in the above package you must specify the input dimensions. | https://discuss.pytorch.org/t/is-there-similar-pytorch-function-as-model-summary-as-keras/2678/3 | CC-MAIN-2022-21 | refinedweb | 941 | 61.16 |
This is the mail archive of the cygwin-apps mailing list for the Cygwin project.
On Aug 20 16:44, Corinna Vinschen wrote: > On Aug 20 16:06, Corinna Vinschen wrote: > >. > > On further looking into this, it appears that the termcap/terminfo > entries are wrong. ESC O A to ESC O D are only generated after > entering the DEC expanded cursor mode with ESC [ ? 1 h. The default > codes are ESC [ A to ESC [ D. It's not clear to me why the > termcap/terminfo entries list the expanded mode sequences instead of > the standard sequences. I'd like to suggest the below patch. It aligns the handling of Home and End key to its xterm counterparts. That doesn't solve the problem with the rxvt-cygwin-native termcap/terminfo entries, but it let rxvt work better in default xterm mode. Home and End now generate the vt102/vt220/xterm sequence ESC [ H and ESC [ F. After switching to the DEC extended cursor mode, they generate ESC O H and ESC O F, same as vt102/vt220/xterm. Corinna --- command.c.ORIG 2007-08-20 16:51:43.419482700 +0200 +++ command.c 2007-08-20 16:55:20.632170700 +0200 @@ -465,6 +465,8 @@ rxvt_lookup_key(rxvt_t *r, XKeyEvent *ev #endif case XK_End: STRCPY(kbuf, KS_END); + if (r->h->PrivateModes & PrivMode_aplCUR) + kbuf[1] = 'O'; break; #ifdef XK_KP_Home case XK_KP_Home: @@ -477,6 +479,8 @@ rxvt_lookup_key(rxvt_t *r, XKeyEvent *ev #endif case XK_Home: STRCPY(kbuf, KS_HOME); + if (r->h->PrivateModes & PrivMode_aplCUR) + kbuf[1] = 'O'; break; #define FKEY(n, fkey) \ --- command.h.ORIG 2007-08-20 16:56:10.099082700 +0200 +++ command.h 2007-08-20 16:56:20.687946700 +0200 @@ -38,8 +38,8 @@ # define KS_HOME "\033[1~" /* Home == Find */ # define KS_END "\033[4~" /* End == Select */ #else -# define KS_HOME "\033[7~" /* Home */ -# define KS_END "\033[8~" /* End */ +# define KS_HOME "\033[H" /* Home */ +# define KS_END "\033[F" /* End */ #endif #ifdef SCROLL_ON_SHIFT -- Corinna Vinschen Please, send mails regarding Cygwin to Cygwin Project Co-Leader cygwin AT cygwin DOT com Red Hat | http://cygwin.com/ml/cygwin-apps/2007-08/msg00151.html | CC-MAIN-2017-22 | refinedweb | 336 | 73.88 |
If you use the Divi theme or Divi Builder, you’ll regularly work with modules. They are the building blocks within the theme that enable you to add page elements, style them, control them and utilize them to create beautiful websites.
Trouble is, when you’re in the middle of designing or trying to navigate your way around Divi Builder, it’s difficult to see exactly what’s available.
This complete guide to Divi modules will outline the 46 core modules contained within Divi. It will also highlight some free and premium modules from third party developers.
All so you can make the most of Divi for your, or your client’s websites.
This article is one of our many Divi reviews that CollectiveRay has done to cover the various aspects of the Divi theme and builder.
Need to get Divi at a bargain price? We've currently got an exclusive discount from Elegant Themes:
Get Divi for 10% OFF in February 2021 Only
Official Divi Modules
There are 46 Divi modules currently available.
1. Accordion
The Accordion adds an accordion slider module to a page. You know when you see a content box with a selectable element and it slides down to reveal more content? That’s an accordion.
For Divi, an accordion module is a selectable element containing content. Select the first line and it expands to reveal a brief explanation or overview. Select the next line and the first line closes and the second opens. It’s an elegant way to include a lot of content in a small space.
2. Audio
The Audio module provides an audio player you can place anywhere on a page. You can link the player to a locally hosted audio file so it plays whenever a user selects it.
In Divi, the Audio module is a simple audio player but if you know a little CSS, you could style it yourself.
3. Bar Counters
Bar Counters are the progress bars you see on websites all over the internet. Done right, they are an immediately understandable measure of something and can work very well in the right situation.
Divi Bar Counters can be coloured, customized to suit almost any purpose, be manually configured for specific levels and be used in any number of ways.
4. Blog
The Divi Blog module allows you to place blog posts anywhere on a page. Not only can you position these posts anywhere, you can also style them to suit your theme.
The Divi Blog module provides complete freedom over where and how you display your blog posts. You’re no longer tied to where WordPress or your theme thinks you should have them with this module.
5. Blurb
The Blurb module is a content element complete with icon and optional animations. These are useful for product or service descriptions on pages as the optional animation aspect can add a little interest to a page.
The Divi Blurb module has a range of icons, colours and animation options depending on how you use them. Some are contained as defaults within the module while others can be implemented with CSS.
6. Button
The Divi Button module provides the means to add buttons anywhere on your site, in any colour and a wide range of shapes and sizes. The design can be controlled in the theme customizer and links and effects configured at the same time.
They are a simple but effective extension to the existing button options within Divi.
7. Call To Action
Calls to action play a vital role in conversion. The more compelling you can make them, the more effective they can be. That’s where this module comes in.
The Divi Call to Action module provides an easy way to build your own calls to action using a mixture of CTA box, headline, content and button to help increase conversions anywhere on your website.
8. Circle Counter
The Circle Counter module works in a similar way to Bar Counters but use a full circle graphic instead. Rather than a simple bar, the module adds a full circle with areas covered depending on what percentage you mark as complete.
The Circle Counter works with the theme customizer and can be fully customized to suit any theme.
9. Code
The Divi Code module is a custom code element that you can add to any page. It accepts shortcodes, CSS and HTML and can help you accomplish a multitude of things within a page.
They work similar to custom CSS elements within themes, only you can place them anywhere and have them do almost anything as they are not constrained by the theme.
10. Comments
The Divi Comments module enables you to add a comment from your blog anywhere on the page. For example, a recommendation or feedback from a blog comment can be featured on a product page.
Rather than using an image, you can include the real thing and then link to the main comment, which just adds to the authenticity.
11. Contact Form
The Contact Form module is useful if you don’t want to use a third-party contact form plugin. You can implement a form anywhere on the page and style it using the theme customizer.
You can create multiple forms, use field validation and conditional logic to make any form work.
12. Countdown Timer
Countdown timers are often used for product releases, countdowns to special offers or sales or for creating time anxiety in readers.
The Countdown Timer module helps with that by allowing you to style a timer, add your own countdown and place it anywhere on the page.
13. Divider
Dividers are small but important ways to break up web pages and give the audience a bit of a break before the next section. Most web themes seem to include them as an afterthought, which is where Divi comes in.
The Divi theme has dividers but the Divider module adds more.
14. Email Opt-in
Email Opt-in forms are essential for building email lists and for increasing engagement. Email is still an incredibly powerful marketing tool and the Email Opt-in module aims to help with that.
You can create forms, newsletter signups and lead generating elements using this module and then link it to your email program to help manage it efficiently.
15. Filterable Portfolio
The Filterable Portfolio module is ideal for including an attractive portfolio section within a page. You can style it, configure your own categories and filters and create a fully interactive portfolio.
Some Divi themes come with portfolio elements built in and the Divi Builder has them too but this module adds even more.
16. Gallery
The Divi Gallery module does much the same for galleries. It enables you to showcase images and videos anywhere on a page.
The gallery can be fully customized and include any image you like. You can set the style as a grid or slider and control many aspects of the look and feel of it from the customizer.
17. Image
The Divi Image module adds a range of options when displaying images on a page. You can add lightbox effects, implement lazy loading, add animations and make your images really stand out.
Images have a powerful effect on engagement and time on page so doing your images justice makes perfect sense. This module can help with that.
18. Login
The Divi Login module adds a characterful login form to pages using the familiar styling of your theme. The module can be styled to suit the page to either sit in the background or stand out and be noticed.
The login page will automatically log the user into the site without redirecting to the default WordPress login page.
19. Map
The Divi Map module takes the standard map element and adds extra customization options and seamless integration into a page. As maps can play an integral role in some sites, this is a very useful addon to use!
Map integrates with Google Maps to highlight locations or add interactive elements. It can be styled to match your page too.
20. Number Counter
The Number Counter module is another graphical device for communicating with your audience. Rather than using a bar or circle graphics, this module uses simple numbers to communicate.
It works in the same way as those others too. Style it in the theme customizer and place it anywhere on the page.
21. Person
The Person module adds personalities to your website. Whether you want to showcase authors, provide insight into your team or something else, the Person module is how you do it.
You can add an image, biography copy, social media links and post it anywhere on your website. There are customization options too if you need it to fit into an existing theme.
22. Portfolio
The Portfolio module builds on the options provided by Gallery by allowing you to showcase your work in a number of ways. If you’re a freelancer or small business and want to show off your work, this is how.
The module can work with grids, full-width layouts, offer category filters and pagination. There are also some customizations you can apply should you need to.
23. Post Navigation
The Post Navigation takes the default read next or previous options and makes them more attractive. While WordPress and many themes have these features, the Divi option adds even more utility.
The module allows you to include attractive previous and next buttons to the bottom of posts to allow readers to work their way through your blog.
24. Post Slider
The Post Slider module is a great way to showcase your blog posts. It uses a slider to roll through a defined series of blog posts to show off your work and attract clicks.
While many other plugins offer to list or show blog posts, a slider can include a colourful image and excerpt which is sure to engage. Minor customizations are also possible with this module.
25. Post Title
The Post Title module is a small but useful addition that uses Divi styling for post titles. It displays the title and also has the option of adding a featured image and any metadata you might want to display too.
The module has a few customization options you can use to fit it into a theme but the defaults work well enough for most uses.
26. Pricing Tables
Pricing tables are one of those elements that very few WordPress themes seem to get right. Divi isn’t one of them. The default theme tables work well enough but you can supercharge that with the Pricing Tables module.
This module adds a customizable table you can fit on any page. You can change colours, currencies, number of features and effects as required.
27. Search
Search is another of those features that is usually less than ideal. The default WordPress search function can be slow and miss the obvious. Some themes include search which often disappoints. The Divi Search module changes all that.
This is a simple search box you can place anywhere and style to suit your theme. Simple, fast and very effective.
28. Shop
The Divi Shop module is an excellent extension to WooCommerce. If you already run a store, this module allows you to feature products in a standalone element anywhere on your site. It’s an excellent opportunity to cross-sell or upsell.
The module allows you to sort products, style the element and perform a few customizations to the display too.
29. Sidebar
The Sidebar module is one of the most useful of any module in this list. It takes a standard sidebar and gives you full control of how it looks, what it features and how it works.
The module lets you build custom sidebars using the theme customizer and place them on all pages, some pages or specified pages.
30. Slider
Sliders may be contentious subjects but there is no doubt that they can be effective if they are styled right. The Divi Slider module does just that.
It’s a simple slider you can place anywhere on the page and customize to fit the design. You can also use video, images, control the slide type and a whole lot more.
31. Social Media Follow
Follow buttons are another page feature few themes manage to get right. They are such a simple feature but can often look clumsy, not work properly or look like they have been added with a plugin.
The Social Media Follow module is different. It adds some attractive icons with links and allows you to customize them to suit your needs.
32. Tabs
If the Accordion module isn’t what you’re looking for, perhaps the Tabs module is. This is another way of featuring a lot of text without overloading the page.
This addon allows you to create a content element with a number of horizontal tabs that can feature copy, images or video.
33. Testimonial
The Testimonial module adds social proof to a page. We all know how important social proof is and this module allows you to add it anywhere.
You have several styling options to fit the module into the page, you can feature an image, some copy and links depending on your needs.
34. Text
The Text module allows you to access the WordPress text editor to add custom text anywhere you like. It’s another minor but useful addon that offers a lot more freedom in terms of text placement on a page.
35. Toggle
The Divi Toggle module works in a similar way to Accordion in that it toggles content boxes to slide open and closed. Where Accordion uses a single box with multiple slides, Toggle uses individual boxes that each slide individually.
It’s a useful alternative to Accordion where you might only have a couple of elements you want to use or would want all elements open at once.
36. Video
You can already embed video in WordPress but you need to use the entire iFrame URL in the code view. The Divi Video module saves all that.
The module lets you embed an uploaded or linked video anywhere on a page. You can also set a custom image instead of the first frame and customize the play button.
37. Video Slider
The Video Slider module takes video and adds a slider. You can set a main video and feature a number of others underneath and let the slider switch between them.
The module lets you customize the first image and play button, use uploaded or linked videos and place them anywhere on a page.
38. Fullwidth Code
The Fullwidth Code module works with full width Divi themes and lets you embed code onto a page while retaining formatting. It’s a simple but effective module that could be useful for how-to websites, developer websites or something else.
39. Fullwidth Header
The Fullwidth Header module allows you to create a header using the full width of the page. Simple but very effective. You can feature a headline, sub-header and copy along with up to two buttons.
40. Fullwidth Image
Fullwidth Image is the full width version of Image but works seamlessly in full width designs. It has all the same display and customization options too.
41. Fullwidth Map
The Fullwidth Map module works just like Maps but for full width pages. You also get the same Google Map compatibility, customization options and ease of use as that module.
42. Fullwidth Menu
Fullwidth Menu provides a custom menu that stretches across a page. It takes the standard WordPress menu and features it in a custom element. You can then customize the menu in the usual way.
43. Fullwidth Portfolio
This module takes the standard Portfolio module and makes it work with full width pages. It has the same customizations and features but works with this layout.
44. Fullwidth Post Slider
The Fullwidth Post Slider takes the Post Slider module and makes it work across the full width of a page. It has the same utility and customization options as that module, offering full control over how it looks to the user.
45. Fullwidth Post Title
The Fullwidth Post Title is the same as Post Title but works fullwidth. It’s something we imagine you would use sparingly on a page but this Divi module makes sure you can feature full width titles without any coding.
46. Fullwidth Slider
The Fullwidth Slider takes the Slider module and does the same. Makes it work flawlessly with a full width design. This is a more useful module with full control over how the slides look and feel.
WooCommerce Divi Modules
WooCommerce is very well served by Divi. Some extend existing features within WooCommerce pages while others enable you to feature some store elements in non-store pages.
Each is worth checking out if you’re looking for more flexibility in how you design your store.
1. Woo Breadcrumb Module
Breadcrumbs are used frequently on websites to help navigation. The Woo Breadcrumb module for Divi does the same thing for your store. The options are simple and include a course page, current page and optional link and separator.
It’s a simple but effective module that enables you to place descriptive breadcrumbs at the top of the page to help your users navigate.
2. Woo Title Module
This module allows you to have full control over product titles. You can change the title, style it and add links, backgrounds and configure as required. It builds on the default title option by adding more design tools and some advanced spacing.
What’s more, when you update a title with this module, you can set it to automatically update everywhere on your site.
3. Woo Image Module
The Woo Image Module offers full control over product imagery on your store. The default options are good, but this takes it further. You can add a number of images, use a thumbnail slider and add badges or graphical layers for offers or something else.
The module has a few customization options you can use to style the image and then lets you place it anywhere you like on any page.
4. Woo Gallery Module
The Woo Gallery Module builds on the Image Module by incorporating images into a product gallery. It offers similar options to the Divi Gallery module we mentioned earlier and offers the opportunity to style the gallery and place it anywhere, on any page.
Images sell products, so this is an excellent option if the default image capacity of WooCommerce isn’t delivering what you need.
5. Woo Price Module
The Woo Price Module extends pricing and enables you to feature products and prices on any page, not just store pages. It’s a customizable element that displays current price, old price, sale price and design those prices to fit your theme.
While the standard WooCommerce plugin has a lot of pricing options built in, this module takes it a step further and includes the ability to promote on non-product pages.
6. Woo Add to Cart Module
The Woo Add to Cart Module delivers full control over the actual purchase. With it you can style the Buy It Now button in any way you like. From what it says to how it looks and separate the button from the default WooCommerce layout.
If, for some reason, the default price and button layout doesn’t work for your theme, this module helps with that. You can place it anywhere, style it, show a quantity option and even a remaining stock display.
7. Woo Rating Module
Ratings are everything in retail. Highly rated products outsell non-rated products by a significant margin. The rise of reviews and social proof can be yours to command with the Woo Rating Module.
It lets you place a rating on a page, display reviews, display the number and average rating of those reviews and links to them. Every store should use ratings and this is how to do it.
8. Woo Stock Module
The Woo Stock Module does exactly what it says on the tin. It enables you to show an accurate stock number in your product display. This can help increase urgency, which in turn increases conversion.
You can style each display to help with that urgency by highlighting low stock in red or high stock in green, add ‘Out of stock’ text and place it anywhere on the page.
9. Woo Meta Module
The Woo Meta Module takes care of little details like displaying SKU, tags, categories and supplementary data on a page. If you want to include as much data as possible on pages then this module will help.
It isn’t a freeform module but can take internal meta and display them for all to see. You can style the design though.
10. Woo Description Module
The Woo Description Module lets you display a product description for a specific product anywhere within a Divi theme.
It’s a basic but usable module that enables you to promote products on blog pages or service pages and fully style the look and feel of that description.
11. Woo Tabs Module
The Woo Tabs Module works in a similar way to the Divi Tabs module. It installs a tabbed content element to a page that you can fill with whatever content you like.
Tabs can be useful for combining multiple sources of information on a single page. For example, product details, product specifications, delivery options and reviews within a single box with a tab for each.
12. Woo Additional Information Module
The Woo Additional Information Module is for those who want more. Have products with extra options? This is the module to use. For example, sizes or different colours would be featured here.
You can style it however you like and place it on a page using the standard customizer. Another simple but valuable addition.
13. Woo Related Products Module
The Woo Additional Information Module should need little introduction. Stores thrive on cross-selling and upselling and this module is how you do it. You can add a Related Products section to a page and add supporting information as desired.
Every store should use cross-selling and if the standard WooCommerce options aren’t enough, this module works seamlessly with Divi.
14. Woo Upsell Module
The Woo Upsell Module does much the same thing. You can add this to product pages or to any page on your site to upsell products.
The products featured in this module will be those you have set as upsell options in WooCommerce. This module just lets you place them anywhere on a page.
15. Woo Cart Notice Module
The Woo Cart Notice Module is a value-add option that adds a simple notice to a product page notifying the user they have added a product to cart. It’s a simple but useful piece of interaction that can mark a great store out from just a good one.
Notifications can be styles and with colours and fonts. The default setting will use your theme colour but you can easily override that if you prefer.
16. Woo Reviews Module
The Woo Reviews Module allows you to place product reviews for your items on any page on your site. It is useful for promotion pages or blog posts to add that vital social proof to help influence a buying decision.
The module allows you to set specific fields, show comment counts and influence colour and style. It’s a useful module if you promote in places other than your product pages.
10 of the Best Free Divi Modules
There is a wide range of free Divi modules out there and not all of them are created equal. We think these 10 free Divi modules are well worth trying.
1. Divi Tweaker
Divi Tweaker is a very smart module that helps speed up the Divi Builder and WooCommerce, removes Query Strings that can slow down page loading and can replace local theme files with files served from a CDN.
The module also adds some extra design features for mobile and desktop, some animations and effects, page transitions, layout options and a whole lot more.
2. Divi Advanced Text Module
Divi Advanced Text Module is a small but very useful module that expands the existing text options and adds some useful tools. If you work a lot with text, as we do, the ability to change the width and height of the text element makes a huge difference when you’re trying to perfect a page layout. This module does that.
It also adds an image upload tool that shortens design times in a small but important way.
3. Divi Slimbuilder
Divi Slimbuilder is ideal if you build landing pages or longer site pages with the Divi Builder. It changes the layout of the main window so the page elements are slimmer. It also changes the way section titles are displayed to make the entire design process much smoother.
It’s a small thing but means you can see a lot more of what’s going on with the back-end of the design without having to keep scrolling up and down.
4. Article Cards Extension
Article Cards Extension was apparently Elegant Themes’ first ever Divi module. It is so useful that it’s still around and still popular today. It’s another modest module that adds more styling options to the Divi Blog module to change the way the blog cards are displayed.
Changes are modest and include shadow effects, background colours, the ability to style the blog grid and change the position of the blog title and meta.
5. Divi Icon Expansion Pack
The Divi Icon Expansion Pack does exactly what it says it does. It adds a raft of hand-drawn icons to the Divi Builder for you to use in your design. There are hundreds to choose from and you can customize them all to suit your theme.
There is a free and a premium version of this module. The premium adds more icons and customization options.
6. Expand Divi
Expand Divi is another self-explanatory Divi module. It adds a range of features to Divi including Lightbox, a new related posts section, new author boxes, new recent posts element, animator for page preloading, Font Awesome tools and a whole lot more.
The module hasn’t been updated for a while but we tested it on the latest version of WordPress and Divi and it worked fine.
7. Battle Suit for Divi
As well as having a very cool name, Battle Suit for Divi has a lot to offer. It’s an expansion module that adds more post, footer, gallery and image options, adds Lightbox for image and video, adds image effects, post title and meta options and a ton of other tools.
Considering this is a free module, there is a lot going on here and the module makes everything accessible and very easy to use.
8. Simple Divi Shortcode
Simple Divi Shortcode takes a very powerful tool in WordPress, shortcodes, and allows you to place them anywhere inside other modules. It’s another very simple tool that can make a huge difference if you use shortcodes a lot in your pages.
There is a free and a premium version of this plugin but the free option does everything you’re likely to need it to do.
9. Surbma Divi Extras
Surbma Divi Extras adds a few more features to Divi that some of you might find useful. One thing that makes it stand out is the text logo option. You may not need to use it often, but when you do, this tool alone makes this module worth using.
The module also adds styling, layout, menu and footer options and has a very neat vertical centre option for copy within a module. This is another of those tools that can be a genuine lifesaver!
10. Popups for Divi
Popups for Divi is very useful if you want to create a single popup but don’t want to use a dedicated popup plugin for WordPress. It adds a feature where you can create an element within the builder and use it as a popup for marketing.
It’s a simple solution to a serious problem and ideal for creating basic popups within a page without having to use or pay for a popup plugin.
10 Premium Divi Modules
There are hundreds of premium Divi modules out there. Some are worth the investment and others, not so much. These 10 are definitely worth your money!
1. Divi Carousel Module 2.0
Divi Carousel Module 2.0 helps you build carousels for almost anything within Divi. They can be useful for products, services, testimonials and all kinds of promotional features. This plugin makes them happen.
It allows you to create as many carousels as you like and save them as templates to use anywhere. You have full control over how they look and feel and all the designing is done within the builder. A superb option for displays.
2. Divi Ecommerce
Divi Ecommerce works with both Divi and WooCommerce to shortcut building an online store. It has a couple of designs to use as templates, some custom page elements, demo content to get you up and running quickly and everything you need to build a basic store.
The module even comes with sidebars, social sharing, product layout options, countdown clocks, trending product modules and a lot more options. If you don’t like any of the Divi demos, this could be the module for you.
3. Divi Headers Pack
The Divi Headers Pack is huge. It adds over 750 new headers, some functional, some new designs. It adds off-canvas menu options, responsive headers, menu effects, menu animations and a ton of tools for styling headers.
This module has a very narrow focus but it is well worth the investment if you’re having trouble finding the perfect header. If you don’t find it here, you won’t find it anywhere!
4. Divi Supreme Pro
Divi Supreme Pro includes a range of modules to enhance your creativity while using Divi. Modules include Gradient Text, Flipbox, Text Divider, Divi Typing, Supreme Button, Facebook Feed and a number of others.
There is a lot contained within this module, over 40 different modules and 7 premium extensions. Considering the price, Divi Supreme Pro is a bargain!
5. Divi Events Calendar
Divi Events Calendar can be used to build a complete event management website or be used to add events to a standard site. It uses the standard Divi Builder to help create events and has everything you need to style and display them.
This module includes a calendar, carousel, event feed and page module to help you create a fully functional events website or event section and is well worth checking out.
6. Table Maker
Some people find tables easy while others find them a frustrating mess. If you’re in the latter camp, the Table Maker module is for you. It enables you to quickly embed a table in a page and style everything about it.
You can add images, icons, texts, buttons and even collapse rows for mobile. It’s a very powerful plugin that makes short work of adding and styling tables to any page and for that it is well worth buying.
7. Divi Modal Popup
If you want to utilize popups and Popups for Divi isn’t enough, Divi Modal Popup will be. It’s a feature-rich module that makes short work of creating popups from page load, time delay and a range of other triggers.
More importantly, you can include the full range of page elements, place your popup anywhere, have it triggered by anything on the page and add animations to the popup itself. If you want to increase engagement with popups, this is what you use.
8. Divi Responsive Helper
The Divi Responsive Helper is a tool to help you see exactly how your page will load on mobile from within the Builder. You can also change how it looks, how it loads, change the order of elements and fully control how your site looks on mobile devices.
The module also includes a very smart automatic fixer tool that can rebalance sentences or paragraphs so they look better. That alone makes it worth the purchase!
9. Divi Masonry Gallery
Divi Masonry Gallery is ideal if you want more from a portfolio or blog page. It takes the standard masonry layout and adds the ability to create different shapes, change columns, add or remove space, add modal popups and configure a specific gallery for mobile.
If you’re designing an image-rich website and want to do more with masonry, this module lets you do everything from within the familiar Builder interface.
10. Divi MadMenu
Divi MadMenu adds more options to the menu section of Divi Builder. If the default settings aren’t enough, this module adds more. It also breaks a header down into separate sections for easy customization.
The module lets you control how the menu works on different screen sizes, set different layouts for different devices, adds Ajax elements for products, adds calls to actions and other elements too. It’s a powerful way to master headers.
If you're looking for additional functionality, check out our article about Divi plugins.
How to Develop Your Own Custom Divi Module
Want to develop your own Divi module? Have an issue that isn’t covered by an existing module?
This part of the article is here to help.
We are going to outline the basics of developing your own custom Divi module. You will need basic PHP skills to complete this section as Divi Builder defines modules as PHP classes.
First you will need to create a Divi extension. You have to do this first because your custom Divi module is implemented within an extension, theme or child theme and the extension is the easiest to create.
Read this guide to create your extension. Once you’re done, come back here to create your module.
Open your extension and locate includes/modules
Create a directory called SimpleHeader
Create a file in SimpleHeader and call it SimpleHeader.php
Paste the following into the file and save
< ) {
}
}
new SIMP_SimpleHeader;
If you know your PHP, you will see a basic header that can be used by Divi Builder. You will see a header, some content and background.
Now add some HTML to the file so it can render.
Add the following after ‘public function render( $unprocessed_props, $content = null, $render_slug ) {’
return sprintf(
'<h1 class="simp-simple-header-heading">%1$s</h1>
<p>%2$s</p>',
esc_html( $this->props['heading'] ),
$this->props['content']
);
}
}
new SIMP_SimpleHeader;
Your complete file should look like this:
< ) {
return sprintf(
'<h1 class="simp-simple-header-heading">%1$s</h1>
<p>%2$s</p>',
esc_html( $this->props['heading'] ),
$this->props['content']
);
}
}
new SIMP_SimpleHeader;
If it does, it’s now time to create the React Component class that lets Divi Builder render the module.
Create a file and call it SimpleHeader.jsx
Paste the following and save it
// External Dependencies
import React, { Component, Fragment } from 'react';
// Internal Dependencies
import './style.css';
class SimpleHeader extends Component {
static slug = 'simp_simple_header';
render() {
return (
<div className="simp-simple-header">
{this.props.content()}
</div>
);
}
}
export default SimpleHeader;
Navigate to includes/modules/index.js in your extension file
Add and save the following
// Internal Dependencies
import SimpleHeader from './SimpleHeader/SimpleHeader';
export default [
SimpleHeader,
];
Add the following to SimpleHeader.jsx after
render() {
return (
and save it.
<Fragment>
<h1 className="simp-simple-header-heading">{this.props.heading}</h1>
<p>
The full file should now look like this:
// External Dependencies
import React, { Component, Fragment } from 'react';
// Internal Dependencies
import './style.css';
class SimpleHeader extends Component {
static slug = 'simp_simple_header';
render() {
return (
<Fragment>
<h1 className="simp-simple-header-heading">{this.props.heading}</h1>
<p>
{this.props.content()}
</p>
</Fragment>
);
}
}
export default SimpleHeader;
Open your module’s style.css and add
.simp-simple-header-heading {
margin-bottom: 20px;
}
That’s it for developing your Divi module. All you need to do now is test it!
Open the Divi Builder, locate your Simple Header module and try to use it on a page. If you got the code right, you will see a simple header option.
Roundup of Divi Modules
We have included over 70 free and premium divi modules covering everything from creating popups to adding extra design features to Divi Builder. Some are niche modules you won’t use very often but some are essential for the smooth and efficient use of Divi Builder.
We think they represent a cross-section of what’s available, what works and what are sensibly priced. What do you think?
Do you use any of these Divi modules? Have any modules to suggest?
Please leave a useful comment with your thoughts, then share this on your Facebook group(s) who would find this useful and let's reap the benefits together. Thank you for sharing and being nice! | https://www.collectiveray.com/divi-modules | CC-MAIN-2021-10 | refinedweb | 6,191 | 62.68 |
java.lang.Object
org.netlib.lapack.DLASY2org.netlib.lapack.DLASY2
public class DLASY2
DLASY2 is a simplified interface to the JLAPACK routine dlasyASY2 solves for the N1 by N2 matrix X, 1 <= N1,N2 <= 2, in * * op(TL)*X + ISGN*X*op(TR) = SCALE*B, * * where TL is N1 by N1, TR is N2 by N2, B is N1 by N2, and ISGN = 1 or * -1. op(T) = T or T', where T' denotes the transpose of T. * * Arguments * ========= * * LTRANL (input) LOGICAL * On entry, LTRANL specifies the op(TL): * = .FALSE., op(TL) = TL, * = .TRUE., op(TL) = TL'. * * LTRANR (input) LOGICAL * On entry, LTRANR specifies the op(TR): * = .FALSE., op(TR) = TR, * = .TRUE., op(TR) = TR'. * * ISGN (input) INTEGER * On entry, ISGN specifies the sign of the equation * as described before. ISGN may only be 1 or -1. * * N1 (input) INTEGER * On entry, N1 specifies the order of matrix TL. * N1 may only be 0, 1 or 2. * * N2 (input) INTEGER * On entry, N2 specifies the order of matrix TR. * N2 may only be 0, 1 or 2. * * TL (input) DOUBLE PRECISION array, dimension (LDTL,2) * On entry, TL contains an N1 by N1 matrix. * * LDTL (input) INTEGER * The leading dimension of the matrix TL. LDTL >= max(1,N1). * * TR (input) DOUBLE PRECISION array, dimension (LDTR,2) * On entry, TR contains an N2 by N2 matrix. * * LDTR (input) INTEGER * The leading dimension of the matrix TR. LDTR >= max(1,N2). * * B (input) DOUBLE PRECISION array, dimension (LDB,2) * On entry, the N1 by N2 matrix B contains the right-hand * side of the equation. * * LDB (input) INTEGER * The leading dimension of the matrix B. LDB >= max(1,N1). * * SCALE (output) DOUBLE PRECISION * On exit, SCALE contains the scale factor. SCALE is chosen * less than or equal to 1 to prevent the solution overflowing. * * X (output) DOUBLE PRECISION array, dimension (LDX,2) * On exit, X contains the N1 by N2 solution. * * LDX (input) INTEGER * The leading dimension of the matrix X. LDX >= max(1,N1). * * XNORM (output) DOUBLE PRECISION * On exit, XNORM is the infinity-norm of the solution. * * INFO (output) INTEGER * On exit, INFO is set to * 0: successful exit. * 1: TL and TR have too close eigenvalues, so TL or * TR is perturbed to get a nonsingular equation. * NOTE: In the interests of speed, this routine does not * check the inputs for errors. * * ===================================================================== * * .. Parameters ..
public DLASY2()
public static void DLASY2(boolean ltranl, boolean ltranr, int isgn, int n1, int n2, double[][] tl, double[][] tr, double[][] b, doubleW scale, double[][] x, doubleW xnorm, intW info) | http://icl.cs.utk.edu/projectsfiles/f2j/javadoc/org/netlib/lapack/DLASY2.html | CC-MAIN-2014-42 | refinedweb | 424 | 64.2 |
Are you sure?
This action might not be possible to undo. Are you sure you want to continue?
Instructions for Form 1120S
(Rev. February 2004) U.S. Income Tax Return for an S Corporation
Section references are to the Internal Revenue Code unless otherwise noted. Contents Changes To Note . . . . . . . . . . . Photographs of Missing Children Unresolved Tax Issues . . . . . . . Direct Deposit of Refund . . . . . . How To Make a Contribution To Reduce the Public Debt . . . . . How To Get Forms and Publications . . . . . . . . . . . . . General Instructions . . . . . . . . Purpose of Form . . . . . . . . . . Who Must File . . . . . . . . . . . Termination of Election . . . . . Electronic Filing . . . . . . . . . . When To File . . . . . . . . . . . . Period Covered . . . . . . . . . . Who Must Sign . . . . . . . . . . . Paid Preparer Authorization . . Where To File . . . . . . . . . . . . Accounting Methods . . . . . . . Accounting Periods . . . . . . . . Rounding Off to Whole Dollars Recordkeeping . . . . . . . . . . . Depository Method of Tax Payment . . . . . . . . . . . . . . Estimated Tax Payments . . . . Interest and Penalties . . . . . . Other Forms, Returns, and Statements That May Be Required . . . . . . . . . . . . . . Assembling the Return . . . . . Amended Return . . . . . . . . . Passive Activity Limitations . . Extraterritorial Income Exclusion . . . . . . . . . . . . . Specific Instructions . . . . . . . Name . . . . . . . . . . . . . . . . . . Address . . . . . . . . . . . . . . . . Employer Identification Number . . . . . . . . . . . . . . Total Assets . . . . . . . . . . . . . Initial Return, Final Return, Name Change, Address Change, and Amended Return . . . . . . . . . . . . . . . Income . . . . . . . . . . . . . . . . . Deductions . . . . . . . . . . . . . . Tax and Payments . . . . . . . . Schedule A — Cost of Goods Sold . . . . . . . . . . . . . . . . . Schedule B — Other Information . . . . . . . . . . . . General Instructions for Schedules K and K-1 . . . . . . Purpose of Schedules . . . . . . Substitute Forms . . . . . . . . . Shareholder’s Pro Rata Share Items . . . . . . . . . . . . . . . . Page ... 1 ... 1 ... 1 ... 2 Contents Specific Instructions (Schedule K-1 Only) . . . . . . . General Information . . . . . . . . Special Reporting Requirements for Corporations With Multiple Activities . . . . . . . . . . . . . . . Special Reporting Requirements for At-Risk Activities . . . . . . . . . . . . . . . Specific Items . . . . . . . . . . . . . Specific Instructions (Schedules K and K-1, Except as Noted) . . . . . . . . . . Income (Loss) . . . . . . . . . . . . . Deductions . . . . . . . . . . . . . . . Investment Interest . . . . . . . . . Credits . . . . . . . . . . . . . . . . . . Adjustments and Tax Preference Items . . . . . . . . . Foreign Taxes . . . . . . . . . . . . Supplemental Information . . . . Schedule L — Balance Sheets per Books . . . . . . . . . . . . . . . Schedule M-1 — Reconciliation of Income (Loss) per Books With Income (Loss) per Return Schedule M-2 — Analysis of Accumulated Adjustments Account, Other Adjustments Account, and Shareholders’ Undistributed Taxable Income Previously Taxed . . . . . . . . . . Codes for Principal Business Activity . . . . . . . . . . . . . . . . . . Index . . . . . . . . . . . . . . . . . . . . . Page . . . 19 . . . 19
Department of the Treasury Internal Revenue Service
.. . .. ..
..... 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 2 2 2 2 2 3 3 3 3 3 4 4 5 5
expense deduction was passed through to shareholders for the property. • This version (February 2004) of these instructions was issued to reflect changes to the text for Qualified dividends on page 21 that occurred after the original version was sent to print.
. . . 20 . . . 20 . . . 20 . . . . . . . . . . . . . . . 20 20 22 23 23.
. . . 24 . . . 25 . . . 26 . . . 28 . . . 28
Unresolved Tax Issues
If the corporation has attempted to deal with an IRS problem unsuccessfully, it should contact the Taxpayer Advocate. The Taxpayer Advocate independently represents the corporation corporation’s case is given a complete and impartial review. The corporation’s assigned personal advocate will listen to its point of view and will work with the corporation to address its concerns. The corporation can expect the advocate to provide: • A ‘‘fresh look’’ at a new or ongoing problem. • Timely acknowledgment. • The name and phone number of the individual assigned to its case. • Updates on progress. • Timeframes for action. • Speedy resolution. • Courteous service. When contacting the Taxpayer Advocate, the corporation should provide the following information: • The corporation’s name, address, and employer identification number (EIN). • The name and telephone number of an authorized contact person and the hours he or she can be reached. • The type of tax return and year(s) involved.
..... 5 ..... 5 ..... 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 7 8 8
. . . 29 . . . 31 . . . 34
11 12 12 12
. . . . 12 . . . . 12
Changes To Note
Reconciliation Act of 2003, the general tax rates applicable to net capital gains for individuals have been reduced. The new gains rates also apply to qualified dividends under the new section 1(h)(11). The new rates apply to capital gains (including installment payments) occurring on or after May 6, 2003. The tax rates for qualified dividends apply to dividends received after December 31, 2002. Schedules K and K-1 have been redesigned to take into account the shareholders’ shares of these gains and dividends. • The instructions for line 4 of Form 1120S and line 23 of Schedule K-1 have been revised to change how dispositions of property are reported if a section 179
Cat. No. 11515K
• Under the Jobs and Growth Tax Relief
. . . .
. . . .
. . . .
. . . .
12 12 13 17
. . . . 17 . . . . 18 . . . . 19 . . . . 19 . . . . 19 . . . . 19
and the office that had been contacted. • A description of the hardship the corporation is facing (if applicable). The corporation may contact a Taxpayer Advocate by calling a toll-free number, 1-877-777-4778 or by visiting the IRS website at. Persons who have access to TTY/TDD equipment may call 1-800-829-4059 and ask for Taxpayer Advocate assistance. If the corporation prefers, it may call, write, or fax the Taxpayer Advocate office in its area. See Pub. 1546, The Taxpayer Advocate Service of the IRS, for a list of addresses and fax numbers.
• A detailed description of the problem. • Previous attempts to solve the problem
free to buy the CD-ROM for .
General Instructions
Purpose of Form
Form 1120S is used to report the income, deductions, gains, losses, etc., of a domestic corporation that has elected to be an S corporation by filing Form 2553, Election by a Small Business Corporation, and whose election is in effect for the tax year.
Direct Deposit of Refund
To request a direct deposit of the corporation’s income tax refund, attach Form 8050, Direct Deposit of Corporate Tax Refund (see page 17).
Who Must File
A corporation must file Form 1120S if (a) it elected to be an S corporation by filing Form 2553, (b) the IRS accepted the election, and (c) the election remains in effect. Do not file Form 1120S for any tax year before the year the election takes effect. You cannot file Form 1120S unless you have previously filed a properly completed Form 2553. After filing Form 2553 you should have received confirmation that Form 2553 was accepted. If you did not receive notification of acceptance or nonacceptance of the election within 3 months of filing Form 2553 (6 months if you checked box Q1 to request a letter ruling), you should contact the service center where the form was filed to make sure the IRS received the election. If you have not filed Form 2553, or did not file Form 2553 on time, you may be entitled to relief for a late filed election to be an S corporation. See the Instructions for Form 2553 for details.
How To Make a Contribution To Reduce the Public Debt
To make a contribution to reduce the public debt, send a check made payable to the “Bureau of the Public Debt” to Bureau of the Public Debt, Department G, P.O. Box 2188, Parkersburg, WV 26106-2188. Or, enclose a check with Form 1120S. Contributions to reduce the public debt are deductible, subject to the rules and limitations for charitable contributions. instructions for line 22a for details on how to figure the tax. 3. The election is revoked. An election may be revoked only with the consent of shareholders who, at the time the revocation is made, hold more than 50% of the number of issued and outstanding shares of stock (including non-voting stock). The revocation may specify an effective revocation date that is on or after the day the revocation is filed. If no date is specified, the revocation is effective at the start of. To revoke the election, the corporation must file a statement with the service center where it filed its election to be an S corporation. may may request permission from the IRS to continue to be treated as an S corporation. See Regulations section 1.1362-4 for the specific requirements that must be met to qualify for inadvertent termination relief.
Termination of Election. See Regulations section 1.1362-5 for more details. An election terminates automatically in any of the following cases: 1.. 2. The corporation, for each of three consecutive tax years, (a) has accumulated earnings and profits and (b)
Electronic Filing
S corporations will have an option to file Form 1120S and related forms, schedules, and attachments electronically. However, the option to file electronically does not apply to certain returns, including: • Amended returns, • Bankruptcy returns, • Final returns, • Returns with a name change, • Returns with precomputed penalty and interest, • Returns with reasonable cause for failing to file timely, • Returns with reasonable cause for failing to pay timely,
-2-
• Returns with request for overpayment to be applied to another account, • Short-year returns, and • 52 – 53 week tax year returns.
Notes: 1. Visit for details, including a list of forms and schedules not acceptable for electronic filing. Form 1120S cannot be electronically filed if any of those forms and schedules are required to be attached to Form 1120S. 2. Form 7004, Application for Automatic Extension of Time To File Corporation Income Tax Return, cannot be electronically filed.
Air Express Service, Next Afternoon Service, Second Day Service. • DHL Worldwide Express (DHL): DHL ‘‘Same Day’’ Service, DHL USA Overnight. • Federal Express (FedEx): FedEx Priority Overnight, FedEx Standard Overnight, FedEx 2Day, FedEx International Priority, FedEx International First. • United Parcel Service (UPS): UPS Next Day Air, UPS Next Day Air Saver, UPS 2nd Day Air, UPS 2nd Day Air A.M., UPS Worldwide Express Plus, UPS Worldwide Express. The private delivery service can tell you how to get written proof of the mailing date. Extension. Use Form 7004, Application for Automatic Extension of Time To File Corporation Income Tax Return, to request an automatic 6-month extension of time to file. Most private delivery services will not accept your return without a street address in addition to the city, state, and ZIP code. You can get the street address of your service center by calling 1-800-829-4933.
• Airborne Express (Airborne): Overnight
• The corporation has a tax year of less than 12 months that begins and ends in 2004 and • The 2004 Form 1120S is not available by the time the corporation is required to file its return. The corporation must show its 2004 tax year on the 2003 Form 1120S and take into account any tax law changes that are effective for tax years beginning after December 31, 2003.
Who Must Sign
The return must be signed and dated by: • The president, vice president, treasurer, assistant treasurer, chief accounting officer, or • Any other corporate officer (such as tax officer) authorized to sign. Receivers, trustees, or assignees must also sign and date any return filed on behalf of a corporation. If an employee of the corporation completes Form 1120S, the paid preparer’s space should remain blank. In addition, anyone who prepares Form 1120S, but does not charge the corporation,
In general, file Form 1120S by the 15th day of the 3rd month following the date the corporation’s tax year ended as shown at the top of Form 1120S. For calendar year corporations, the due date is March 15, 2004. If the due date falls on a Saturday, Sunday, or legal holiday, file on the next business day. If the S corporation election was terminated during the tax year, file Form 1120S for the S corporation’s short year by the due date (including extensions) of the C corporation’s short year return. Private delivery services. Corporation’s:
Period Covered
File the 2003 return for calendar year 2003 and fiscal years beginning in 2003 and ending in 2004. If the return is for a fiscal year or a short tax year, fill in the tax year space at the top of the form. Note: The 2003 Form 1120S may also be used if:
Paid Preparer Authorization
If the corporation wants to allow the IRS to discuss its 2003’’ its return, • Call the IRS for information about the processing of its return or the status of its refund or payment(s), and • Respond to certain IRS notices that the corporation has shared with the preparer.
Where To File
File your return at the applicable IRS address listed below.
If the corporation’s principal And the total assets at the business, office, or agency end of the tax year (Form is located in: 1120S, page 1, item E) are: Connecticut, Delaware,, Wisconsin Alabama, Alaska, Arizona, Arkansas, A foreign country or U.S. possession Use the following Internal Revenue Service Center address:
Less than $10 million
Cincinnati, OH 45999-0013
$10 million or more
Ogden, UT 84201-0013
Any amount
Ogden, UT 84201-0013
Any amount
Philadelphia, PA 19255-0013
-3-
The authorization cannot be revoked. However, the authorization will automatically end no later than the due date (excluding extensions) for filing the 2004 tax return.
Accounting Methods
An accounting method is a set of rules used to determine when and how income and expenditures are reported. Figure ordinary income using the method of accounting regularly used in keeping the corporation’s books and records. In all cases, the method used must clearly reflect income. Generally, permissible methods include: • Cash, • Accrual, or • Any other method authorized by the Internal Revenue Code. Schedule A. Cost of Goods Sold on page 17. Generally, an S corporation may not use the cash method of accounting if the corporation is a tax shelter (as defined in section 448(d)(3)). See section 448 for details. Accrual method. in which: • All events that determine liability have occurred, • The amount of the liability can be figured with reasonable accuracy, and • Economic performance takes place with respect to the expense. There are exceptions for certain items, including recurring expenses. See section 461(h) and the related regulations for the rules for determining when economic performance takes place. Percentage-of-completion method. Long-term contracts (except for certain real property construction contracts) must generally be accounted for using the percentage of completion method. For rules on long-term contracts, see section 460 and the underlying regulations. Mark-to-market accounting method. Generally, dealers in securities must use the mark-to-market accounting method
described in section 475. Under this method, any security that is inventory to the dealer must be included in inventory at its fair market value (FMV). Any security held by a dealer that is not inventory and that is held at the close of the tax year is treated as sold at its FMV. Dealers in commodities and traders in securities and commodities may elect to use the mark-to-market accounting method. To make the election, the corporation sections 475(e) and (f) and Rev. Proc. 99-17, 1999-7 I.R.B. 52. Change in accounting method. Generally, the corporation must get IRS consent to change its method of accounting used to report taxable income (for income as a whole or for any material item). To do so, it must file Form 3115, Application for Change in Accounting Method. For more information, see Pub. 538, Accounting Periods and Methods. Section 481(a) adjustment., a corporation may elect to use a 1-year adjustment period if the net section 481(a) adjustment for the change is less than $25,000. For more details on the section 481(a) adjustment, see Form 3115 and Pub. 538. Include any net positive section 481(a) adjustment on page 1, line 5. If the net section 481(a) adjustment is negative, report it on page 1, line 19.
A new S corporation must use Form 2553 to adopt a tax year other than a calendar year. To change the corporation’s tax year, see Pub. 538 and Form 1128, Application To Adopt, Change, or Retain a Tax Year, (unless the corporation is making an election under section 444, discussed below). Establish a business purpose. To establish a business purpose for changing or retaining its tax year on Form 1128, the corporation must establish that: • The requested tax year is the corporation’s natural business year or ownership tax year under the automatic approval request provisions of Rev. Proc. 2002-38, 2002-2 I.R.B. 1037, or • There is a business purpose for the requested tax year under the ruling request provisions of Rev. Proc. 2002-39, 2002-2 I.R.B. 1046 (a user fee is required). If the corporation changes its tax year solely because its current tax year no longer qualifies as a natural business year (or, for certain corporations, an ownership tax year), its shareholders may elect to take into account ratably over 4 tax years their pro rata share of income attributable to the corporation’s short tax year ending on or after May 10, 2002, but before June 1, 2004. See Rev. Proc. 2003-79, 2003-45 I.R.B. 1036, for details. If the corporation changes its tax year and the change falls within the scope of Rev. Proc. 2003-79, the corporation must attach a statement to Schedule K-1 that provides shareholders with the information they will need to make this election. Electing a tax year under section 444. Under the provisions of section 444, an S corporation may elect to have a tax year other than a permitted year, but only if the deferral period of the tax year is not longer than the shorter of 3 months or the deferral period of the tax year being changed. This election is made by filing Form 8716, Election To Have a Tax Year Other Than a Required Tax Year. An S corporation may not make or continue an election under section 444 if it is a member of a tiered structure, other than a tiered structure that consists entirely of partnerships and S corporations that have the same tax year. For the S corporation to have a section 444 election in effect, it must make the payments required by section 7519 and file Form 8752, Required Payment or Refund Under Section 7519. A section 444 election ends if an S corporation changes its accounting period to a calendar year or some other permitted year; it is penalized for willfully failing to comply with the requirements of section 7519; or its S election is terminated (unless it immediately becomes a personal service corporation). If the termination results in a short tax year, type or legibly print at the top of the first page of Form 1120S for the short tax year, “SECTION 444 ELECTION TERMINATED.”
Accounting Periods
Generally, an S corporation tax year is required to be: • A calendar year. • A 52-53 week tax year that ends with reference to a calendar year or a tax year elected under section 444. • A tax year elected under section 444. • Any other tax year for which the corporation establishes a business purpose by filing Form 1128.
-4- each shareholder’s return is due or is filed, whichever is later. Keep records that verify the corporation’s basis in property for as long as they are needed to figure the basis of the original or replacement property. The corporation should keep copies of all returns filed. They help in preparing future returns and in making amended returns.
1-800-829-4933. Be sure toS” on the check or money order. Be sure to darken the “1120” box on the coupon. Records of these deposits will be sent to the IRS. If the corporation.
payments, see the instructions for line 24 on page 17. (including extensions) to the date of payment. The interest charge is figured at a rate determined under section 6621. Penalty for late filing of return. A corporation that does not file its tax return by the due date, including extensions, may have to pay a penalty of 5% a month, or part of a month, up to a maximum of 25%, for each month the return is not filed. The penalty is imposed on the net amount due. The minimum penalty for filing a return more than 60 days late is the smaller of the tax due or $100. The penalty will not be imposed if the corporation can show that the failure to file on time was due to reasonable cause. If the failure is due to reasonable cause, attach an explanation to the return. Penalty for late payment of tax. A corporation corporation can show that failure to pay on time was due to reasonable cause. Penalty for failure to furnish information timely. Section 6037(b) requires an S corporation to furnish to each shareholder a copy of the information shown on Schedule K-1 (Form 1120S) that is attached to Form 1120S. Provide Schedule K-1 to each shareholder on or before the day on which the corporation files Form 1120S. For each failure to furnish Schedule K-1 to a shareholder when due and each failure to include on Schedule K-1 all the information required to be shown (or the inclusion of incorrect information), a $50 penalty may be imposed with regard to each Schedule K-1 for which a failure occurs. If the requirement to report correct information is intentionally disregarded, each $50 penalty is increased to $100 or, if greater, 10% of the aggregate amount of items required to be reported. See sections 6722 and 6724 for more information. The penalty will not be imposed if the corporation can show that not furnishing information timely was due to reasonable cause and not due to willful neglect. Trust fund recovery penalty. This penalty may apply if certain excise, income, social security, and Medicare taxes that must be collected or withheld are not collected or withheld, or these taxes are not paid. These taxes are generally reported on Forms 720, 941,
Estimated Tax Payments 2004 by April 15, June 15, September 15, and December 15. For a fiscal year corporation, they are due by the 15th day of the 4th, 6th, 9th, and 12th months of the fiscal year. If any date falls on a Saturday, Sunday, or legal holiday, the installment is due on the next regular business day. The corporation must make the payments using the depository method described above. For more information on estimated tax payments, including penalties that apply if the corporation fails to make required
Depository Method 2004 if: • The total deposits of such taxes in 2002 were more than $200,000 or • The corporation was required to use EFTPS in 2003. or 1-800-945-8400. To enrol online, visit.. If you do not have a preprinted Form 8109, use Form 8109-B to make deposits. You can get this form only by calling
-5-
943, or 945 (see Other Forms, Returns, and Statements That May Be Required below). The trust fund recovery penalty may be imposed on all persons who are determined by the IRS to have been responsible for collecting, accounting for,. Other penalties. Other penalties can be imposed for negligence, substantial understatement of tax, and fraud. See sections 6662 and 6663.
Other Forms, Returns, and Statements That May Be Required
Operations of U.S. Corporations. The corporation may have to file this schedule if it had assets in or operated a business in a foreign country or a U.S. possession. • Forms W-2, Wage and Tax Statement, and W-3 Transmittal of Wage and Tax Statements. Use these forms to report wages, tips, other compensation, and withheld income, social security, and Medicare taxes for employees. • Form 720, Quarterly Federal Excise Tax Return. Use Form 720 to report environmental taxes, communications and air transportation taxes, fuel taxes, manufacturers taxes, ship passenger tax, and certain other excise taxes. • Form 926, Information Return of a U.S. Transferor of Property to a Foreign Corporation. Use this form to report certain information required under section 6038B. • Form 940 or Form 940-EZ, Employer’s Annual Federal Unemployment (FUTA) Tax Return. The corporation may be liable for FUTA tax and may have to file Form 940 or 940-EZ if it either: 1. Paid wages of $1,500 or more in any calendar quarter in 2002 or 2003 or 2. Had one or more employees who worked for the corporation for at least some part of a day in any 20 or more different weeks in 2002 or 20 or more different weeks in 2003. A corporate officer who performs substantial services is considered an employee. Except as provided in section 3306(a), reasonable compensation for these services is subject to FUTA tax, no matter what the corporation calls the payments. • Form 941, Employer’s Quarterly Federal Tax Return or Form 943, Employer’s Annual Tax Return for Agricultural Employees. Employers must file these forms to report income tax withheld, and employer and employee social security and Medicare taxes. Also, see Trust Fund Recovery Penalty on page 5. A corporate officer who performs substantial services is considered an
• Schedule N (Form 1120), Foreign
employee. Distributions and other payments by an S corporation to a corporate officer must be treated as wages to the extent the amounts are reasonable compensation for services to the corporation.. • Forms 1042 and 1042-S, Annual Withholding Tax Return for U.S. Source Income of Foreign Persons; and Foreign Person’s U.S. Source Income Subject to Withholding. Use these forms to report and send withheld tax on payments made to nonresident alien individuals, foreign partnerships, or foreign corporations to the extent those payments constitute gross income from sources within the United States (see sections 861 through 865). For more details, see sections 1441 and 1442, and Pub. 515, Withholding of Tax on Nonresident Aliens and Foreign Entities. • Form 1042-T, Annual Summary and Transmittal of Forms 1042-S. Use Form 1042-T to transmit paper Forms 1042-S to the IRS. • Form 1096, Annual Summary and Transmittal of U.S. Information Returns. • Form 1098, Mortgage Interest Statement. Use this form to report the receipt from any individual of $600 or more of mortgage interest (including points) in the course of the corporation’s trade or business and reimbursements of overpaid interest. • Forms 1099. Use these information returns to report the following. 1. 1099-A, Acquisitions or Abandonment of Secured Property. 2. 1099-B, Proceeds From Broker and Barter Exchange Transactions. 3. 1099-C, Cancellation of Debt. 4. 1099-DIV, Dividends and Distributions, Use Form 1099-DIV to report actual dividends paid by the corporation. Only distributions from accumulated earnings and profits are classified as dividends. Do not issue Form 1099-DIV for dividends received by the corporation that are allocated to shareholders on line 4b of Schedule K-1. 5. 1099-INT, Interest Income. 6. 1099-LTC, Long-Term Care and Accelerated Death Benefits. 7. 1099-MISC, Miscellaneous Income. Use this form to report payments: to certain fishing boat crew members, to providers of health and medical services, of rent or royalties, of nonemployee compensation, etc. Note: Every corporation must file Form 1099-MISC if it makes payments of rents, commissions, or other fixed or determinable income (see section 6041) totaling $600 or more to any one person in the course of its trade or business during the calendar year.
8. 1099-MSA, Distributions From an Archer MSA or Medicare+Choice MSA. 9. 1099-OID, Original Issue Discount. 10. 1099-PATR, Taxable Distributions Received From Cooperatives. 11. 1099-R, Distributions From Pensions, Annuities, Retirement or Profit-Sharing Plans, IRAs, Insurance Contracts, etc. 12. 1099-S, Proceeds From Real Estate Transactions. • Form 3520, Annual Return to Report Transactions With Foreign Trust and Receipt of Certain Foreign Gifts. The corporation may have to file this form if it: 1. Directly or indirectly transferred property or money to a foreign trust. For this purpose, any U.S. person who created a foreign trust is considered a transferor. 2. Is treated as the owner of any part of the assets of a foreign trust under the grantor trust rules. 3. Received a distribution from a foreign trust. For more information, see the Instructions for Form 3520. Note: An owner of a foreign trust must ensure that the trust files an annual information return on Form 3520-A, Annual Information Return of Foreign Trust With a U.S. Owner. • Form 5471, Information Return of U.S. Persons With Respect to Certain Foreign Corporations. This form is required if the corporation). • Form 5498, IRA Contribution Information. Use this form to report contributions (including rollover contributions) to any IRA, including a SEP, SIMPLE, or Roth IRA, and to report Roth IRA conversions, IRA recharacterizations, and the fair market value of the account. • Form 5498-ESA, Coverdell ESA Contribution Information. Use this form to report contributions (including rollover contributions) to and the fair market value of a Coverdell education savings account (ESA). • Form 5498-MSA, Archer MSA or Medicare+Choice MSA Information. Use this form to report contributions to an Archer MSA and the fair market value of an Archer MSA or Medicare+Choice MSA. For more information, see the general and specific Instructions for Forms 1099, 1098, 5498, and W-2G. • Form 5713, International Boycott Report. Corporations that had operations in, or related to, certain “boycotting” countries file Form 5713. • Form 8023, Elections Under Section 338 for Corporations Making Qualified Stock Purchases. Corporations file this form to make elections under section 338
-6-
for a “target” corporation if the purchasing corporation has made a qualified stock purchase of the target corporation. • Form 8050, Direct Deposit of Corporate Tax Refund. File Form 8050 to request that the IRS deposit a corporate tax refund (including a refund of $1 million or more) directly into an account at any U.S. bank or other financial institution (such as a mutual fund or brokerage firm) that accepts direct deposits. • Form 8264, Application for Registration of a Tax Shelter. Tax shelter organizers must use this form to register tax shelters with the IRS receive a tax shelter registration number. • Form 8271, Investor Reporting of Tax Shelter Registration Number. Corporations, which have acquired an interest in a tax shelter that is required to be registered, use this form to report the tax shelter’s registration number. Attach Form 8271 to any return (including an amended return) on which a deduction, credit, loss, or other tax benefit attributable to a tax shelter is taken or any income attributable to a tax shelter is reported. •. • Form 8275-R, Regulation Disclosure Statement, is used to disclose any item on a tax return for which a position has been taken that is contrary to Treasury regulations. • Form 8281, Information Return for Publicly Offered Original Issue Discount Instruments. This form is used by issuers of publicly offered debt instruments having OID to provide the information required by section 1275(c). • Forms 8288 and 8288-A, U.S. Withholding Tax Return for Dispositions by Foreign Persons of U.S. Real Property Interests; and Statement of Withholding on Dispositions by Foreign Persons of U.S. Real Property Interests. Use these forms to report and transmit withheld tax on the sale of U.S. real property by a foreign person. See section 1445 and the related regulations for additional information. • Form 8300, Report of Cash Payments Over $10,000 Received in a Trade or Business. Use this form to report the receipt of more than $10,000 in cash or foreign currency in one transaction or a series of related transactions. • Form 8594, Asset Acquisition Statement Under Section 1060. Corporations file this form to report the purchase or sale of a group of assets that make up a trade or business if goodwill or going concern value could attach to the assets and if the buyer’s basis is
determined only by the amount paid for the assets. • Form 8697, Interest Computation Under the Look-Back Method for Completed Long-Term Contracts. Certain S corporations that are not closely held may have to file Form 8697 to figure the interest due or to be refunded under the look-back method of section 460(b)(2). The look-back method applies to certain long-term contracts accounted for under either the percentage of completion method or the percentage of completion-capitalized cost method. Closely held corporations should see the instructions on page 27 for line 23, item 11, of Schedule K-1 for details on the Form 8697 information they must provide to their shareholders. • Form 8865, Return of U.S. Person With Respect To Certain Foreign Partnerships. A corporation corporation owned, directly or indirectly, at least a 10% interest in the foreign partnership or b. The fair market value of the property the corporation contributed to the foreign partnership, when added to other contributions of property made to the foreign partnership during the preceding 12-month period, exceeds $100,000. Also, the corporation. • Form 8866, Interest Computation Under the Look-Back Method for Property Depreciated Under the Income Forecast Method. Certain S corporations that are not closely held may have to file Form 8866. Figure the interest due or to be refunded under the look-back method of section 167(g)(2) for certain property placed in service after September 13, 1995, that is depreciated under the income forecast method. Closely held corporations should see the instructions on page 28 for line 23, item 21, of Schedule K-1 for details on the Form 8866 information they must provide to their shareholders.
Exclusion. Use this form to report the amount of extraterritorial income excluded from the corporation’s gross income for the tax year. • Form 8876, Excise Tax on Structured Settlement Factoring Transactions. Use Form 8876 to report and pay the 40% excise tax imposed under section 5891. • Form 8883, Asset Allocation Statement Under Section 338. Corporations use this form to report information about transactions involving the deemed sale of assets under section 338. • Form 8886, Reportable Transaction Disclosure Statement. Use the form to disclose information for each reportable transaction in which the corporation participated. Form 8886 must be filed for each tax year the corporation participated in the transaction. The following are reportable transactions. Any transaction: 1. The same as or substantially similar to tax avoidance transactions identified by the IRS. 2. Offered under conditions of confidentiality. 3. For which the corporation has contractual protection against disallowance of the tax benefits. 4. Resulting in a loss of at least $2 million in any single year or $4 million in any combination of years. 5. Resulting in book-tax difference of more than $10 million on a gross basis. 6. Resulting in a tax credit of more than $250,000, if the corporation held the asset generating the credit for 45 days or less.
• Form 8873, Extraterritorial Income
Statements
Stock ownership in foreign corporations. If the corporation owned at least 5% in value of the outstanding stock of a foreign personal holding company, and the corporation was required to include in its gross income any undistributed foreign personal holding company income, attach the statement required by section 551(c). Transfers to a corporation controlled by the transferor. If a person receives stock of a corporation in exchange for property, and no gain or loss is recognized under section 351, the transferor and transferee must each attach to their tax returns the information required by Regulations section 1.351-3.
Assembling the Return
To ensure that the corporation’s tax return is correctly processed, attach all schedules and forms after page 4, Form 1120S, in the following order: 1. Schedule N (Form 1120). 2. Form 8050. 3. Form 4136, Credit for Federal Tax Paid on Fuels. 4. Additional schedules in alphabetical order. 5. Additional forms in numerical order. Complete every applicable entry space on Form 1120S and Schedule K-1. Do not write “See Attached” instead of completing the entry spaces. If more
-7-
space is needed on the forms or schedules, attach separate sheets using the same size and format as the printed forms. If there are supporting statements and attachments, arrange them in the same order as the forms or schedules they support and attach them last. Show the totals on the printed forms. Also, be sure to enter the corporation’s name and EIN on each supporting statement or attachment.
Amended Return
To correct an error on a Form 1120S already filed, file an amended Form 1120S and check box F(5). If the amended return results in a change to income, or a change in the distribution of any income or other information provided any shareholder, an amended Schedule K-1 (Form 1120S) must also be filed with the amended Form 1120S and given to that shareholder. Be sure to check box D(2) on each Schedule K-1 to indicate that it is an amended Schedule K-1. A change to the corporation’s Federal return may affect its state return. This includes changes made as the result of an IRS examination of Form 1120S. For more information, contact the state tax agency for the state in which the corporation’s return was filed.
income and tax from passive activities. Thus, passive losses and credits cannot be applied against income from salaries, wages, professional fees, or a business in which the shareholder materially participates; against “portfolio income” (defined on page 9); or against the tax related to any of these types of income. Special rules require that net income from certain activities that would otherwise be treated as passive income must be recharacterized as nonpassive income for purposes of the passive activity limitations. To allow each shareholder to apply the passive activity limitations at the individual level, the corporation must report income or loss and credits separately for each of the following: trade or business activities, rental real estate activities, rental activities other than rental real estate, and portfolio income.
property that is actively traded, such as stocks, bonds, and other securities. See Temporary Regulations section 1.469-1T(e)(6) for more details. Note: The section 469(c)(3) exception for a working interest in oil and gas properties does not apply to an S corporation because state law generally limits the liability of shareholders. shareholder does not materially participate in the activity, a trade or business activity of the corporation is a passive activity for the shareholder. Each shareholder must determine if they materially participated in an activity. As a result, while the corporation’s overall trade or business income (loss) is reported on page 1 of Form 1120S, the specific income and deductions from each separate trade or business activity must be reported on attachments to Form 1120S. Similarly, while each shareholder’s allocable share of the corporation’s overall trade or business income (loss) is reported on line 1 of Schedule K-1, each shareholder’s allocable share of the income and deductions from each trade or business activity must be reported on attachments to each Schedule K-1. See Passive Activity Reporting Requirements on page 11 for more information.
Activities That Are Not Passive Activities
The following are not passive activities. 1. Trade or business activities in which the shareholder materially participated for the tax year. 2. Any rental real estate activity in which the shareholder materially participated if the shareholder met both of the following conditions for the tax year: a. More than half of the personal services the shareholder performed in trades or businesses were performed in real property trades or businesses in which he or she materially participated, and b. conditions 2a and b above,. 3. The rental of a dwelling unit used by a shareholder for personal purposes during the year for more than the greater of 14 days or 10% of the number of days that the residence was rented at fair rental value. 4. An activity of trading personal property for the account of owners of interests in the activity. For purposes of this rule, personal property means
Passive Activity Limitations
In general, section 469 limits the amount of losses, deductions, and credits that shareholders may upon the nature of the activity that generated it, the corporation must report income or loss and credits separately for each activity. The instructions below (pages 8 through 12) and the instructions for Schedules K and K-1 (pages 19 through 28) in which the shareholder does not materially participate and (b) any rental activity (defined below) even if the shareholder materially participates. For exceptions, see Activities That Are Not Passive Activities below. The level of each shareholder’s participation in an activity must be determined by the shareholder. The passive activity rules provide that losses and credits from passive activities can generally be applied only against
Rental Activities: • The average period of customer use (defined on page 9) for such property is 7 days or less. • The average period of customer use for such property is 30 days or less and significant personal services (defined on page 9) are provided by or on behalf of the corporation. • Extraordinary personal services (defined on page 9) are provided by or on behalf of the corporation. • Rental of the property is treated as incidental to a nonrental activity of the corporation under Temporary Regulations
-8-
section 1.469-1T(e)(3)(vi) and Regulations section 1.469-1(e)(3)(vi). • The corporation customarily makes the property available during defined business hours for nonexclusive use by various customers. • based on all the facts and circumstances. In addition, a guaranteed payment described in section 707(c) is not income from a rental activity under any circumstances. Average period. Personal services include only services performed by individuals. To determine if personal services are significant personal services, consider all of the relevant facts and circumstances. Relevant facts and circumstances include: • How often the services are provided, • The type and amount of labor required to perform the services, and • The value of the services in relation to the amount charged for the use of the property. The following services are not considered in determining whether personal services are significant: • Services necessary to permit the lawful use of the rental property. • Services performed in connection with improvements or repairs to the rental property that extend the useful life of the property substantially beyond the average rental period. • that the patient receives from the hospital’s medical staff. Similarly, a student’s use of a dormitory room in a boarding school is incidental to the personal services provided by the school’s teaching staff. Rental property: • The main purpose for holding the property is to realize a gain from the appreciation of the property. • The gross rental income from such property for the tax year is less than 2% of the smaller of the property’s unadjusted basis or its fair market value. Rental of property is incidental to a trade or business activity if all of the following apply: • The corporation owns an interest in the trade or business at all times during the year. • The rental property was mainly used in the trade or business activity during the tax year or during at least 2 of the 5 preceding tax years. • The gross rental income from the property is less than 2% of the smaller of the property’s unadjusted basis or its fair market value. The sale or exchange of property that is also rented during the tax year (where the gain or loss is recognized) is treated as incidental to the activity of dealing in property if, at the time of the sale or exchange, the property was held primarily for sale to customers in the ordinary course of the corporation’s trade or business. See Temporary Regulations section 1.469-1T(e)(3) and Regulations section 1.469-1(e)(3) for more information on the definition of rental activities for purposes of the passive activity limitations. Reporting of rental activities. In reporting the corporation’s income or losses and credits from rental activities, the corporation must separately report (a) rental real estate activities and (b) rental activities other than rental real estate activities. Shareholders who actively participate in a rental real estate activity may be able to deduct part or all of their rental real estate losses (and the deduction equivalent of rental real estate credits) against income (or tax) from nonpassive activities. Generally, the combined amount of rental real estate losses and the deduction equivalent of rental real estate credits from all sources (including rental real estate activities not held through the corporation) that may be claimed is limited to $25,000. Report rental real estate activity income (loss) on Form 8825, Rental Real
Estate Income and Expenses of a Partnership or an S Corporation, and on line 2 of Schedules K and K-1, rather than on page 1 of Form 1120S. Report credits related to rental real estate activities on lines 12c and 12d and low-income housing credits on line 12b of Schedules K and K-1. Report income (loss) from rental activities other than rental real estate on line 3 and credits related to rental activities other than rental real estate on line 12e of Schedules K and K-1.
Portfolio Income
Generally, portfolio income includes all gross income, other than income derived in the ordinary course of a trade or business, that is attributable to interest; dividends; royalties; income from a real estate investment trust, a regulated investment company, a real estate mortgage investment conduit, a common trust fund, a controlled foreign corporation, a qualified electing fund, or a cooperative; income from the disposition of property that produces income of a type defined as portfolio income; and income from the disposition of property held for investment. See Self-Charged Interest on page 10 for an exception. Solely for purposes of the preceding paragraph, gross income derived in the ordinary course of a trade or business includes (and portfolio income, therefore, does not include) only the following types of income: • Interest income on loans and investments made in the ordinary course of a trade or business of lending money. • Interest on accounts receivable arising from the performance of services or the sale of property in the ordinary course of a trade or business of performing such services or selling such property, but only if credit is customarily offered to customers of the business. • Income from investments made in the ordinary course of a trade or business of furnishing insurance or annuity contracts or reinsuring risks underwritten by insurance companies. • Income or gain derived in the ordinary course of an activity of trading or dealing in any property if such activity constitutes a trade or business (unless the dealer held the property for investment at any time before such income or gain is recognized). • Royalties derived by the taxpayer in the ordinary course of a trade or business of licensing intangible property. • Amounts included in the gross income of a patron of a cooperative by reason of any payment or allocation to the patron based on patronage occurring with respect to a trade or business of the patron. • Other income identified by the IRS as income derived by the taxpayer in the ordinary course of a trade or business. See Temporary Regulations section 1.469-2T(c)(3) for more information on portfolio income.
-9-
Report portfolio income on line 4 of Schedules K and K-1, rather than on page 1 of Form 1120S. Report deductions related to portfolio income on line 9 of Schedules K and K-1.
• Four separate activities.
Once the corporation chooses a grouping under these rules, it must continue using that grouping in later tax years unless a material change in the facts and circumstances makes it clearly inappropriate. The IRS may regroup the corporation’s activities if the corporation’s grouping fails to reflect one or more appropriate economic units and one of the primary purposes real property or vice versa). 3. Any activity with another activity in a different type of business and in which the corporation holds. Activities conducted through partnerships. Once a partnership determines its activities under these rules, the corporation as a partner may use these rules to group those activities with: • Each other, • Activities conducted directly by the corporation, or • Activities conducted through other partnerships. The corporation may not treat as separate activities those activities grouped together by the partnership.
Income from the following six sources is subject to recharacterization. Note: Any net passive income recharacterized as nonpassive income is treated as investment income for purposes of figuring investment interest expense limitations if it is from (a) an activity of renting substantially nondepreciable property from an equity-financed lending activity or (b) an activity related to an interest in a pass-through entity that licenses intangible property. 1. Significant participation passive activities. A significant participation passive activity is any trade or business activity in which the shareholder both participated for more than 100 hours during the tax year but did not materially participate. Because each shareholder must determine his or her level of participation, the corporation corporation has net income from a passive equity-financed lending activity, the smaller of the net passive income. 4. Rental activities: • The corporation recognizes gain from the sale, exchange, or other disposition of the rental property during the tax year. •
Self-Charged Interest
Certain self-charged interest income and deductions may be treated as passive activity gross income and passive activity deductions if the loan proceeds are used in a passive activity. Generally, self-charged interest income and deductions result from loans to and from the corporation and its shareholders. It also includes loans between the corporation and another S corporation or partnership if each owner in the borrowing entity has the same proportional ownership interest in the lending entity. The self-charge interest rules do not apply to a shareholder’s interest in an S corporation if the S corporation makes an election under Regulations section 1.467 may only be revoked with the consent of the IRS. For more details on the self-charge interest rules, see Regulations section 1.469-7.
Grouping of Activities
Generally, one or more trade or business activities or rental activities may be treated as a single activity if the activities make up an appropriate economic unit corporation has a significant ownership interest in a bakery and a movie theater in Baltimore and in a bakery and a movie theater in Philadelphia. Depending on the relevant facts and circumstances, there may be more than one reasonable method for grouping the corporation’s activities. For instance, the following groupings may or may not be permissible: • A single activity, • A movie theater activity and a bakery activity, • A Baltimore activity and a Philadelphia activity, or
Recharacterization of Passive Income
Under Temporary Regulations section 1.469-2T(f) and Regulations section 1.469-2(f), net passive income from certain passive activities must be treated as nonpassive income. Net passive income is the excess of an activity’s passive activity gross income over its passive activity deductions (current year deductions and prior year unallowed losses).
-10-
significant value-enhancing services remain to be performed. • The shareholder materially participated or significantly participated for any tax year in an activity that involved the performing of. 5. Activities involving property rented to a nonpassive activity. If a taxpayer rents property to a trade or business activity in which the taxpayer materially participates, the taxpayer’s net rental activity income (defined in item 4) from the property is nonpassive income. 6. Acquisition of an interest in a pass-through entity that licenses intangible property. Generally, net royalty income from intangible property is nonpassive income if the taxpayer acquired an interest in the pass-through entity after it created the intangible property or performed substantial services or incurred substantial costs in developing or marketing the intangible property. Net royalty income is the excess of passive activity gross income from licensing or transferring any right in intangible property over passive activity deductions (current year deductions and prior year unallowed losses) that are reasonably allocable to the intangible property. See Temporary Regulations section 1.469-2T(f)(7)(iii) for exceptions to this rule.
Passive Activity Reporting Requirements
To allow shareholders to correctly apply the passive activity loss and credit limitation rules, any corporation that carries on more than one activity must: 1. Provide an attachment for each activity conducted through the corporation. 3.. 4. Identify the net income (loss) and the shareholder’s share of interest expense from each activity of trading personal property conducted through the corporation.). 6. Identify the shareholder’s share of the corporation’s self-charged interest income or expense (see Self-Charged Interest on page 10). a.. b.. 7. Specify the amount of gross portfolio income, the interest expense properly allocable to portfolio income, and expenses other than interest expense that are clearly and directly allocable to portfolio income. 8. Identify the ratable portion of any section 481 adjustment (whether a net positive or a net negative adjustment) allocable to each corporate activity.
9. Identify any gross income from sources specifically excluded from passive activity gross income, including: a. Income from intangible property, if the shareholder is an individual whose personal efforts significantly contributed to the creation of the property; b. Income from state, local, or foreign income tax refunds; and c. Income from a covenant not to compete, if the shareholder is an individual who contributed the covenant to the corporation. 10. Identify any deductions that are not passive activity deductions. 11.). 12. Identify the following items developed (by the shareholder or the corporation), rented, and sold within 12 months after the rental of the property commenced; d. Net rental activity income from the rental of property by the corporation to a trade or business activity in which the shareholder had an interest (either directly or indirectly); and e. Net royalty income from intangible property if the shareholder acquired the shareholder’s interest in the corporation after the corporation created the intangible property or performed substantial services or incurred substantial costs in developing or marketing the intangible property. 13. Identify separately the credits from each activity conducted by or through the corporation.
Extraterritorial Income Exclusion
The corporation may exclude extraterritorial income to the extent of qualifying foreign trade income. For details and to figure the amount of the exclusion, see Form 8873 and its separate instructions. The corporation must report the extraterritorial income exclusion on its return as follows: 1. If the corporation met the foreign economic process requirements
-11-
explained in the Instructions for Form 8873, it may report the exclusion as a non-separately stated item on whichever of the following lines apply to that activity: • Form 1120S, page 1, line 19; • Form 8825, line 15; or • Form 1120S, Schedule K, line 3b. In addition, the corporation must report as an item of information on Schedule K-1, line 23, the shareholder’s pro rata share of foreign trading gross receipts from Form 8873, line 15. 2. If the foreign trading gross receipts of the corporation for the tax year are $5 million or less and the corporation did not meet the foreign economic process requirements, it may not report the extraterritorial income exclusion as a non-separately stated item on its return. Instead, it must report the following separately-stated items to the shareholders on Schedule K-1, line 23:
• By mailing or faxing Form SS-4,
Application for Employer Identification Number. If the corporation has not received its EIN by the time the return is due, write “Applied for” in the space for the EIN. For more details, see Pub. 583, Starting a Business and Keeping Records. Please call the toll-free Business and Specialty Tax Line at 1-800-829-4933 for assistance in applying for an EIN.
Item E. Total Assets
Enter the corporation’s total assets at the end of the tax year, as determined by the accounting method regularly used in maintaining the corporation’s books and records. If there were no assets at the end of the tax year, enter “0”. If the S election terminated during the tax year, see the instructions for Schedule L on page 28 for special rules that may apply when figuring the corporation’s year-end assets.
property or engages in an activity that produces exempt income, reports this income on line 18 of Schedules K and K-1. Report tax-exempt interest income, including exempt-interest dividends received as a shareholder in a mutual fund or other regulated investment company, on line 17 of Schedules K and K-1. See Deductions beginning on page 13 for information on how to report expenses related to tax-exempt income. Cancelled debt exclusion. If the S corporation has had debt discharged resulting from a title 11 bankruptcy proceeding, or while insolvent, see Form 982, Reduction of Tax Attributes Due to Discharge of Indebtedness, and Pub. 908, Bankruptcy Tax Guide.
• The shareholder’s pro rata share of
Line 1. Gross Receipts or Sales
Enter gross receipts or sales from all trade or business operations except those that must be reported on lines 4 and 5. In general, advance payments are reported in the year of receipt. To report income from long-term contracts, see section 460. For special rules for reporting certain advance payments for goods and long-term contracts, see Regulations section 1.451-5. For permissible methods for reporting certain advance payments for services by an accrual method corporation, see Rev. Proc. 71-21,1971-2 C.B. 549. Installment sales.. Exception. These restrictions on using the installment method do not apply to dispositions of property used or produced in a farming business or sales of timeshares and residential lots for which the corporation elects to pay interest under section 453(l)(3). Enter on line 1a: • Gross sales. • Cost of goods sold. • Gross profits. • Percentage of gross profits to gross sales. • Amount collected. • Gross profit on the amount collected.
foreign trading gross receipts from Form 8873, line 15. • The shareholder’s pro rata share of the extraterritorial income exclusion from Form 8873, line 52, and identify the activity to which the exclusion relates. Note: Upon request of a shareholder, the corporation should furnish a copy of the corporation’s Form 8873 if that shareholder has a reduction for international boycott operations, illegal bribes, kickbacks, etc.
Item F. Initial Return, Final Return, Name Change, Address Change, and Amended Return
• If this is the corporation’s first return,
check the “Initial return” box. file Form 1120S and check the “Final return” box. Also check box D(1) on each Schedule K-1 to indicate that it is a final Schedule K-1. • If the corporation changed its name since it last filed a return, check the box for “Name change.” Generally, a corporation must also have amended its articles of incorporation and filed the amendment with the state in which it is incorporated. • If the corporation has changed its address since it last filed a return, check the box for “Address change.” Note: If a change in address occurs after the return is filed, use Form 8822, Change of Address, to notify the IRS of the new address. • If this amends a previously filed return, check the box for “Amended return.” If Schedules K-1 are also being amended, check box D(2) on each Schedule K-1.
• If the corporation has ceased to exist,
Specific Instructions
Name
If the corporation did not receive a label, print or type the corporation’s true name (as set forth in the corporate charter or other legal document creating it).
Address
Include the suite, room, or other unit number after the street address. If a preaddressed label is used, include the information on the label. If the Post Office does not deliver to the street address and the corporation has a P.O. box, show the box number instead of the street address.
Item B. Business Code No.
See the Codes for Principal Business Activity on pages 31 through 33 of these instructions.
Income
Report only trade or business activity income or loss on lines 1a CAUTION through 6. Do not report rental activity income or portfolio income or loss on these lines. (See Passive Activity Limitations beginning on page 8 for definitions of rental income and portfolio income.) Rental activity income and portfolio income are reported on Schedules K and K-1 (rental real estate activities are also reported on Form 8825). Tax-exempt income. Do not include any tax-exempt income on lines 1 through 5. A corporation that receives any exempt income other than interest, or holds any
!
Itemam to 5:30pm in the corporation’s local time zone.
-12-
Line 2. Cost of Goods Sold
See the instructions for Schedule A on page 17.
Line 4. Net Gain (Loss) From Form 4797
Include only ordinary gains or losses from the sale, exchange, or CAUTION involuntary conversion of assets used in a trade or business activity. Ordinary gains or losses from the sale, exchange, or involuntary conversions of assets used in rental activities are reported separately on Schedule K as part of the net income (loss) from the rental activity in which the property was used. A corporation that is a partner in a partnership must include on Form 4797, Sales of Business Property, its share of ordinary gains (losses) from sales, exchanges, or involuntary or compulsory conversions (other than casualties or thefts) of the partnership’s trade or business assets. If the corporation sold or otherwise disposed of business property for which the corporation passed through a section 179 expense deduction to its shareholders, the disposition must be reported separately on line 23 of Schedule K-1 instead of being reported on Form 4797.
!
separate schedule need not be attached to the return in this case. Do not net any expense item (such as interest) with a similar income item. Report all trade or business expenses on lines 7 through 19. Do not include items requiring separate computations by shareholders that must be reported on Schedules K and K-1. See the instructions for Schedules K and K-1 beginning on page 19.
nondeductible expenses on line 19 of Schedules K and K-1. If an expense is connected with both taxable income and nontaxable income, allocate a reasonable part of the expense to each kind of income.
Limitations on Deductions
Section 263A uniform capitalization rules. The uniform capitalization rules of section 263A require corporations to capitalize or include in inventory costs certain costs incurred in connection with: • The production of real. The costs required to be capitalized under section 263A are not deductible until the property to which the costs relate is sold, used, or otherwise disposed of by the corporation. Exceptions. Section 263A does not apply to: • Personal property acquired for resale if the taxpayer’s average annual gross receipts for the 3 prior tax years are $10 million or less. • Timber. • Most property produced under a long-term contract. • Certain property produced in a farming business. See Special rules for certain corporations engaged in farming on page 14. The corporation must report the following costs separately to the shareholders for purposes of determinations under section 59(e): • Research and experimental costs under section 174. • Intangible drilling costs for oil, gas, and geothermal property. • Mining exploration and development costs. • Inventoriable items accounted for in the same manner as materials and supplies that are not incidental. See Schedule A. Cost of Goods Sold on page 17 for details. Tangible personal property produced by a corporation includes a film, sound recording, video tape, book, or similar property. Indirect costs. Corporations subject to the rules are required to capitalize not only direct costs but an allocable portion of most indirect costs (including taxes) that benefit the assets produced or acquired for resale or are incurred by reason of the performance of production or resale activities. For inventory, some of the indirect costs that must be capitalized are: • Administration expenses. • Taxes. • Depreciation. • Insurance.
Ordinary Income (Loss) From a Partnership, Estate, or Trust
Enter the ordinary trade or business income (loss) from a partnership shown on Schedule K-1 (Form 1065), from an estate or trust shown on Schedule K-1 (Form 1041), or from a foreign partnership, estate, or trust. Show the partnership’s, estate’s, or trust’s name, address, and EIN (if any) on a separate statement attached to this return. If the amount entered is from more than one source, identify the amount from each source. Do not include portfolio income or rental activity income (loss) from a partnership, estate, or trust on this line. Instead, report these amounts on the applicable lines 6 of Schedules K and K-1. Treat shares of other items separately reported on Schedule K-1 issued by the other entity as if the items were realized or incurred by the.
Line 5. Other Income (Loss)
Enter on line 5 trade or business income (loss) that is not included on lines 1a through 4. List the type and amount of income on an attached schedule. If the corporation has only one item of other income, describe it in parentheses on line 5. Examples of other income include: • Interest income derived in the ordinary course of the corporation’s trade or business, such as interest charged on receivable balances. • Recoveries of bad debts deducted in prior years under the specific charge-off method. • Taxable income from insurance proceeds. • The amount of credit figured on Form 6478, Credit for Alcohol Used as Fuel. The corporation must also include in other income the: • Recapture amount under section 280F if the business use of listed property drops to 50% or less. To figure the recapture amount, the corporation must complete Part IV of Form 4797. • Recapture of any deduction previously taken under section 179A. The S corporation may have to recapture part or all of the benefit of any allowable deduction for qualified clean-fuel vehicle property (or clean-fuel vehicle refueling property), if the property ceases to qualify for the deduction within 3 years after the date it was placed in service. See Pub. 535, Business Expenses, for details on how to figure the recapture. If “other income” consists of only one item, identify it by showing the account caption in parentheses on line 5. A
Deductions
CAUTION
!
Report only trade or business activity expenses on lines 7 through 19.
Do not report rental activity expenses or deductions allocable to portfolio income on these lines. Rental activity expenses are separately reported on Form 8825 or line 3 of Schedules K and K-1. Deductions allocable to portfolio income are separately reported on line 9 of Schedules K and K-1. See Passive Activity Limitations beginning on page 8 for more information on rental activities and portfolio income. Do not report any nondeductible amounts (such as expenses connected with the production of tax-exempt income) on lines 7 through 19. Instead, report
-13-
attributable to services. deducted. Interest expense. Special rules for certain corporations engaged in farming. For S corporations not required to use the accrual method of accounting, the rules of section 263A do not apply to expenses of raising any: • Animal or • Plant that has a preproductive period of 2 years or less. Shareholders of S corporations not required to use the accrual method of accounting may elect to currently deduct the preproductive period expenses of certain plants that have a preproductive period of more than 2 years. Because each shareholder makes the election to deduct these expenses, the corporation should not capitalize them. Instead, the corporation should report the expenses separately on line 21 of Schedule K and each shareholder’s pro rata share on line 23 of Schedule K-1. See sections 263A(d) and (e) and Regulations section 1.263A-4 for definitions and other details. Transactions between related taxpayers. Generally, an accrual basis S corporation may deduct business expenses and interest owed to a related party (including any shareholder) only in the tax year of the corporation that includes the day on which the payment is includible in the income of the related party. See section 267 for details. Section 291 limitations. If the S corporation was a C corporation for any of the 3 immediately preceding years, the corporation may be required to adjust deductions allowed to the corporation for depletion of iron ore and coal, and the amortizable basis of pollution control facilities. See section 291 to determine the amount of the adjustment. Business start-up expenses. Business start-up expenses must be capitalized. An election may be made to amortize them over a period of not less than 60 months. See section 195 and Regulations section 1.195-1. Reducing certain expenses for which credits are allowable. For each credit listed below, the corporation must reduce the otherwise allowable deductions for expenses used to figure the credit by the amount of the current year credit.
• Compensation paid to officers
• The work opportunity credit, • The welfare-to-work credit, • The credit for increasing research • The enhanced oil recovery credit, • The disabled access credit, • The empowerment zone and renewal
activities,
community employment credit, • The Indian employment credit, • The credit for employer social security and Medicare taxes paid on certain employee tips, • The orphan drug credit, and • The New York Liberty Zone business employee credit. If the corporation has any of these credits, be sure to figure each current year credit before figuring the deductions for expenses on which the credit is based.
Report amounts paid for health insurance coverage for a more than 2% shareholder (including that shareholder’s spouse and dependents) as an information item in box 14 of that shareholder’s Form W-2. For 2003, a more-than-2% shareholder may be allowed to deduct up to 100% of such amounts on Form 1040, line 29.).
Line 7. Compensation of Officers and Line 8—Salaries and Wages
Distributions and other payments by an S corporation to a corporate CAUTION officer must be treated as wages to the extent the amounts are reasonable compensation for services to the corporation. Enter on line 7 the total compensation of all officers paid or incurred in the trade or business activities of the corporation. Enter on line 8 the amount of salaries and wages paid or incurred to employees (other than officers) during the tax year in the trade or business activities of the corporation. Do not include amounts reported elsewhere on the return, such as salaries and wages included in cost of goods sold, elective contributions to a section 401(k) cash or deferred arrangement, or amounts contributed under a salary reduction SEP agreement or a SIMPLE IRA plan. Reduce the amounts on lines 7 and 8 by any applicable employment credits from: • Form 5884, Work Opportunity Credit, • Form 8861, Welfare-to-Work Credit, • Form 8844, Empowerment Zone and Renewable Community Employment Credit, • Form 8845, Indian Employment Credit, and • Form 8884, New York Liberty Zone Business Employee Credit. See the instructions for these forms for more, page 1, of Form 1120S. See the instructions for that line for information on the types of expenditures that are treated as fringe benefits and for the stock ownership rules.
Line 9. Repairs and Maintenance
Enter the costs of incidental repairs and maintenance, such as labor and 10. Bad Debts
Enter the total debts that became worthless in whole or in part during the year, but only to the extent such debts relate to a trade or business activity. Report deductible nonbusiness bad debts as a short-term capital loss on Schedule D (Form 1120S). Cash method taxpayers may not claim a bad debt deduction unless CAUTION the amount was previously included in income.
!
Line 11. Rents
If the corporation rented or leased a vehicle, enter the total annual rent or lease expense paid or incurred in the trade or business activities of the corporation.:
The lease term began: After 12/31/02 and before 1/1/04 After 12/31/98 and before 1/1/03 After 12/31/96 but before 1/1/99 After 12/31/94 but before 1/1/97 After 12/31/93 but before 1/1/95 $18,000 $15,500 $15,800 $15,500 $14,600
If the lease term began before January 1, 1994, see Pub. 463, Travel, Entertainment, Gift, and Car Expenses, to find out if the corporation has an inclusion amount and how to figure it.
-14-
Line 12. Taxes and Licenses
Enter taxes and licenses paid or incurred in the trade or business activities of the corporation, if not reflected in cost of goods sold. Federal import duties and Federal excise and stamp taxes are deductible only if paid or incurred in carrying on the trade or business of the corporation. Do not deduct the following taxes on line 12: • Federal income taxes (except for the portion of built-in gains tax allocable to ordinary income), or taxes reported elsewhere on the return. • Section 901 foreign taxes. Report these taxes separately on line 15g, Schedule K. • Taxes allocable to a rental activity. Taxes allocable to a rental real estate activity are reported on Form 8825. Taxes allocable to a rental activity other than a rental real estate activity are reported on line 3b of Schedule K. • Taxes allocable to portfolio income. Report these taxes separately on line 9 of Schedules K and K-1. • Taxes paid or incurred for the production or collection of income, or for the management, conservation, or maintenance of property held to produce income. Report these taxes separately on line 10 of Schedules K and K-1. See section 263A(a) for information on capitalization of allocable costs (including taxes) for any property. apportionment of taxes on real property between seller and purchaser.
• Taxes not imposed on the corporation. • Taxes, including state or local sales
Line 13. Interest
Include on line 13 only interest incurred in the trade or business activities of the corporation that is not claimed elsewhere on the return. Do not include interest expense: •.
portfolio or investment income. This interest expense is reported separately on line 11a of Schedule K. • On debt proceeds allocated to distributions made to shareholders during the tax year. Instead, report such interest on line 10 of Schedules K and K-1. To determine the amount to allocate to distributions to shareholders, see Notice 89-35, 1989-1 C.B. 675. • On debt required to be allocated to the production of designated property. Interest allocable to designated property produced by an S corporation for its own use or for sale must instead be capitalized. The corporation must also capitalize any interest on debt allocable to an asset used to produce designated property. A shareholder may have to capitalize interest that the shareholder incurs during the tax year for the production expenditures of the S corporation. Similarly, interest incurred by an S corporation may have to be capitalized by a shareholder for the shareholder’s own production expenditures. The information required by the shareholder to properly capitalize interest for this purpose must be provided by the corporation on an attachment for line 23 of Schedule K-1. See section 263A(f) and Regulations sections 1.263A-8 through 1.263A-15 for additional information, including the definition of “designated property.” Special rules apply to: •. • Prepaid interest, which generally can only be deducted over the period to which the prepayment applies. See section 461(g) for details. • Limit the interest deduction if the corporation is a policyholder or beneficiary with respect to a life insurance, endowment, or annuity contract issued after June 8, 1997. For details, see section 264(f). Attach a statement showing the computation of the deduction.
• Clearly and directly allocable to
to the shareholders on line 8 of Schedule K-1.
Line 15. Depletion
If the corporation claims a deduction for timber depletion, complete and attach Form T, Forest Activities Schedule. Do not deduct depletion for oil and gas properties. Each shareholder CAUTION figures depletion on these properties under section 613A(c)(11). See the instructions on page 26 for Schedule K-1, line 23, item 2, for information on oil and gas depletion that must be supplied to the shareholders by the corporation.
!
Line 17. Pension, Profit-Sharing, etc., Plans
Enter the deductible contributions not claimed elsewhere on the return made by the corporation for its employees under a qualified pension, profit-sharing, annuity, or simplified employee pension (SEP) or SIMPLE plan, and under qualified under the Internal Revenue Code and whether or not a deduction is claimed for the current tax year, generally must file the applicable form listed below. • Form 5500, Annual Return/Report of Employee Benefit Plan. File this form for a plan that is not a one-participant plan (see below). •. There are penalties for failure to file these forms on time and for overstating the pension plan deduction.
Line 18. Employee Benefit Programs paid on behalf of more than 2% shareholders on line 7 or 8, whichever applies. A shareholder is considered to own more than 2% of the corporation’s stock if that person owns on any day during the tax year more than 2% of the outstanding stock of the corporation
Line 14. Depreciation
Enter on line 14a only the depreciation claimed on assets used in a trade or business activity. deductible by the corporation. Instead, it is passed through
-15-
or stock possessing more than 2% of the combined voting power of all stock of the corporation. See section 318 for attribution rules.
Line 19. Other Deductions
Enter the total of all allowable trade or business deductions that are not deductible elsewhere on page 1 of Form 1120S. Attach a schedule listing by type and amount each deduction included on this line. Examples of other deductions include: • Amortization (except as noted below) — see the Instructions for Form 4562 for more information. Complete and attach Form 4562 if the corporation is claiming amortization of costs that began during the tax year. • Insurance premiums. • Legal and professional fees. • Supplies used and consumed in the business. • Utilities. Also, see Special Rules below for limits on certain other deductions. Do not deduct on line 19: • Items that must be reported separately on Schedules K and K-1. • Qualified expenditures to which an election under section 59(e) may apply. See the instructions on page 26 for lines 16a and 16b of Schedule K-1 for details on treatment of these items. • Amortization of reforestation expenditures under section 194. The corporation can elect to amortize up to $10,000 of qualified reforestation expenditures paid or incurred during the tax year. However, the amortization is not deducted by the corporation but the amortizable basis is instead separately allocated among the shareholders. See the instructions on page 28 for Schedule K-1, line 23, item 22 and Pub. 535 for more details. • Fines or penalties paid to a government for violating any law. Report these expenses on Schedule K, line 19. • Expenses allocable to tax-exempt income. Report these expenses on Schedule K, line 19. • Net operating losses as provided by section 172 or the special deductions in sections 241 through 249 (except the
election to amortize organizational expenditures under section 248). These deductions cannot be claimed by an S corporation. Note: Shareholders are allowed, subject to limitations, to deduct from gross income the corporation’s net operating loss. See section 1366.
convention expenses, and entertainment tickets. See section 274 and Pub. 463 for more details. Travel. The corporation cannot can.
Special Rules
Commercial revitalization deduction. If the corporation constructs, purchases, or substantially rehabilitates a qualified building in a renewal community, it may qualify for a deduction of either (a) 50% of qualified capital expenditures in the year the building is placed in service or (b) amortization of 100% of the qualified capital expenditures over a 120-month period beginning with the month the building is placed in service. If the corporation elects to amortize these expenditures, complete and attach Form 4562. To qualify, the building must be nonresidential (as defined in section 168(e)(2)) and placed in service by the corporation. The corporation must be the original user of the building unless it is substantially rehabilitated. The amount of the qualified expenditures cannot exceed the lesser of $10 million or the amount allocated to the building by the commercial revitalization agency of the state in which the building is located. Any remaining expenditures are depreciated over the regular depreciation recovery period. See Pub. 954, Tax Incentives for Distressed Communities, and section 1400I for details. Rental real estate. The corporation cannot deduct commercial revitalization expenditures for a building placed in service as rental real estate. Instead, the commercial revitalization deduction for rental real estate is reported separately to shareholders; see line 23, item 25, of Schedule K-1. Travel, meals, and entertainment. Subject to limitations and restrictions discussed below, a corporation can deduct ordinary and necessary travel, meals, and entertainment expenses paid or incurred in its trade or business. Also, special rules apply to deductions for gifts, skybox rentals, luxury water travel,
Worksheet for Line 22a.
-16-. Lobbying expenses. Do not deduct amounts paid or incurred to participate or intervene in any political campaign on behalf of a candidate for public office, or to influence the general public regarding legislative matters, elections, or referendums. In addition, corporations generally cannot deduct expenses paid or incurred to influence Federal or state legislation, or to influence the actions or positions of certain Federal executive branch officials. However, certain in-house lobbying expenditures that do not exceed $2,000 are deductible. See section 162(e) for more details. Clean-fuel vehicles and certain refueling property. A deduction is allowed for part of the cost of qualified clean-fuel vehicle property and qualified clean-fuel vehicle refueling property placed in service during the tax year. For more details, see section 179A and Pub. 535. Certain corporations engaged in farming. Section 464(f) limits the deduction for certain expenditures of S corporations engaged in farming that use the cash method of accounting, and whose prepaid farm supplies are more than 50% of other deductible farming expenses. Prepaid farm supplies include expenses for feed, seed, fertilizer, and similar farm supplies not used or consumed during the year. They also include the cost of poultry that would be allowable as a deduction in a later tax year if the corporation were to (a) capitalize the cost of poultry bought for use in its farm business and deduct it ratably over the lesser of 12 months or the useful life of the poultry and (b) deduct the cost of poultry bought for resale in the year it sells or otherwise disposes of it. If the limit applies, the corporation can deduct prepaid farm supplies that do not exceed 50% of its other deductible farm expenses in the year of payment. The excess is deductible only in the year the corporation uses or consumes the supplies (other than poultry, which is deductible as explained above). For exceptions and more details on these rules, see Pub. 225, Farmer’s Tax Guide.
Tax and Payments
Line 22a. Excess Net Passive Income Tax
If the corporation has always been an S corporation, the excess net passive income tax does not apply. If the corporation has accumulated earnings and profits (E&P) at the close of its tax year, has passive investment income for the tax year that is in excess of 25% of gross receipts, and has taxable income at year-end, the corporation must pay a tax on the excess net passive income. Complete lines 1 through 3 and line 9 of the worksheet on page 16 to make this determination. If line 2 is greater than line 3 and the corporation has taxable income (see instructions for line 9 of worksheet), it must pay the tax. Complete a separate schedule using the format of lines 1 through 11 of the worksheet on page 16 to figure the tax. Enter the tax on line 22a, page 1, Form 1120S, and attach the computation schedule to Form 1120S. Reduce each item of passive income passed through to shareholders by its portion of tax on line 22a. See section 1366(f)(3).
corporation’s last tax year as a C corporation or for the tax year of the transfer, whichever applies. The S corporation must pay each of the remaining installments by the due date (not including extensions) of Form 1120S for the 3 succeeding tax years. Include this year’s installment in the total amount to be entered on line 22c. To the left of the total on line 22c, enter the installment amount and “LIFO tax.” Interest due under the look-back method for completed long-term contracts. If the corporation owes interest, attach Form 8697, Interest Computation Under the Look-Back Method for Completed Long-Term Contracts. To the left of the total on line 22c, enter the amount owed and “From Form 8697.” Interest due under the look-back method for property depreciated under the income forecast method. If the corporation owes interest, attach Form 8866, Interest Computation Under the Look-Back Method for Property Depreciated Under the Income Forecast Method. To the left of the total on line 22c, enter the amount owed and “From Form 8866.”
Line 22b. Tax From Schedule D (Form 1120S)
Enter the built-in gains tax from line 22 of Part III of Schedule D. See the instructions for Part III of Schedule D to determine if the corporation is liable for the tax.
Line 23d
If the S corporation is a beneficiary of a trust and the trust makes a section 643(g) election to credit its estimated tax payments to its beneficiaries, include the corporation’s share of the payment (reported to the corporation on Schedule K-1 (Form 1041)) in the total amount entered on line 23d. Also, to the left of line 23d, enter “T” and the amount of the payment.
Line 22c
Include in the total for line 22c the following: Investment credit recapture tax. The corporation is liable for investment credit recapture attributable to credits allowed for tax years for which the corporation was not an S corporation. Figure the corporation’s investment credit recapture tax by completing Form 4255, Recapture of Investment Credit. To the left of the line 22c total, enter the amount of recapture tax and “Tax From Form 4255.” Attach Form 4255 to Form 1120S. LIFO recapture tax. The corporation may be liable for the additional tax due to LIFO recapture under Regulations section 1.1363-2 if: • The corporation used the LIFO inventory pricing method for its last tax year as a C corporation, or • A C corporation transferred LIFO inventory to the corporation in a nonrecognition transaction in which those assets were transferred basis property. The additional tax due to LIFO recapture is figured for the corporation’s last tax year as a C corporation or for the tax year of the transfer, whichever applies. See the Instructions for Forms 1120 and 1120-A to figure the tax. The tax is paid in four equal installments. The C corporation must pay the first installment by the due date (not including extensions) of Form 1120 for the
Line 24. Estimated Tax Penalty
A corporation that fails to make estimated tax payments when due may be subject to an underpayment penalty for the period of underpayment. Use Form 2220, Underpayment of Estimated Tax by Corporations, to see if the corporation owes a penalty and to figure the amount of the penalty. If you attach Form 2220 to Form 1120S, be sure to check the box on line 24 and enter the amount of any penalty on this line.
Line 27. Direct Deposit of Refund
If the corporation wants its refund directly deposited into its checking or savings account at any U.S. bank or other financial institution instead of having a check sent to the corporation, complete Form 8050 and attach it to the corporation’s return. However, the corporation cannot have its refund from an amended return directly deposited.
Line 21. Ordinary Income (Loss)
Enter this income or loss on line 1 of Schedule K. Line 21 income is not used in figuring the tax on line 22a or 22b. See the instructions for line 22a for figuring taxable income for purposes of line 22a or 22b tax.
Schedule A. Cost of Goods Sold
Generally, inventories are required at the beginning and end of each tax year if the production, purchase, or sale of merchandise is an income-producing factor. See Regulations section 1.471-1.
-17-
However, if the corporation. See Rev. Proc. 2001-10, 2001-2 I.R.B. 272 for details. A qualifying small business taxpayer is a taxpayer (a) that, for each prior tax year ending on or after December 31, 2000, has average annual gross receipts of $10 million or less for the 3-tax-year period ending with that prior tax year and (b) whose principal business activity is not an ineligible activity. See Rev. Proc. 2002-28, 2002-18 I.R.B. 815 for details. corporation can deduct for the tax year is figured on line 8. Section 263A Uniform Capitalization Rules. The uniform capitalization rules of section 263A are discussed under Limitations on Deductions on page 13. See those instructions before completing Schedule A.
section 263A that are required to be capitalized under section 263A. For new corporations, additional section 263A costs are the costs, other than interest, that must be capitalized under section 263A, but which the corporation would not have been required to capitalize if it had existed before the effective date of section 263A. For more details, see Regulations section 1.263A-2(b). For corporations that have elected the simplified resale method, additional section 263A costs are generally those costs incurred with respect to the following categories. • Off-site storage or warehousing. • Purchasing. • Handling, such as processing, assembly, repackaging, and transporting. • General and administrative costs (mixed service costs). For details, see Regulations section 1.263A-3(d). Enter on line 4 the balance of section 263A costs paid or incurred during the tax year not includable on lines 2, 3, and 5.
Line 5. Other Costs
Enter on line 5 any other inventoriable.
Lines 9a Through 9e. Inventory Valuation Methods
Inventories can. Corporations that use erroneous valuation methods must change to a method permitted for Federal income tax purposes. To make this change, use Form 3115.
Line 1. Inventory at Beginning of Year
If the corporation is changing its method of accounting for the current tax year to no longer account for inventories, 4).
On line 9a, check the method(s) used for valuing inventories. Under “lower of cost or market,” market (for normal goods) means the current bid price prevailing on the inventory valuation date for the particular merchandise in the volume usually purchased by the taxpayer. For a manufacturer, market applies to the basic elements of cost — raw materials, labor, and burden. If section 263A applies to the taxpayer, the basic elements of cost must reflect the current bid price of all direct costs and all indirect costs properly allocable to goods on hand at the inventory date. Inventory may be valued below cost when the merchandise is unsalable at normal prices or unusable in the normal way because the goods are subnormal due to damage, imperfections, shopwear, etc., within the meaning of Regulations section 1.471-2(c). These goods may be valued at a current bona fide selling price, minus direct cost of disposition (but not less than scrap value) if such a price can be established. If this is the first year the Last-in, First-out (LIFO) inventory method was either adopted or extended to inventory goods not previously valued under the LIFO method provided in section 472, attach Form 970, Application To Use LIFO Inventory Method, or a statement with the information required by Form 970. Also check the LIFO box on line 9c. On line 9d, enter the amount or the percent of total closing inventories covered under section 472. Estimates are acceptable. If the corporation changed or extended its inventory method to LIFO and has had to write up its opening inventory to cost in the year of election, report the effect of this write-up as income (line 5, page 1) proportionately over a 3-year period that begins with the tax year of the LIFO election (section 472(d)). See Pub. 538 for more information on inventory valuation methods.
Schedule B. Other Information
Be sure to answer the questions and provide other information in items 1 through 8.
Line 7
Complete line
-18- on line 7 the corporation’s net unrealized built-in gain reduced by the net recognized built-in gain for prior years. See sections 1374(c)(2) and (d)(1).
Line 8
Check the box on line 8 if the corporation was a C corporation in a prior year and has accumulated earnings and profits (E&P) at the close of its 2003 tax year. For details on figuring accumulated E&P, see section 312. If the corporation has accumulated E&P, it may be liable for tax imposed on excess net passive income. See the instructions for line 22a, page 1, of Form 1120S for details on this tax.
Schedule K. Lines 1 through 20 of Schedule K correspond to lines 1 through 20 of Schedule K-1. Other lines do not correspond, but instructions explain the differences. Be sure to give each shareholder a copy of the Shareholder’s Instructions for Schedule K-1 (Form 1120S). These instructions are available separately from Schedule K-1 at most IRS offices. Note: Instructions that apply only to line items reported on Schedule K-1 may be prepared and given to each shareholder instead of the instructions printed by the IRS.
Substitute Forms
The corporation does not need IRS approval to use a substitute Schedule K-1 if it is an exact copy of the IRS schedule, or if it contains only those lines the taxpayer is required to use, and the lines have the same numbers and titles and are in the same order as on the IRS Schedule K-1. In either case, the substitute schedule must include the OMB number and either (a) the Shareholder’s Instructions for Schedule K-1 (Form 1120S) or (b) instructions that apply to the items reported on Schedule K-1 (Form 1120S). The corporation must request IRS approval to use other substitute Schedules K-1. To request approval, write to Internal Revenue Service, Attention: Substitute Forms Program Coordinator, SE:W:CAR:MP:T:T:SP, 1111 Constitution Avenue, NW, Washington, DC 20224. The corporation may be subject to a penalty if it files a substitute Schedule K-1 that does not conform to the specifications of Rev. Proc. 2003-73, 2003-39 I.R.B. 647.
Line 9
Total receipts is the sum of the following amounts: • Gross receipts or sales (page 1, line 1a). • All other income (page 1, lines 4 and 5). • Income reported on Schedule K, lines 3a, 4a, 4b(2), and 4c. • Income or net gain reported on Schedule K, lines 4d(2), 4e(2), 4f, 5, and 6. • Income or net gain reported on Form 8825, lines 2, 19, and 20a.
General Instructions for Schedules K and K-1. Shareholders’ Shares of Income, Credits, Deductions, etc.
Purpose of Schedules
The corporation is liable for taxes on lines 22a, 22b, and 22c, page 1, Form 1120S. Shareholders are liable for income tax on their shares of the corporation’s income (reduced by any taxes paid by the corporation on income) and must include their share of the income on their tax return whether or not it is distributed to them. Unlike most partnership income, S corporation income is not self-employment income and is not subject to self-employment tax. Schedule K is a summary schedule of all shareholders’ shares of the corporation’s income, deductions, credits, etc. Schedule K-1 shows each shareholder’s separate share. Attach a copy of each shareholder’s Schedule K-1 to the Form 1120S filed with the IRS. Keep a copy as a part of the corporation’s records, and give each shareholder a separate copy. The total pro rata share items (column (b)) of all Schedules K-1 should equal the amount reported on the same line shareholder’s Schedule K-1. For more details on the election, see Temporary Regulations section 1.1377-1T(b). Qualifying dispositions. If a qualifying disposition takes place during the tax year, the corporation may make an irrevocable election to allocate income and expenses, etc., as if the corporation’s tax year consisted of 2 tax years, the first of which ends on the close of the day the qualifying disposition occurs. A qualifying disposition is: 1. A disposition by a shareholder of at least 20% of the corporation’s outstanding stock in one or more transactions in any 30-day period during the tax year, 2. A redemption treated as an exchange under section 302(a) or 303(a) of at least 20% of the corporation’s outstanding stock in one or more transactions in any 30-day period during the tax year, or 3. An issuance of stock that equals at least 25% of the previously outstanding stock to one or more new shareholders in any 30-day period during the tax year. To make the election, the corporation must attach a statement to a timely filed original or amended Form 1120S for the tax year for which the election is made. In the statement, the corporation must state that it is electing under Regulations section 1.1368-1(g)(2)(i) to treat the tax year as if it consisted of separate tax years, give the facts relating to the qualifying disposition (e.g., sale, gift, stock issuance, or redemption), and state that each shareholder who held stock in the corporation during the tax year consents to the election. A single election statement may be filed for all elections made under this special rule for the tax year. For more details on the election, see Temporary Regulations section 1.1368-1T(g)(2).
Shareholder’s Pro Rata Share Items
General Rule
Items of income, loss, deductions, etc., are allocated to a shareholder on a daily basis, according to the number of shares of stock held by the shareholder on each day during the tax year of the corporation. See the instructions for item A. A shareholder who disposes of stock is treated as the shareholder for the day of disposition. A shareholder who dies is treated as the shareholder for the day of the shareholder’s death.
Special Rules
Termination of shareholder’s interest. If a shareholder terminates his or her interest in a corporation during the tax year, the corporation, with the consent of all affected shareholders (including the one whose interest is terminated), may elect to allocate income and expenses, etc., as if the corporation’s tax year consisted of 2 separate tax years, the first of which ends on the date of the shareholder’s termination. To make the election, the corporation must attach a statement to a timely filed original or amended Form 1120S for the
Specific Instructions (Schedule K-1 Only)
General Information
On each Schedule K-1, complete the date spaces at the top; enter the names, addresses, and identifying numbers of the shareholder and corporation; complete items A through D; and enter the
-19-
shareholder’s pro rata share of each item. Schedule K-1 must be prepared and given to each shareholder on or before the day on which Form 1120S is filed. Note: Space has been provided on line 23 (Supplemental Information) of Schedule K-1 for the corporation to provide additional information to shareholders. This space, if sufficient, should be used in place of any attached schedules required for any lines on Schedule K-1, or other amounts not shown on lines 1 through 22 of Schedule K-1. Please be sure to identify the applicable line number next to the information entered below line 23.
held 40%, 40%, and 20%, respectively, for the remaining half of the tax year. The percentage of ownership for the year for A, B, and C is figured as follows and is then entered in item A.
a % of total stock owned A B C Total 50 40 50 40 20 b % of tax year held 50 50 50 50 50 c (a b) % of ownership for the year 25 +20 25 +20 10 45 45 10 100%
Line 1. Ordinary Income (Loss) From Trade or Business Activities
Enter the amount from line 21, page 1. Enter the income or loss without reference to (a) shareholders’ basis in the stock of the corporation and in any indebtedness of the corporation to the shareholders (section 1366(d)), (b) shareholders’ at-risk limitations, and (c) shareholders’ passive activity limitations. These limitations, if applicable, are determined at the shareholder level. If the corporation is involved in more than one trade or business activity, see Passive Activity Reporting Requirements on page 11 for details on the information to be reported for each activity. If an at-risk activity loss is reported on line 1, see Special Reporting Requirements for At-Risk Activities above.
Special Reporting Requirements for Corporations With Multiple Activities
If items of income, loss, deduction, or credit from more than one activity (determined for purposes of the passive activity loss and credit limitations) are reported on lines 1, 2, or 3 of Schedule K-1, the corporation must provide information for each activity to its shareholders. See Passive Activity Reporting Requirements on page 11 for details on the reporting requirements.
Special Reporting Requirements for At-Risk Activities
If the corporation is involved in one or more at-risk activities for which a loss is reported on Schedule K-1, the corporation must report information separately for each at-risk activity. See section 465(c) for a definition of at-risk activities. For each at-risk activity, the following information must be provided on an attachment to Schedule K-1: 1. A statement that the information is a breakdown of at-risk activity loss amounts. 2. The identity of the at-risk activity; the loss amount for the activity; other income and deductions; and other information that relates to the activity.
If there was a change in shareholders or in the relative interest in stock the shareholders owned during the tax year, each shareholder’s pro rata share items generally are figured by multiplying the Schedule K amount by the percentage in item 19 for more details. Each shareholder’s pro rata share items are figured separately for each period on a daily basis, based on the percentage of stock held by the shareholder on each day.
Line 2. Net Income (Loss) From Rental Real Estate Activities
Enter the net income or loss from rental real estate activities of the corporation from Form 8825, Rental Real Estate Income and Expenses of a Partnership or an S Corporation. Each Form 8825 has space for reporting the income and expenses of up to eight properties. If the corporation has income or loss from more than one rental real estate activity reported on line 2, see Passive Activity Reporting Requirements on page 11 for details on the information to be reported for each activity. If an at-risk activity loss is reported on line 2, see Special Reporting Requirements for At-Risk Activities above.
Item C
If the corporation is a registration-required tax shelter or has invested in a registration-required tax shelter, it must enter its tax shelter registration number in item C. Also, a corporation that has invested in a registration-required shelter must furnish a copy of its Form 8271 to its shareholders. See Form 8271 for more details.
Line 3. Income and Expenses of Other Rental Activities
Enter on lines 3a and 3b of Schedule K (line 3 of Schedule K-1) the income and expenses of rental activities other than those reported on Form 8825. If the corporation has more than one rental activity reported on line 3, see Passive Activity Reporting Requirements on page 11 for details on the information to be reported for each activity. If an at-risk activity loss is reported on line 3, see Special Reporting Requirements for At-Risk Activities above. Also see Rental Activities on page 8 for a definition and other details on other rental activities.
Specific Items
Item A A for each shareholder. Each shareholder’s pro rata share items (lines 1 through 20 of Schedule K-1) are figured by multiplying the Schedule K amount on the corresponding line of Schedule K by the percentage in item A. If there was a change in shareholders or in the relative interest in stock the shareholders owned during the tax year, each shareholder’s percentage of ownership is weighted for the number of days in the tax year that stock was owned. For example, A and B each held 50% for half the tax year and A, B, and C
Specific Instructions (Schedules K and K-1, Except as Noted)
Income (Loss)
Reminder: Before entering income items on Schedule K or K-1, be sure to reduce the items of income for the following: 1. Built-in gains tax (Schedule D, Part III, line 22). Each recognized built-in gain item (within the meaning of section 1374(d)(3)) is reduced by its proportionate share of the built-in gains tax. 2. Excess net passive income tax (line 22a, page 1, Form 1120S). Each item of passive investment income (within the meaning of section 1362(d)(3)(C)) is reduced by its proportionate share of the net passive income tax.
Lines 4a Through 4f. Portfolio Income (Loss)
Enter portfolio income (loss) on lines 4a through 4f. See Portfolio Income on page 9 for the definition of portfolio income. Do not reduce portfolio income by deductions allocated to it. Report such deductions (other than interest expense) on line 9 of Schedules K and K-1. Interest expense allocable to portfolio income is generally investment interest expense and is reported on line 11a of Schedules K and K-1. Line 4a. Enter only taxable interest on this line from portfolio income. Interest income derived in the ordinary course of the corporation’s trade or business, such
-20-
as interest charged on receivable balances, is reported on line 5, page 1, Form 1120S. See Temporary Regulations section 1.469-2T(c)(3). Lines 4b(1) and 4b(2). Enter only taxable ordinary dividends on these lines. Enter on line 4b(1) all qualified dividends from line 4b(2). Qualified dividends. Except as provided below, qualified dividends are dividends received after December 31, 2002, from domestic corporations and qualified foreign corporations. Exceptions. The following dividends are not qualified dividends: • Dividends the corporation received on any share of stock held for less than 61 days during the 121-day period that began 60 days before the ex-dividend date. When determining the number of days the corporation held the stock, it cannot count certain days during which the corporation’s risk of loss was diminished. See Pub. 550 for more details.. •. See Pub. 550 for more details. Preferred dividends attributable to periods totaling less than 367 days are subject to the 61-day holding period rule above. • Dividends that relate to payments that the corporation is obligated to make with respect to short sales or positions in substantially similar or related property. • Dividends paid by a regulated investment company that are not treated as qualified dividend income under section 854. • Dividends paid by a real estate investment trust that are not treated as qualified dividend income under section 857(c).. See Notice 2003-69, 2003-42 I.R.B. 851 for details. the following foreign entities in either the tax year of the distribution or the preceding tax year: • A foreign investment company (section 1246(b)), • A passive foreign investment company (section 1297), or • A foreign personal holding company (section 552). See Notice 2003-79 for more details. Lines 4d(1) and 4d(2). Enter on line 4d(1) the Post-May 5, 2003, gain or loss from line 6a of Schedule D (Form 1120S). Enter on line 4d(2) the gain (loss) for the entire year from line 6b of Schedule D (Form 1120S). Lines 4e(1) and 4e(2). Enter on line 4e(1) the Post-May 5, 2003, gain or loss that is portfolio income (loss) from Schedule D (Form 1120S), line 13. Enter on line 4e(2) the gain or loss for the entire year that is portfolio income (loss) from Schedule D (Form 1120S), line 14. If any gain or loss from lines 6, 13, and 14 of Schedule D is not CAUTION portfolio income (e.g., gain or loss from the disposition of nondepreciable personal property used in a trade or business), do not report this income or loss on lines 4d(1) through 4e(2). Instead, report it on line 6. Line 4f. Enter any other portfolio income not reported on lines 4a through 4e. If the corporation holds a residual interest in a REMIC, report on an attachment for line 4f each shareholder’s share of taxable income (net loss) from the REMIC (line 1b of Schedule Q (Form 1066)); excess inclusion (line 2c of Schedule Q (Form 1066)); and section 212 expenses (line 3b of Schedule Q (Form 1066)). Because Schedule Q (Form 1066) is a quarterly statement, the corporation must follow the Schedule Q (Form 1066) Instructions for Residual Interest Holder to figure the amounts to report to shareholders for the corporation’s tax year.
Do not include gain or loss from involuntary conversions due to casualty or theft on lines 5a or 5b. Report net gain or loss from involuntary conversions due to casualty or theft on line 6. If the corporation is involved in more than one trade or business or rental activity, see Passive Activity Reporting Requirements on page 11 for details on the information to be reported for each activity. If an at-risk activity loss is reported on line 5, see Special Reporting Requirements for At-Risk Activities on page 20.
Line 6. Other Income (Loss)
Enter any other item of income or loss not included on lines 1 through 5. Items to be reported on line 6 include: • Recoveries of tax benefit items (section 111). • Gambling gains and losses (section 165(d)). • Gains from the disposition of an interest in oil, gas, geothermal, or other mineral properties (section 1254). • Net gain (loss) from involuntary conversions due to casualty or theft. The amount for this item is shown on Form 4684, Casualties and Thefts, line 38a or 38b. • Any net gain or loss from section 1256 contracts from Form 6781, Gains and Losses From Section 1256 Contracts and Straddles. • Gain from the sale or exchange of qualified small business stock (as defined in the Instructions for Schedule D) that is eligible for the 50% section 1202 exclusion. To be eligible for the section 1202 exclusion, the stock must have been held by the corporation for more than 5 years. Corporate shareholders are not eligible for the section 1202 exclusion. Additional limitations apply at the shareholder level. Report each shareholder’s share of section 1202 gain on Schedule K-1. Each shareholder will determine if he or she qualifies for the section 1202 exclusion. Gain eligible for section 1045 rollover (replacement stock purchased by the corporation). Include only gain from the sale or exchange of qualified small business stock (as defined in the Instructions for Schedule D) that was deferred by the corporation under section 1045 and reported on Schedule D. See the Instructions for Schedule D for more details. Corporate shareholders are not eligible for the section 1045 rollover. Additional limitations apply at the shareholder level. Report each shareholder’s share of the gain eligible for section 1045 rollover on Schedule K-1. Each shareholder will determine if he or she qualifies for the rollover. Report on an attachment to Schedule K-1 for each sale or exchange the name of the qualified
!
Line 5. Net Section 1231 Gain (Loss) (Except From Casualty or Theft)
Enter on line 5a the Post-May 5, 2003, net section 1231 gain (loss) from Form 4797, line 7, column (h). Enter on line 5b the net section 1231 gain (loss) for the entire year from Form 4797, line 7, column (g). If the corporation had a gain prior to May 6, 2003, from any section 1231 property held more than 5 years, show the total of all such gains on an attachment to Schedule K-1 (do not include any gain attributable to straight-line depreciation from section 1250 property). Indicate on the statement that this amount should be included in the shareholder’s computation of qualified 5-year gain only if the amount on the shareholder’s Form 4797, line 7, is more than zero.
-21-
small business that issued the stock, the shareholder’s share of the corporation’s adjusted basis and sales price of the stock, and the dates the stock was bought and sold. • Gain eligible for section 1045 rollover (replacement stock not purchased by the corporation). Include only gain from the sale or exchange of qualified small business stock (as defined in the Instructions for Schedule D) the corporation held for more than 6 months but that was not deferred by the corporation under section 1045. See the Instructions for Schedule D for more details. A shareholder (other than a corporation) may be eligible to defer his or her pro rata share of this gain under section 1045 if he or she purchases other qualified small business stock during the 60-day period that began on the date the stock was sold by the corporation. Additional limitations apply at the shareholder level. If the corporation had a gain before May 6, 2003, from the disposition of non-depreciable personal property used in a trade or business held more than 5 years, show the total of all such gains on an attachment to Schedule K-1. Indicate on the statement that the shareholder should include this amount on line 5 of the worksheet for line 35 of Schedule D (Form 1040). If the income or loss is attributable to more than one activity, report the income or loss amount separately for each activity on an attachment to Schedule K-1 and identify the activity to which the income or loss relates. If the corporation is involved in more than one trade or business or rental activity, see Passive Activity Reporting Requirements on page 11 for details on the information to be reported for each activity. If an at-risk activity loss is reported on line 6, see Special Reporting Requirements for At-Risk Activities on page 20.
the corporation corporation’s return, or if earlier, the date the corporation files its return. Do not attach the acknowledgment to the tax return, but keep it with the corporation’s records. These rules apply in addition to the filing requirements for Form 8283 described below. Certain contributions made to an organization conducting lobbying activities are not deductible. See section 170(f)(9) for more details. If the deduction claimed for noncash contributions exceeds $500, complete Form 8283, Noncash Charitable Contributions, and attach it to Form 1120S. The corporation must give a copy of its Form 8283 to every shareholder if the deduction for any item or group of similar items of contributed property exceeds $5,000, even if the amount allocated to any shareholder is $5,000 or less. If the deduction for an item or group of similar items of contributed property is $5,000 or less, the corporation must report each shareholder’s pro rata share of the amount of noncash contributions to enable individual shareholders to complete their own Forms 8283. See the Instructions for Form 8283 for more information. If the corporation made a qualified conservation contribution under section 170(h), also include the fair market value of the underlying property before and after the donation, as well as the type of legal interest contributed, and describe the conservation purpose furthered by the donation. Give a copy of this information to each shareholder.
See the instructions for line 23 of Schedule K-1, item 3, for sales or other dispositions of property for which a section 179 expense deduction has passed through to shareholders. See item 4 for recapture if the business use of the property dropped to 50% or less.
Line 9. Deductions Related to Portfolio Income (Loss)
Enter on line 9 the deductions clearly and directly allocable to portfolio income (other than interest expense). Interest expense related to portfolio income is investment interest expense and is reported on line 11a of Schedules K and K-1. Generally, the line 9 expenses are section 212 expenses and are subject to section 212 limitations at the shareholder level. Note: No deduction is allowed under section 212 for expenses allocable to a convention, seminar, or similar meeting. Because these expenses are not deductible by shareholders, the corporation does not report these expenses on line 9 or line 10. The expenses are nondeductible and are reported as such on line 19 of Schedules K and K-1.
Line 10. Other Deductions
Enter any other deductions not included on lines 7, 8, 9, and 15g. On an attachment, identify the deduction and amount, and if the corporation has more than one activity, the activity to which the deduction relates. Examples of items to be reported on an attachment to line 10 include: • Amounts (other than investment interest required to be reported on line 11a of Schedules K and K-1) paid by the corporation that would be allowed as itemized deductions on a shareholder’s income tax return if they were paid directly by a shareholder for the same purpose. These amounts include, but are not limited to, expenses under section 212 for the production of income other than from the corporation’s trade or business. • Any penalty on early withdrawal of savings not reported on line 9 because the corporation withdrew funds from its time savings deposit before its maturity. • Soil and water conservation expenditures (section 175). • Expenditures paid or incurred for the removal of architectural and transportation barriers to the elderly and disabled that the corporation has elected to treat as a current expense. See section 190. • Contributions to a capital construction fund. • Interest expense allocated to debt-financed distributions. See Notice 89-35, 1989-1 C.B. 675, for more information. • If there was a gain (loss) from a casualty or theft to property not used in a trade or business or for income-producing purposes, provide each shareholder with the needed information to complete Form 4684.
Line 8. Section 179 Expense Deduction
An S corporation may elect to expense part of the cost of certain property that the corporation purchased during the tax year for use in its trade or business or certain rental activities. See the Instructions for Form 4562 for more information. Complete Part I of Form 4562 to figure the corporation’s section 179 expense deduction. The corporation does not claim the deduction itself, but instead passes it through to the shareholders. Attach Form 4562 to Form 1120S and show the total section 179 expense deduction on Schedule K, line 8. Report each individual shareholder’s pro rata share on Schedule K-1, line 8. Do not complete line 8 of Schedule K-1 for any shareholder that is an estate or trust. If the corporation is an enterprise zone business, also report on an attachment to Schedules K and K-1 the cost of section 179 property placed in service during the year that is qualified zone property.
Deductions
Line 7. Charitable Contributions
Enter the amount of charitable contributions paid during the tax year. On an attachment to Schedules K and K-1, show separately the dollar amount of contributions subject to each of the 50%, 30%, and 20% of adjusted gross income limits. For additional information, see Pub. 526, Charitable Contributions. An accrual basis S corporation may not elect to treat a CAUTION contribution as having been paid in the tax year the board of directors authorizes the payment if the contribution is not actually paid until the next tax year. Generally, no deduction is allowed for any contribution of $250 or more unless
!
-22-
Investment Interest
Complete lines 11a and 11b for all shareholders.
Credits
Note: If the corporation has credits from more than one trade or business activity on line 12a or 13, or from more than one rental activity on line 12b, 12c, 12d, or 12e, it must report separately on an attachment to Schedule K-1, the amount of each credit and provide any other applicable activity information listed in Passive Activity Reporting Requirements on page 11. However, do not attach Form 3800, General Business Credit, to Form 1120S.
Line 11a. Investment Interest Expense. Report investment interest expense only on line 11a of Schedules K and K-1. The amount on line 11a will be deducted by individual shareholders on Schedule A (Form 1040), line 13, after applying the investment interest expense limitations of section 163(d). For more information, see Form 4952, Investment Interest Expense Deduction.
on line 12a(2) of Schedule K-1 (Form 1065). Note: If part or all of the credit reported on line 12b(1) or 12b(2) is attributable to additions to qualified basis of property placed in service before 1990, report on an attachment to Schedules K and K-1 the amount of the credit on each line that is attributable to property placed in service (a) before 1990 and (b) after 1989.
Line 12a. Credit for Alcohol Used as Fuel
Enter on line 12a of Schedule K the credit for alcohol used as fuel attributable to trade or business activities. Enter on line 12d or 12e the credit for alcohol used as fuel attributable to rental activities. Figure the credit on Form 6478, Credit for Alcohol Used as Fuel, and attach it to Form 1120S. The credit must be included in income on page 1, line 5, of Form 1120S. See section 40(f) for an election the corporation can make to have the credit not apply. Enter each shareholder’s share of the credit for alcohol used as fuel on line 12a, 12d, or 12e of Schedule K-1. If this credit includes the small ethanol producer credit, identify on a statement attached to each Schedule K-1 (a) the amount of the small producer credit included in the total credit allocated to the shareholder, (b) the number of gallons of qualified ethanol fuel production allocated to the shareholder, and (c) the shareholder’s pro rata share, in gallons, of the corporation’s productive capacity for alcohol.
Line 12c. Qualified Rehabilitation Expenditures Related to Rental Real Estate Activities
Enter total qualified rehabilitation expenditures related to rental real estate activities of the corporation. For line 12c of Schedule K, complete the applicable lines of Form 3468, Investment Credit, that apply to qualified rehabilitation expenditures for property related to rental real estate activities of the corporation for which income or loss is reported on line 2 of Schedule K. See Form 3468 for details on qualified rehabilitation expenditures. Attach Form 3468 to Form 1120S. For line 12c of Schedule K-1, enter each shareholder’s pro rata share of the expenditures. On the dotted line to the left of the entry space for line 12c, enter the line number of Form 3468 on which the shareholder should report the expenditures. If there is more than one type of expenditure, or the expenditures are from more than one line 2 activity, report this information separately for each expenditure or activity on an attachment to Schedules K and K-1. Note: Qualified rehabilitation expenditures not related to rental real estate activities must be listed separately on line 23 of Schedule K-1.
Lines 11b(1) and 11b(2). Investment Income and Expenses
Enter on line 11b(1) only the investment income included on lines 4a, b(2), c, and f of Schedule K-1. Do not include other portfolio gains or losses on this line. Enter on line 11b(2) only the investment expense included on line 9 of Schedule K-1. If there are other items of investment income or expense included in the amounts that are required to be passed through separately to the shareholders on Schedule K-1, such as net short-term capital gain or loss, net long-term capital gain or loss, and other portfolio gains or losses, give each shareholder a schedule identifying these amounts. Investment income includes gross income from property held for investment, the excess of net gain attributable to the disposition of property held for investment over net capital gain from the disposition of property held for investment, and any net capital gain from the disposition of property held for investment that each shareholder elects to include in investment income under section 163(d)(4)(B)(iii). on investment income and expenses.
Line 12b. Low-Income Housing Credit
Section 42 provides for a credit that may be claimed by owners of low-income residential rental buildings. If shareholders are eligible to claim the low-income housing credit, complete the applicable parts of Form 8586, Low-Income Housing Credit, and attach it to Form 1120S. Enter the credit figured by the corporation on Form 8586, and any low-income housing credit received from other entities in which the corporation is allowed to invest, on the applicable line as explained below. The corporation must also complete and attach Form 8609, Low-Income Housing Credit Allocation Certification, and Schedule A (Form 8609), Annual Statement, to Form 1120S. See the Instructions for Form 8586 and Form 8609 for information on completing these forms. Line 12b(1). If the corporation invested in a partnership to which the provisions of section 42(j)(5) apply, report on line 12b(1) the credit the partnership reported to the corporation on line 12a(1) of Schedule K-1 (Form 1065). Line 12b(2). Report on line 12b(2) any low-income housing credit not reported on line 12b(1). This includes any credit from a partnership reported to the corporation
Line 12d. Credits (Other Than Credits Shown on Lines 12b and 12c) Related to Rental Real Estate Activities
Enter on line 12d any other credit (other than credits on lines 12b and 12c) related to rental real estate activities. On the dotted line to the left of the entry space for line 12d, identify the type of credit. If there is more than one type of credit or the credit is from more than one line 2 activity, report this information separately for each credit or activity on an attachment to Schedules K and K-1. These credits may include any type of credit listed in the instructions for line 13.
Line 12e. Credits Related to Other Rental Activities
Enter on line 12e any credit related to other rental activities for which income or loss is reported on line 3 of Schedules K and K-1. On the dotted line to the left of the entry space for line 12e, identify the type of credit. If there is more than one type of credit or the credit is from more than one line 3 activity, report this information separately for each credit or activity on an attachment to Schedules K and K-1. These credits may include any type of credit listed in the instructions for line 13.
-23-
Line 13. Other Credits
Enter on line 13 any other credit, except credits or expenditures shown or listed for lines 12a through 12e of Schedules K and K-1 or the credit for Federal tax paid on fuels (which is reported on line 23c of page 1). On the dotted line to the left of the entry space for line 13, identify the type of credit. If there is more than one type of credit or the credit is from more than one activity, report this information separately for each credit or activity on an attachment to Schedules K and K-1. The credits to be reported on line 13 and other required attachments follow. • Credit for backup withholding on dividends, interest, or patronage dividends. • Nonconventional source fuel credit. Figure this credit on a separate schedule and attach it to Form 1120S. See section 29 for rules on figuring the credit. • Qualified electric vehicle credit (Form 8834). • Unused investment credit from cooperatives. If the corporation is a member of a cooperative that passes an unused investment credit through to its members, the credit is in turn passed through to the corporation’s shareholders. • Work opportunity credit (Form 5884). • Welfare-to-work credit (Form 8861). • Credit for increasing research activities (Form 6765). • Enhanced oil recovery credit (Form 8830). • Disabled access credit (Form 8826). • Renewable electricity production credit (Form 8835). • Empowerment zone and renewal community employment credit (Form 8844). • Indian employment credit (Form 8845). • Credit for employer social security and Medicare taxes paid on certain employee tips (Form 8846). • Orphan drug credit (Form 8820). • New markets credit (Form 8874). • Credit for contributions to selected community development corporations (Form 8847). • Credit for small employer pension start-up costs (Form 8881). • Credit for employer-provided child care facilities and services (Form 8882). • New York Liberty Zone business employee credit (Form 8884). • Qualified zone academy bond credit (Form 8860). • General credits from an electing large partnership. See the instructions for line 21 (Schedule K) and line 23 (Schedule K-1) to report expenditures qualifying for the (a) rehabilitation credit not related to rental real estate activities, (b) energy credit, or (c) reforestation credit.
(AMT). See Form 6251, Alternative Minimum Tax — Individuals, or Schedule I of Form 1041, U.S. Income Tax Return for Estates and Trusts, to determine the amounts to enter and for other information. Do not include as a tax preference item any qualified expenditures to which an election under section 59(e) may apply. Because these expenditures are subject to an election by each shareholder, the corporation cannot figure the amount of any tax preference related to them. Instead, the corporation must pass through to each shareholder on lines 16a and 16b of Schedule K-1 the information needed to figure the deduction.
result on line 14.
Line 14b. Adjusted Gain or Loss schedule that identifies the amount of the adjustment allocable to each type of gain or loss. For a net long-term capital gain (loss), also identify the amount of the adjustment that is 28% rate gain (loss). For a net section 1231 gain (loss), also identify the amount of adjustment that is unrecaptured section 1250 gain. Also indicate the amount of any qualified 5-year gain and the portion of each amount that is post-May 5, 2003, gain or loss.
Line 14a. Depreciation Adjustment on Property Placed in Service After 1986
Figure the adjustment for line): • For section 1250 property (generally, residential rental and nonresidential real property), use the straight line method over 40 years. • For tangible property (other than section 1250 property) depreciated using the straight line method for the regular tax, use the straight line method over the property’s class life. Use 12 years if the property has no class life. •.
Line 14c. Depletion (Other Than Oil and Gas)
Do not include any depletion on oil and gas wells. The shareholders must figure their.
Adjustments and Tax Preference Items
Lines 14a through 14e must be completed for all shareholders. Enter items of income and deductions that are adjustments or tax preference items for the alternative minimum tax
-24-
Lines 14d(1) and 14d(2)
Generally, the amounts to be entered on these lines are only the income and deductions for oil, gas, and geothermal properties that are used to figure the amount on line 21, page 1, Form 1120S. If there are any items of income or deductions for oil, gas, and geothermal properties included in the amounts that are required to be passed through separately to the shareholders on Schedule K-1, give each shareholder a schedule that shows, for the line on which the income or deduction is included, the amount of income or deductions included in the total amount for that line. Do not include any of these direct pass-through amounts on line 14d(1) or 14d(2). The shareholder is told in the Shareholder’s Instructions for Schedule K-1 (Form 1120S) to adjust the amounts on lines 14d(1) and 14d(2) for any other income or deductions from oil, gas, or geothermal properties included on lines 2 through 10 and 23 of Schedule K-1 in order to determine the total income and deductions from oil, gas, and geothermal properties for the corporation. Figure the amounts for lines 14d(1) and 14d(2) separately for oil and gas properties that are not geothermal deposits and for all properties that are geothermal deposits. Give the shareholders a schedule that shows the separate amounts included in the computation of the amounts on lines 14d(1) and 14d(2). Line 14d(1). Gross income from oil, gas, and geothermal properties. Enter the total amount of gross income (within the meaning of section 613(a)) from all oil, gas, and geothermal properties received or accrued during the tax year and included on page 1, Form 1120S. Line 14d(2). Deductions allocable to oil, gas, and geothermal properties. Enter the amount of any deductions allowed for the AMT that are allocable to oil, gas, and geothermal properties.
• Losses from tax shelter farm activities.
No loss from any tax shelter farm activity is allowed for the AMT.
Foreign Taxes
Lines 15a through 15h must be completed if the corporation has foreign income, deductions, or losses, or has paid or accrued foreign taxes. See Pub. 514, Foreign Tax Credit for Individuals, for more information.
Line 15a. Name of Foreign Country or U.S. Possession schedule for each country for lines 15a through 15h.
included in each of the following listed categories of income: • Financial services income; • High withholding tax interest; • Shipping income; • Dividends from each noncontrolled section 902 corporation; • Dividends from a domestic international sales corporation (DISC) or a former DISC; • Distributions from a foreign sales corporation (FSC) or a former FSC; • Section 901(j) income; and • Certain income re-sourced by treaty. Line 15d(3). General limitation foreign source income (all other foreign source income).
Line 15e. Deductions Allocated and Apportioned at Shareholder Level
Enter on line 15e(1) the corporation corporate level and is included on lines 15f(1) through (3). On line 15e(2), enter the total of all other deductions or losses that are required to be allocated at the shareholder level. For example, include on line 15e(2) research and experimental expenditures (see Regulations section 1.861-17(f)).
Line 15b. Gross Income From All Sources
Enter the corporation’s gross income from all sources, (both U.S. and foreign).
Line 15c. Gross Income Sourced at Shareholder Level schedule showing the following information: • The amount of this gross income (without regard to its source) in each category identified in the instructions for line 15d, including each of the listed categories. • Sales or Exchanges of Certain Personal Property in Pub. 514 and section 865. • Specify foreign source capital gains or losses within each separate limitation category. Also separately identify foreign source gains or losses within each separate limitation category that are 28% rate gains and losses, unrecaptured section 1250 gains, and qualified 5-year gains and indicate the post-May 5, 2003, portion of each.
Line 15f. Deductions Allocated and Apportioned at Corporate Level to Foreign Source Income
Separately report corporate deductions that are apportioned at the corporate level to (1) passive foreign source income, (2) each of the listed foreign categories of income, and (3) general limitation foreign source income (see the instructions for line 15d). See Pub. 514 for more information.
Line 15g. Total Foreign Taxes
Enter in U.S. dollars the total foreign taxes (described in section 901 or section 903) that were paid or accrued by the corporation (according to its method of accounting for such taxes). Translate these amounts into U.S. dollars by using the applicable exchange rate (see Pub. 514). Attach a schedule reporting the following information: 1. The total amount of foreign taxes (including foreign taxes on income sourced at the shareholder level) relating to each category of income (see instructions for line 15d). 2. The dates on which the taxes were paid or accrued, the exchange rates used, and the amounts in both foreign currency and U.S. dollars, for: • Taxes withheld at source on interest. • Taxes withheld at source on dividends.
Line 14e. Other Adjustments and Tax Preference Items
Attach a schedule that shows each shareholder’s share of other items not shown on lines 14a through 14d(2) that are adjustments or tax preference items or that the shareholder needs to complete Form 6251 or Schedule I of Form 1041. See these forms and their instructions to determine the amount to enter. Other adjustments or tax preference items include the following: • Accelerated depreciation of real property under pre-1987 rules. • Accelerated depreciation of leased personal property under pre-1987 rules. • Long-term contracts entered into after February 28, 1986. Except for certain home construction contracts, the taxable income from these contracts must be figured using the percentage of completion method of accounting for the AMT.
Line 15d. Foreign Gross Income Sourced at Corporate Level
Separately report gross income from sources outside the United States by category of income as follows. See Pub. 514 for information on the categories of income. Line 15d(1). Passive foreign source income. Line 15d(2). Attach a schedule showing the amount of foreign source income
-25-
• Taxes withheld at source on rents and royalties. • Other foreign taxes paid or accrued.
Line 15h. Reduction in Taxes Available for Credit
Enter the total reductions in taxes available for credit. Attach a schedule showing the reductions for: • Taxes on foreign mineral income (section 901(e)). • Taxes on foreign oil and gas extraction income (section 907(a)). • Taxes attributable to boycott operations (section 908). • Failure to timely file (or furnish all of the information required on) Forms 5471 and 8865. • Any other items (specify).
this information separately for each type of expenditure (or month) on an attachment to Schedules K and K-1.
Line 17. Tax-Exempt Interest Income
Enter on line 17 tax-exempt interest income, including any exempt-interest dividends received from a mutual fund or other regulated investment company. This information must be reported by individuals on line 8b of Form 1040. Generally, the basis of the shareholder’s stock is increased by the amount shown on this line under section 1367(a)(1)(A).
the corporation must provide the necessary information to the shareholder to enable the shareholder to figure the recapture. If the corporation filed Form 8693, Low-Income Housing Credit Disposition Bond, to avoid recapture of the low-income housing credit, no entry should be made on line 22 of Schedule K-1. See Form 8586, Form 8611, and section 42 for more information.
Supplemental Information
Line 23 (Schedule K-1 Only)
Enter in the line 23 Supplemental Information space of Schedule K-1, or on an attached schedule if more space is needed, each shareholder’s share of any information asked for on lines 1 through 27 that is required to be reported in detail, and items 1 through 28 below. Please identify the applicable line number next to the information entered in the Supplemental Information space. Show income or gains as a positive number. Show losses in parentheses. 1. Taxes paid on undistributed capital gains by a regulated investment company or a real estate investment trust (REIT). As a shareholder of a regulated investment company or a REIT, the corporation will receive notice on Form 2439, Notice to Shareholder of Undistributed Long-Term Capital Gains, of the amount of tax paid on undistributed capital gains. 2. Gross income and other information relating to oil and gas well properties that are reported to shareholders to allow them to figure the depletion deduction for oil and gas well properties. See section 613A(c)(11) for details. The corporation cannot deduct depletion on oil and gas wells. Each shareholder must determine the allowable amount to report on his or her return. See Pub. 535 for more information. 3. Gain or loss on the sale, exchange, or other disposition of property for which a section 179 expense deduction has been passed through to shareholders. The corporation must provide all the following information with respect to a disposition of property for which a section 179 expense deduction was passed through to shareholders (see the instructions for line 4 on page 13). a. Description of the property. b. Date the property was acquired. c. Date of the sale or other disposition of the property. d. The shareholder’s pro rata share of the gross sales price. e. The shareholder’s pro rata share of the cost or other basis plus expense of sale (reduced as explained in the instructions for Form 4797, line 21). f. The shareholder’s pro rata share of the depreciation allowed or allowable, determined as described in the instructions for Form 4797, line 22, but
Line 18. Other Tax-Exempt Income
Enter on line 18 all income of the corporation exempt from tax other than tax-exempt interest (e.g., life insurance proceeds). Generally, the basis of the shareholder’s stock is increased by the amount shown on this line under section 1367(a)(1)(A).
Other
Lines 16a and 16b. Section 59(e)(2) Expenditures
Generally, section 59(e) allows each shareholder to make an election to deduct the shareholder’s pro rata share of the corporation: • Circulation expenditures. • Research and experimental expenditures. • Intangible drilling and development costs. • Mining exploration and development costs. If a shareholder makes the election, the above items are not treated as tax preference items. Because the shareholders are generally allowed to make this election, the corporation cannot deduct these amounts or include them as adjustments or tax preference items on Schedule K-1. Instead, on lines 16a and 16b of Schedule K-1, the corporation passes through the information the shareholders need to figure their separate deductions. On line 16a, enter the type of expenditures claimed on line 16b. Enter on line 16b the qualified expenditures paid or incurred during the tax year to which an election under section 59(e) may apply. Enter this amount for all shareholders whether or not any shareholder makes an election under section 59(e). If the expenditures are for intangible drilling and development costs, enter the month in which the expenditures were paid or incurred (after the type of expenditures on line 16a). If there is more than one type of expenditure included in the total shown on line 16b (or intangible drilling and development costs were paid or incurred for more than 1 month), report
Line 19. Nondeductible Expenses
Enter on line 19 nondeductible expenses paid or incurred by the corporation. Do not include separately stated deductions shown elsewhere on Schedules K and K-1, capital expenditures, or items for which the deduction is deferred to a later tax year. Generally, the basis of the shareholder’s stock is decreased by the amount shown on this line under section 1367(a)(2)(D).
Line 20
Enter total distributions made to each shareholder other than dividends reported on line 22 of Schedule K. Noncash distributions of appreciated property are valued at fair market value. See Distributions on page 29 for the ordering rules on distributions.
Line 21 (Schedule K Only)
Attach a statement to Schedule K to report the corporation’s total income, expenditures, or other information for items 1 through 28 of the line 23 (Schedule K-1 Only) instruction below.
Line 22 (Schedule K Only)
Enter total dividends paid to shareholders from accumulated earnings and profits. Report these dividends to shareholders on Form 1099-DIV. Do not report them on Schedule K-1.
Lines 22a and 22b (Schedule K-1 Only). Recapture of Low-Income Housing Credit
If recapture of part or all of the low-income housing credit is required because (a) prior year qualified basis of a building decreased or (b) the corporation disposed of a building or part of its interest in a building, see Form 8611, Recapture of Low-Income Housing Credit. The instructions for Form 8611 indicate when Form 8611 is completed by the corporation and what information is provided to shareholders when recapture is required. Note: If a shareholder’s ownership interest in a building decreased because of a transaction at the shareholder level,
-26-
excluding the section 179 expense deduction. g. The shareholder’s pro rata share of the section 179 expense deduction (if any) passed through for the property and the corporation’s tax year(s) in which the amount was passed through. h. An indication if the disposition is from a casualty or theft. i. For an installment sale made during the corporation’s tax year, any information needed to complete Form 6252, Installment Sale Income. The corporation also must separately report the shareholder’s pro rata share of all payments received for the property in future tax years. (Installment payments received for installment sales made in prior tax years should be reported in the same manner used in prior tax years.) 4. Recapture of section 179 expense deduction if business use of the property dropped to 50% or less. If the business use of any property (placed in service after 1986) for which a section 179 expense deduction was passed through to shareholders dropped to 50% or less (for a reason other than disposition), the corporation must provide all the following information. a. The shareholder’s pro rata share of the original basis and depreciation allowed or allowable (not including the section 179 expense deduction). b. The shareholder’s pro rata share of the section 179 expense deduction (if any) passed through for the property and the corporation’s tax year(s) in which the amount was passed through. 5. Recapture of certain mining exploration expenditures (section 617). 6. Any information or statements the corporation is required to furnish to shareholders to allow them to comply with requirements under section 6111 (registration of tax shelters) or section 6662(d)(2)(B)(ii) (regarding adequate disclosure of items that may cause an understatement of income tax). 7. If the corporation is involved in farming or fishing activities, report the gross income from these activities to shareholders. 8. Any information needed by a shareholder to compute the interest due under section 453(l)(3). If the corporation elected to report the dispositions of certain timeshares and residential lots on the installment method, each shareholder’s tax liability must be increased by the shareholder’s pro rata share of the interest on tax attributable to the installment payments received during the tax year. 9. Any information needed by a shareholder to compute the interest due under section 453A(c). If an obligation arising from the disposition of property to which section 453A applies is outstanding at the close of the year, each shareholder’s tax liability must be increased by the tax due under section 453A(c) on the shareholder’s pro rata share of the tax deferred under the installment method.
10. Any information needed by a shareholder to properly capitalize interest as required by section 263A(f). See Section 263A uniform capitalization rules on page 13 for more information. 11. If the corporation is a closely held S corporation (defined in section 460(b)) and it entered into any long-term contracts after February 28, 1986, that are accounted for under either the percentage of completion-capitalized cost method or the percentage of completion method, it must attach a schedule to Form 1120S showing the information required in items (a) and (b) of the instructions for lines 1 and 3 of Part II for Form 8697, Interest Computation Under the Look-Back Method for Completed Long-Term Contracts. It must also report the amounts for Part II, lines 1 and 3, to its shareholders. See the Instructions for Form 8697 for more information. 12. Expenditures qualifying for the (a) rehabilitation credit not related to rental real estate activities, (b) energy credit, or (c) reforestation credit. Complete and attach Form 3468 to Form 1120S. See Form 3468 and related instructions for information on eligible property and the lines on Form 3468 to complete. Do not include that part of the cost of the property the corporation has elected to expense under section 179. Attach to each Schedule K-1 a separate schedule in a format similar to that shown on Form 3468 detailing each shareholder’s pro rata share of qualified expenditures. Also indicate the lines of Form 3468 on which the shareholders should report these amounts., 4, and 5, whether or not any shareholder is subject to recapture of the credit. Attach to each Schedule K-1 a separate schedule providing the information the corporation is required to show on Form 4255, but list only the shareholder’s pro rata share of the cost of the property subject to recapture. Also indicate the lines of Form 4255 on which the shareholders should report these amounts. The corporation itself is liable for investment credit recapture in certain cases. See the instructions for line 22c, page 1, Form 1120S, for details. 14. Any information needed by a shareholder to compute the recapture of the qualified electric vehicle credit. See Pub. 535 for more information. 15. Recapture of new markets credit (Form 8874). 16. Any information a shareholder may need to figure recapture of the Indian employment credit. Generally, if the corporation terminates a qualified employee less than 1 year after the date of initial employment, any Indian
employment credit allowed for a prior tax year by reason of wages paid or incurred to that employee must be recaptured. For details, see section 45A(d). 17. Nonqualified withdrawals by the corporation from a capital construction fund. 18. Unrecaptured section 1250 gain. Figure this amount for each section 1250 property in Part III of Form 4797 (except property for which gain is reported using the installment method on Form 6252) for which you had an entry in Part I of Form 4797 by subtracting line 26g of Form 4797 from the smaller of line 22 or line 24 of Form 4797. Figure the total of these amounts for all section 1250 properties. Generally, the result is the corporation’s unrecaptured section 1250 gain. However, if the corporation is reporting gain on the installment method for a section 1250 property held more than 1 year, see the next paragraph to figure the unrecaptured section 1250 gain on that property allocable to this tax year. Report each shareholder’s pro rata share of the total amount as “Unrecaptured section 1250 gain.” The total unrecaptured section 1250 gain for an installment sale of section 1250 property held more than 1 year is figured in a manner similar to that used in the preceding paragraph. However, the total unrecaptured section 1250 gain must be allocated to the installment payments received from the sale. To do so, the corporation generally must treat the gain allocable to each installment payment as unrecaptured section 1250 gain until all such gain has been used in full. Figure the unrecaptured section 1250 gain for installment payments received during the tax year as the smaller of (a) the amount from line 26 or line 37 of Form 6252 (whichever applies) or (b) the total unrecaptured section 1250 gain for the sale reduced by all gain reported in prior years (excluding section 1250 ordinary income recapture). However, if the corporation chose not to treat all of the gain from payments received after May 6, 1997, and before August 24, 1999, as unrecaptured section 1250 gain, use only the amount the corporation chose to treat as unrecaptured section 1250 gain for those payments to reduce the total unrecaptured section 1250 gain remaining to be reported for the sale. If the corporation received a Schedule K-1 or Form 1099-DIV from an estate, a trust, a REIT, or a mutual fund reporting “unrecaptured section 1250 gain,” do not add it to the corporation’s own unrecaptured section 1250 gain. Instead, report it as a separate amount. For example, if the corporation received a Form 1099-DIV from a REIT with unrecaptured section 1250 gain, report it as “Unrecaptured section 1250 gain from a REIT.” Also report as a separate amount any gain from the sale or exchange of an interest in a partnership attributable to unrecaptured section 1250 gain. See Regulations section 1.1(h)-1 and attach a
-27-
statement required under Regulations section 1.1(h)-1(e). 19. 28% rate gain (loss). Figure this amount attributable to collectibles from the amount reported on Schedule D (Form 1120S) line 14. A collectibles gain (loss) is any long-term gain or deductible long-term loss from the sale or exchange of a collectible that is a capital asset. Collectibles include works of art, rugs, antiques, metal (such as gold, silver, platinum bullion), gems, stamps,). 20. Qualified 5-year gain. Attach a statement to each Schedule K-1 indicating the amount of net long-term gain (not losses) from the disposition of assets (excluding stock that could qualify for section 1202 gain) held more than 5 years that are portfolio income included on line 14 of Schedule D (Form 1120S). Also indicated the aggregate amount of all section 1231 gains from property held more than 5 years. Qualified 5-year gains should be reported only for the portion of the tax year before May 6, 2003. Do not include any section 1231 gain attributable to straight-line depreciation from section 1250 property. Indicate on the statement that this amount should be included in the shareholder’s computation of qualified 5-year gain only if the amount on the shareholder’s Form 4797, line 7, column (g), is more than zero, and that none of the gain is unrecaptured section 1250 gain. 21. If the corporation is a closely held S corporation (defined in section 460(b)(4)) and it depreciated certain property placed in service after September 13, 1995, under the income forecast method, it must attach to Form 1120S the information specified in the instructions for Form 8866, line 2, for the 3rd and 10th tax years beginning after the tax year the property was placed in service. It must also report the line 2 amounts to its shareholders. See the Instructions for Form 8866 for more details. 22. Amortization of reforestation expenditures. Report the amortizable basis and year in which the amortization began for the current year and the 7 preceding years. For limits that may apply, see section 194 and Pub. 535. 23. Any information needed by a shareholder to figure the interest due under section 1260(b). If any portion of a
constructive ownership transaction was open in any prior year, each shareholder’s tax liability must be increased by the shareholder’s pro rata share of interest due on any deferral of gain recognition. See section 1260(b) for details, including how to figure the interest. 24. Any information needed by a shareholder to figure the extraterritorial income exclusion. See Extraterritorial Income Exclusion on page 11 for more information. 25. Commercial revitalization deduction from rental real estate activities. See Line 19 — Other Deductions for the Special Rules that apply to the deduction. 26. If the corporation participates in a transaction that must be disclosed on Form 8886 (see page. 27. Recapture of the credit for employer-provided child care facilities and services (Form 8882). 28. Any other information the shareholders need to prepare their tax returns.
Line 24. Retained Earnings.
Line 25. is a negative amount, enter the amount in parentheses.
Schedule L. Balance Sheets per Books
The balance sheets should agree with the corporation’s books and records. Include certificates of deposit as cash on line 1 of Schedule L. If the S election terminated during the tax year,.
Schedule M-1. Reconciliation of Income (Loss) per Books With Income (Loss) per Return
Line 3b. Travel and Entertainment
Include on this line: • Meals and entertainment not allowed under section 274(n). • Expenses for the use of an entertainment facility. • The part of business gifts over $25. • Expenses of an individual allocable to conventions on cruise ships over $2,000. • Employee achievement awards over $400. • The part of the cost of entertainment tickets that exceeds face value (also subject to 50% limit). • The part of the cost of skyboxes that exceeds the face value of nonluxury box seat tickets. • The part of the cost of luxury water travel not allowed under section 274(m). • Expenses for travel as a form of education; nondeductible club dues. • Other travel and entertainment expenses.
Line 5. Tax-Exempt Securities
• State and local government obligations,
the interest on which is excludible from gross income under section 103(a), and • Stock in a mutual fund or other regulated investment company that distributed exempt-interest dividends during the tax year of the corporation. Include on this line:
-28-
Schedule M-2
Worksheet
(a) Accumulated adjustments account (b) Other adjustments account (c) Shareholders’ undistributed taxable income previously taxed
1 2 3 4 5 6 7 8
Balance at beginning of tax year Ordinary income from page 1, line 21 Other additions Loss from page 1, line 21 Other reductions Combine lines 1 through 5 Distributions other than dividend distributions Balance at end of tax year. Subtract line 7 from line 6
-010,000 20,000 ( ( ( 36,000 6,000 -06,000 ) ) ) (
-05,000 ) 5,000 5,000 -0-
(
)
Schedule M-2. Analysis of Accumulated Adjustments Account, Other Adjustments Account, and Shareholders’ Undistributed Taxable Income Previously Taxed
Column (a). Accumulated Adjustments Account. On the first day of the corporation’s first tax year as an S corporation, the balance of the AAA is zero. At the end of the tax year, adjust the AAA for the items for the tax year as explained below and in the order listed. 1. Increase the AAA by income (other than tax-exempt income) and the excess of the deduction for depletion over the basis of the property subject to depletion (unless the property is an oil and gas property the basis of which has been allocated to shareholders). 2. Generally, decrease the AAA by deductible losses and expenses, nondeductible expenses (other than expenses related to tax-exempt income and Federal taxes attributable to a C
corporation tax year), and the sum of the shareholders’ deductions for depletion for any oil or gas property held by the corporation as described in section 1367(a)(2)(E). However, if the total decreases under 2 exceeds the total increases under 1 above, the excess is a ‘‘net negative adjustment.’’ If the corporation has a net negative adjustment, do not take it into account under 2. Instead, take it into account only under 4 below. 3. Decrease AAA (but not below zero) by property distributions (other than dividend distributions from accumulated E&P), unless the corporation elects to reduce accumulated E&P first. See Distributions below for definitions and other details. 4. Decrease AAA by any net negative adjustment. For adjustments to the AAA for redemptions, reorganizations, and corporate separations, see Regulations section 1.1368-2(d). Note: The AAA may have a negative balance at year end. See section 1368(e).
cannot be transferred to another person. The corporation is required to keep records of each shareholder’s net share of PTI.
Distributions
General rule. Unless the corporation makes one of the elections described below, property distributions (including cash) are applied in the following order to reduce accounts of the S corporation that are used to figure the tax effect of distributions made by the corporation to its shareholders: 1.(c). 2. Reduce shareholders’ PTI account for any section 1375(d) (as in effect before 1983) distributions. A distribution from the PTI account is tax free to the extent of a shareholder’s basis in his or her stock in the corporation. 3.). 4. Reduce the other adjustments account. 5. Reduce any remaining shareholders’ equity accounts. Elections relating to source of distributions. The corporation may modify the above ordering rules by making one or more of the following elections: 1. Election to distribute accumulated E&P first. If the corporation has accumulated E&P and
Column (b). Other Adjustments Account
The other adjustments account is adjusted for tax-exempt income (and related expenses) and Federal taxes attributable to a C corporation tax year. After these adjustments are made, the account is reduced for any distributions made during the year. See Distributions below.
Column (c). Shareholders’ Undistributed Taxable Income Previously Taxed
The shareholders’ undistributed taxable income previously taxed account, also called previously taxed income (PTI), is maintained only if the corporation had a balance in this account at the start of its 2003 tax year. If there is a beginning balance for the 2003
-29-
wants to distribute this E&P. 2. Election to make a deemed dividend.. 3. Election to forego PTI. If the corporation wants to forego distributions of PTI, it may elect to do so with the consent of all its affected shareholders (section 1368(e)(3)(B)). Under this election, paragraph 2 under the General rule on page 29 does not apply to any distribution made during the tax year. This
election is irrevocable and applies only for the tax year for which it is made. For details on making the election, see Statement regarding elections below. Statement regarding elections. To make any of the above elections, the corporation must attach a statement to a timely filed original or amended Form 1120S for the tax year for which the election is made. In the statement, the corporation must identify the election it is making and must state that each shareholder consents to the election. The statement of election to make a deemed dividend must include the amount of the deemed dividend distributed to each shareholder. For more details on the election, see Temporary Regulations section 1.1368-1T(f)(5).
8. Schedule K, line 17 tax-exempt interest — $5,000 9. Schedule K, line 19 nondeductible expenses — $6,000 (reduction in salaries and wages for work opportunity credit), and 10. Schedule K, line 20 distributions — $65,000. Based on return items 1 through 10 and starting balances of zero, the columns for the AAA and the other adjustments account are completed as shown in the Schedule M-2 Worksheet on page 29. For the AAA, the worksheet line 3 — $20,000 amount is the total of the Schedule K, lines 4a and 4b(2) income of $4,000 and $16,000. The worksheet line 5 — $36,000 amount is the total of the Schedule K, line 2 loss of ($3,000), line 7 deduction of $24,000, line 10 deduction of $3,000, and the line 19 nondeductible expenses of $6,000. The worksheet line 7 is zero. The AAA at the end of the tax year (figured without regard to distributions and the net negative adjustment of $6,000) is zero, and distributions cannot reduce the AAA below zero. For the other adjustments account, the worksheet line 3 amount is the Schedule K, line 17, tax-exempt interest income of $5,000. The worksheet line 7 amount is $5,000, reducing the other adjustments account to zero. The remaining $60,000 of distributions are not entered on Schedule M-2.
Example
The following example shows how the Schedule M-2 accounts are adjusted for items of income (loss), deductions, and distributions reported on Form 1120S. In this example, the corporation has no PTI or accumulated E&P. Items per return are: 1. Page 1, line 21 income — $10,000 2. Schedule K, line 2 loss — ($3,000) 3. Schedule K, line 4a income — $4,000 4. Schedule K, line 4b(2) income — $16,000 5. Schedule K, line 7 deduction — $24,000 6. Schedule K, line 10 deduction — $3,000 7. Schedule K, line 13 work opportunity credit — $6,000 1120S Sch. D (1120S) Sch. K-1 (1120S) Recordkeeping 65 hr., 45 min. 10 hr., 2 min. 16 hr., 58 min. Learning about the law or the form 25 hr., 11 min. 4 hr., 31 min. 10 hr., 36 min. Preparing the form 47 hr., 44 min. 9 hr., 32 min. 15 hr., 4 min. Copying, assembling, and sending the form to the IRS 5 hr., 54 min. 1 hr., 20 min. 1 hr., 4 min.
We Welcome Comments on Forms. If you have comments concerning the accuracy of these time estimates or suggestions for making these forms simpler, we would be happy to hear from you. You can write to the Tax Products Coordinating Committee, Western Area Distribution Center, Rancho Cordova, CA 95743-0001. Do not send the tax form to this address. Instead, see Where To File on page 3.
-30-
Codes for Principal Business Activity 1, line 1a); all other income (page 1, lines 4 and 5); income reported on Schedule K, lines 3a, 4a, 4b, and 4c; income or net gain reported on Schedule K, lines 4d, 4e(1), 4f, 5, and 6; and income or net gain reported on Form 8825, lines 2, 19, and 20a., enter the six-digit code from the list below on page 1, item B. Also enter a brief description of the business activity on page 2, Schedule B, line 2(a) and the principal product or service of the business on line 2(b).
Code
Code
Agriculture, Forestry, Fishing and Hunting
Code Animal
Utilities
221100 Electric Power Generation, Transmission & Distribution 221210 Natural Gas Distribution 221300 Water, Sewage & Other Systems
Construction
Code
-31-
Code
Miscellaneous Manufacturing 339110 Medical Equipment & Supplies Mfg 339900 Other Miscellaneous Manufacturing
Code)
Code)storage units)
-32-, & Similiar Organizations (including condominium and homeowners associations)
Management of Companies (Holding Companies)
551111 Offices of Bank Holding Companies 551112 Offices of Other Holding Companies
Educational Services
611000 Educational Services (including schools, colleges, & universities)
-33-
Index
A Accounting methods . . . . . . . . Accounting periods . . . . . . . . Accumulated adjustments account – Sch. M-2 . . . . . . . Address change . . . . . . . . . . Adjusted gain or loss – Sch. K or K-1 . . . . . . . . . . . . . . . . . Adjustments (other) and tax preference items – Sch. K or K-1 . . . . . . . . . . . . . . . . . Adjustments to shareholders’ equity – Sch. L . . . . . . . . . . Adjustments – Sch. K or K-1 . . . Amended return . . . . . . . . . . Assembling return . . . . . . . . . At-risk activities – reporting requirements . . . . . . . . . . .
. . 4 . . 4 . . 29 . . 12 . . 24 . . 25 . . 28 . . 24 8, 12 . . 7 . . 20
Electronic Federal Tax Payment System (EFTPS) . . . . . . . . . . 5 Electronic filing . . . . . . . . . . . . . 2 Employee benefit programs . . . . . 15 Estimated tax payment . . . . . . 5, 17 Estimated tax penalty . . . . . . . . . 17 Expenses, nondeductible – Sch. K or K-1 . . . . . . . . . . . . . . . . . 26 Extraterritorial income exclusion . . . . . . . . . . . . . . . 11 F Farming, special rules . . . . . . . . Final return . . . . . . . . . . . . . . Foreign taxes – Sch. K or K-1: Deductions allocated at corporate level . . . . . . . . . Deductions allocated at shareholder level . . . . . . . . Income sourced at corporate level . . . . . . . . . . . . . . . . Income sourced at shareholder level . . . . . . . . . . . . . . . . Paid or accrued . . . . . . . . . . Reduction . . . . . . . . . . . . . . Forms, other required . . . . . . . . G Gain (loss), adjusted – Sch. K or K-1 . . . . . . . . . . . . . . . . . . Gain (loss), section 1231 – Sch. K or K-1 . . . . . . . . . . . . . . . . Gain, ordinary . . . . . . . . . . . . . Gross receipts . . . . . . . . . . . . I Income . . . . . . . . . . . . . . . . . Income from oil and gas properties – Sch. K or K-1 . . . . Income sourced at corporate level, foreign taxes – Sch. K or K-1 . . Income sourced at shareholder level, foreign taxes – Sch. K or K-1 . . . . . . . . . . . . . . . . Income, other . . . . . . . . . . . . . Income, other – Sch. K or K-1 . . . Income, portfolio – passive activities . . . . . . . . . . . . . . . Income, portfolio – Sch. K or K-1 . . . . . . . . . . . . . . . . . . Income, rental activities – Sch. K or K-1 . . . . . . . . . . . . . . . . . . Income, tax-exempt – Sch. K or K-1 . . . . . . . . . . . . . . . . . . Income, trade or business activities – Sch. K or K-1 . . . . . Income – Sch. K and K-1 . . . . . . Installment sales . . . . . . . . . . . Interest deduction . . . . . . . . . . Interest due on tax payment . . . . Interest expense, investment – Sch. K or K-1 . . . . Inventory . . . . . . . . . . . . . . . . Section 263A rules . . . . . . . . Valuation methods . . . . . . . .
Investment income and expenses – Sch. K or K-1 . . . . . 23 L Loss, ordinary . . . . . . . . . . . . Loss, other – Sch. K or K-1 . . . . Loss, rental activities – Sch. K or K-1 . . . . . . . . . . . . . . . . . Loss, trade or business activities – Sch. K or K-1 . . . . Loss – Sch. K and K-1 . . . . . . . Low-income housing credit recapture – Sch. K-1 (only) . . Low-income housing credit – Sch. K or K-1 . . . . . . . . . . . . . .
. . 13 . . 21 . . 20 . . 20 . . 20 . . 26 . . 23
. 14 . 12 . 25 . 25 . 25 . . . . 25 25 25 6
Rental activities, income and expenses – Sch. K or K-1 . . . Rental activities, passive . . . . . Rental deduction . . . . . . . . . . Rental real estate activities, qualified rehabilitation expenditures – Sch. K or K-1 . Reporting requirements, at-risk activities . . . . . . . . . . . . . . Reporting requirements, multiple activities . . . . . . . . . . . . . . Reporting requirements, passive activities . . . . . . . . . . . . . . Retained earnings – Sch. L . . . . Return, amended . . . . . . . . .
. . 20 . . 8 . . 14 . . 23 . . 20 . . 20 . . 11 . . 28 . . 8
B Bad debt deduction . . . . . . . . . . 14 Balance sheets – Sch. L . . . . . . . . 28 Business start-up expenses . . . . . 14 C Change in accounting method . . . . 4 Charitable contributions – Sch. K or K-1 . . . . . . . . . . . . . . . . . 22 Cost of goods sold . . . . . . . . 13, 17 Credits related to rental activities (real estate) – Sch. K or K-1 . . . . 23 Credits, other – Sch. K or K-1 . . . . 24 D Deductions . . . . . . . . . . . . . . Deductions allocated at corporate level, foreign taxes – Sch. K or K-1 . . . . . . . . . . . . . . . . Deductions allocated at shareholder level, foreign taxes – Sch. K or K-1 . . . . . . . Deductions from oil and gas properties – Sch. K or K-1 . . . . Deductions related to portfolio income – Sch. K or K-1 . . . . . . Deductions, limitations on . . . . . Deductions – Sch. K or K-1 . . . . . Depletion (other than oil and gas) – Sch. K or K-1 . . . . . . . . Depletion . . . . . . . . . . . . . . . Depository method of tax payment . . . . . . . . . . . . . . . Depreciation . . . . . . . . . . . . . Depreciation adjustment on property placed in service after 1986 – Sch. K or K-1 . . . . Direct deposit of refund . . . . . . . Distributions, property – Sch. K or K-1 . . . . . . . . . . . . . . . . . . Distributions – Sch. M-2 . . . . . . .
M Multiple activities – reporting requirements . . . . . . . . . . . . . 20 N Name change . . . . . . . . . . . . . . 12 O Officer compensation . . . . . . . . . 14 P Passive activities – grouping . . . Passive activities – portfolio income . . . . . . . . . . . . . . Passive activities – rental . . . . . Passive activities – reporting requirements . . . . . . . . . . . Passive activities – trade or business . . . . . . . . . . . . . Passive activity limitations . . . . Passive income recharacterization . . . . . . . . Payment, estimated tax . . . . . . Penalties . . . . . . . . . . . . . . . Penalty, estimated tax . . . . . . Pension, profit-sharing, etc., plans . . . . . . . . . . . . . . . . Portfolio income, deductions related to – Sch. K or K-1 . . . Portfolio income, passive activities . . . . . . . . . . . . . . Portfolio income – Sch. K or K-1 . Preferences – Sch. K or K-1 . . . Property distributions – Sch. K or K-1 . . . . . . . . . . . . . . . . .
. 24 . 21 . 13 . 12
. . 10 . . 9 . . 8 . . 11 . . 8 . . 8 . . . . . . . . 10 17 5 17
S Salaries and wages . . . . . . . . . . 14 Sales . . . . . . . . . . . . . . . . . . . 12 Schedule L . . . . . . . . . . . . . . . 28 Schedule M-1 . . . . . . . . . . . . . . 28 Schedule M-2 . . . . . . . . . . . . . . 29 Section 179 expense – Sch. K or K-1 . . . . . . . . . . . . . . . . . . . 22 Section 263A rules . . . . . . . . . . . 13 Section 59(e)(2) expenditures – Sch. K or K-1 . . . 26 Self-charged interest . . . . . . . . . 10 Shareholder’s pro rata share, special rules: Qualifying dispositions . . . . . . . 19 Termination of interest . . . . . . . 19 Substitute Sch. K-1 . . . . . . . . . . 19 Supplemental information – Sch. K-1 (only) . . . . . . . . . . . . . . . 26 T Tax payment, depository method Tax payment, estimated tax . . . Tax payment, interest due . . . . Taxes and licenses deduction . . Taxes due . . . . . . . . . . . . . . Termination of election . . . . . . Travel and entertainment deduction . . . . . . . . . . . . . Travel and entertainment – Sch. M-1 . . . . . . . . . . . . . . . . .
. 13 . 25 . 25 . 25 . 22 . 13 . 22 . 24 . 15 . 5 . 15 . 24 . 17 . 26 . 29
. 12 . 25 . 25 . 25 . 13 . 21 . 9 . 20 . 20 . 26 . . . . . . . . . 20 20 12 15 5 23 13 17 17
. . . . . .
. . . . . .
5 5 5 15 17 2
. . 15 . . 22 . . 9 . . 20 . . 24 . . 26
. . 16 . . 28
U Undistributed taxable income previously taxed – Sch. M-2 . . . . 29 W When to file . . Where to file . Who must file . Who must sign
Q Qualified rehabilitation expenditures – Sch. K or K-1 . . . 23 R Recapture, low-income housing credit – Sch. K-1 (only) . . . . . . . 26 Related party transactions . . . . . . 14 Rental activities, credits related to – Sch. K or K-1 . . . . . . . . . . 23
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
3 3 2 3
■
E Election, termination of . . . . . . . . 2
-34- | https://www.scribd.com/document/544300/US-Internal-Revenue-Service-i1120s-2003 | CC-MAIN-2018-30 | refinedweb | 28,600 | 53.92 |
gobin is an experimental, module-aware command to install/run main packages.
gobin
The gobin command installs/runs main packages.
See the FAQ for more details.
$ GO111MODULE=off go get -u github.com/myitcv/gobin
or download a binary from the latest release.
Update your
PATHand verify we can find
gobinin our new
PATH:
$ export PATH=$(go env GOPATH)/bin:$PATH $ which gobin /home/gopher/gopath/bin/gobin
Install
gohack:
$ gobin github.com/rogpeppe/gohack Installed github.com/rogpeppe/[email protected] to /home/gopher/gopath/bin/gohack
Install a specific version of
gohack:
$ gobin github.com/rogpeppe/[email protected] Installed github.com/rogpeppe/[email protected] to /home/gopher/gopath/bin/gohack
Print the
gobincache location of a specific
gohackversion:
$ gobin -p github.com/rogpeppe/[email protected] /home/gopher/.cache/gobin/github.com/rogpeppe/gohack/@v/v1.0.0/github.com/rogpeppe/gohack/gohack
Run a specific
gohackversion:
$ gobin -run github.com/rogpeppe/[email protected] -help The gohack command checks out Go module dependencies into a directory where they can be edited, and adjusts the go.mod file appropriately. ...
-m
Define a module:
$ cat go.mod module example.com/hello
Add a tool dependency:
$ cat tools.go // +build tools
package tools
import ( _ "golang.org/x/tools/cmd/stringer" )
Review the version of
stringerbeing used:
$ gobin -m -p golang.org/x/tools/cmd/stringer /home/gopher/hello/.gobincache/golang.org/x/tools/@v/v0.0.0-20181102223251-96e9e165b75e/golang.org/x/tools/cmd/stringer/stringer
Check the help for
stringer:
$ gobin -m -run golang.org/x/tools/cmd/stringer -help Usage of stringer: stringer [flags] -type T [directory] stringer [flags] -type T files... # Must be a single package For more information, see: ...
Use
stringervia a
go:generatedirective:
$ cat main.go package main
import "fmt"
//go:generate gobin -m -run golang.org/x/tools/cmd/stringer -type=Pill
type Pill int
const ( Placebo Pill = iota Aspirin Ibuprofen Paracetamol Acetaminophen = Paracetamol )
func main() { fmt.Printf("For headaches, take %v\n", Ibuprofen) }
Generate and run as a "test":
$ go generate $ go run . For headaches, take Ibuprofen
The gobin command installs/runs main packages. Usage: gobin [-m] [-run|-p|-v|-d] [-u|-nonet] [-tags 'tag list'] packages [run arguments...] The gobin command builds, installs, and possibly runs an executable binary for each of the named main packages. The packages argument to gobin is similar to that of the go get command (in module aware mode) with the additional constraint that the list of packages must be main packages. Each argument takes the form $main_pkg[@$version]. By default, gobin will use the main package's module to resolve its dependencies, unless the -m flag is specified, in which case dependencies will be resolved using the main module (as given by go env GOMOD). The -mod flag provides additional control over updating and use of go.mod when using the main module to resolve dependencies. If the -mod flag is provided it implies -m. With -mod=readonly, gobin is disallowed from any implicit updating of go.mod. Instead, it fails when any changes to go.mod are needed. With -mod=vendor, gobin assumes that the vendor directory holds the correct copies of dependencies and ignores the dependency descriptions in go.mod This means that gobin [email protected] is a repeatable way to install an exact version of a binary (assuming it has an associated go.mod file). The version "latest" matches the latest available tagged version for the module containing the main package. If gobin is able to resolve "latest" within the module download cache it will use that version. Otherwise, gobin will make a network request to resolve "latest". The -u flag forces gobin to check the network for the latest tagged version. If the -nonet flag is provided, gobin will only check the module download cache. Hence, the -u and -nonet flags are mutually exclusive. Versions that take the form of a revision identifier (a branch name, for example) can only be resolved with a network request and hence are incompatible with -nonet. If no version is specified for a main package, gobin behaves differently depending on whether the -m flag is provided. If the -m flag is not provided, gobin $module is equivalent to gobin [email protected] If the -m flag is provided, gobin attempts to resolve the current version via the main module's go.mod; if this resolution fails, "latest" is assumed as the version. By default, gobin installs the main packages to $GOBIN (or $GOPATH/bin if GOBIN is not set, which defaults to $HOME/go/bin if GOPATH is not set). The -run flag takes exactly one main package argument and runs that package. It is similar therefore to go run. Any arguments after the single main package will be passed to the main package as command line arguments. The -p flag prints the gobin cache path for each of the packages' executables once versions have been resolved. The -v flag prints the module path and version for each of the packages. Each line in the output has two space-separated fields: a module path and a version. The -d flag instructs gobin to stop after installing the packages to the gobin cache; that is, it instructs gobin not to install, run or print the packages. The -run, -p, -v and -d flags are mutually exclusive. The -tags flag is identical to the cmd/go build flag (see go help build). It is a space-separated list of build tags to consider satisfied during the build. Alternatively, GOFLAGS can be set to include a value for -tags (see go help environment). It is an error for a non-main package to be provided as a package argument. Cache directories ================= gobin maintains a cache of executables, separate from any executables that may be installed to $GOBIN. By default, gobin uses the directories gobin/[email protected]$version/$main_pkg under your user cache directory. See the documentation for os.UserCacheDir for OS-specific details on how to configure its location. When the -m flag is provided, gobin uses the directories .gobincache/[email protected]$version/$main_pkg under the directory containing the main module's go.mod. | https://xscode.com/myitcv/gobin | CC-MAIN-2021-10 | refinedweb | 1,022 | 50.02 |
Nitish Kumar’s "arrogance" and "ambition" to become prime minister drove him to sever relations with the BJP, claims Mr. Modi
Presenting himself as a “truly secular” leader and sharpening his attack on Bihar Chief Minister and fellow prime ministerial aspirant Nitish Kumar, BJP leader Narendra Modi on Monday promised voters in the State a special development package if he came to power at the Centre.
A special package for Bihar has been a major political plank of Mr. Kumar.
Internal discord
Meanwhile, the BJP central leadership sought to play down the internal discord over the Varanasi and Lucknow constituencies, and project the party as the natural choice of regional parties and leaders.
Referring to the Gorkha Janmukti Morcha’s support to the BJP, and alluding to the expected merger of the BSR Congress in Karnataka and the likely alliance with the Telugu Desam Party, senior leader Arun Jaitley said: “These developments will add to the strength of the BJP in the eastern and southern parts of India where the party traditionally was not a strong political force.”
BJP president Rajnath Singh said the party’s Central Election Committee would decide on candidates for each constituency, including Varanasi and that “would be final.” Mr. Modi is reportedly considering contesting from Varanasi where senior leader Murli Manohar Joshi is the sitting MP. Mr. Singh, reportedly keen to contest from Lucknow, now held by Lalji Tandon, said there was no disagreement in the party over these seats.
But the BJP’s calculations hinge substantially on how the party performs in Bihar and that possibly explains Mr. Modi’s no-holds-barred onslaught on Mr. Kumar. Mr. Modi said Mr. Kumar’s “arrogance” and “ambition” to become prime minister drove him to sever relations with the BJP, and compared the socio-economic conditions of Muslims in Gujarat and Bihar to claim he practised “true” secularism. The Congress-RJD alliance was also targeted by the BJP leader, who called it a “Bhrasht-Bandhan” (corrupt alliance). He said even cows and buffaloes were afraid of it as it may deprive them of their food, a reference to Rashtriya Janata Dal leader Lalu Prasad’s conviction in the fodder scam.
Mr. Modi ridiculed the third alternative, of which Mr. Kumar is one of the prime movers, calling it “a ‘Toli’ (group) of ex-Prime Ministers and more than a dozen PM hopefuls who wake up at the sound of elections and go to sleep for the remaining period.”
The Gujarat Chief Minister chose the recent comments of Mr. Kumar that he had more experience than others to be prime minister to attack him. “Why was the BJP-JD(U) alliance broken? Some said it was his [Mr. Kumar’s] habit to stab in the back ... We came to know of it four days ago. The dream to become PM was not letting him sleep. His arrogance is higher than Mount Everest. He says nobody is as good a PM candidate as him,” he said.
(With inputs from PTI)
The congress Vice- president Rahul Gandhi is the face of tomorrow. He
has all the qualities of being a good leader. The nation will give him
this chance in this election to make a drastic change in India. He
actually knows how to make effective measureable change to the nation.
India needs a face like him.
BJP should start doing some good work so that people can also evaluate
the same. It will not benefit them to try to downgrade others. They can
not win elections this way.
Welcome to Kutch Gujarat Mr. Kejriwal.
Nice to know that you want to survey the
developmet of Kutch.
So let we the people of Kutch Brief you
with few facts.
Kutch has the population of 18 lac that is
1% of UP,
but
produces 12,000 MW power and total will
be 27000 MW by 2018.
To put this number into perspective
Australia
produces 30,000 MW power in spite of
being the worldâs largest per capita power
consumer and having population 11 times
that of Kutch !!!
and this will be 35 %
more than whole of Pakistan with
population 100 times that of Kutch.
Kutch is in the process of becoming the
largest cement
producing district by far of India.
Kutch is going to produce 10% of potash
in a yearâs time
which is key ingredient of fertilizers.
Unfortunately in spite of India being
agriculture based country we almost
import 100% of potash, and this import
will be reduced due to plant being put in
Kutch that will provide direct benefit to
every farmer
of India.
Kutch is the largest windfarm power
producing disctrict in
India.
Kutch is 3rd largest area producing Saw
Pipes in
the world, which are used in oil and gas
piping.
Kutch handles maximum sea cargo in
India and is home to two
largest port of India.
Kutch has the largest edible oil refining
capacity in India.
Kutch has the largest number of saw mills
of wood in India,
in spite of not having any forests.
Kutchâs tourism has developed by 1200%
in 7 years and that
too majorly in Muslim majority areas.
Kutch being the desert region with no
water for 5 decades
now receives drinking water directly from
Narmada which has reached right upto
the border for BSF jawans.
Kutch is the district with largest road
network in India.
And these all things have happened in
front of our eyes and
the time when Kutch was reduced to
rubbles due to one of the most severe
earthquakes of India in 2001.
If you are unbiased and really want to see
the development
hopefully you will appreciate these things,
that will give you a bigger stature among
we the people of Kutch.
We are known for our warmth &
hospitality,of course u need to open your
arms too, which is not likely to be done as
you are in TOO much hurry"
-
It's another a good joke by the Modi. All party are doing vote bank
politics which is not good for the nation. BJP party is the best party
in the politics. I think, The whole world knows who is trying hard and
even ignoring party senior most leaders to become Prime Minister. Modi
is the corrupt the people.
No doubt ,its a big joke which Modi expressed to the voters that he has
a special package for the nation's development if power is owned by him
after winning the elections.We better know who is spokesperson no one
rather than Modi. Arun Jaitley commented oh this phrase that this
special development will give strength to the BJP people and will grow
much.
Dreaming of PM is not only Modi's patent.Like Modi's Gujrati-ism,
Nitish Kumar too stands for Bihari sub-nationalism, a state having
10.5 crores people, nearly double the Gujrat.Bihar's rich historical
past, a centre of international learning, makes it a cultural Republic
of India (mind ) and heart of country's geography.Nitish Kumar is
secular leader and a maker of New Bihar from the ruins. He is both
business friendly and pro-people.His is inclusive, coalitional and
accommodative leader who is most fit for country's era of coalition
politics. His economics of development blends growth with justice
largely based on Nobel laureate Sen's Human development Index concept.
On the contrary, Modi's secular image raises many queries.He is
exclusive, aggressive and megalomaniac like Indira Gandhi.Imagine
Indira Gandhi running a coalition government.His development model is
pro-business and growth obsessive based on economist Bhagwati's
concept, making Ambani and Adani world's richest.
While ambition to become PM is not by itself a bad thing, nor inapplicable to Modi himself, there may be an iota of truth in his accusation against Nitish.
Nitish had no problems continuing in the NDA ministry after 2002 and standing on the BJP's shoulders all this while, even milking the BJP's vote-share to be elected CM of Bihar twice. Suddenly, when Modi is declared the BJP's PM candidate, his 'secular' conscience awakens and he breaks a 17-year-old alliance.
The big giveaway? Nitish's self-attestation of himself as the best PM candidate of all. Even before Modi's anointment, some JDU leaders made noises in favour of Nitish over Modi. Was that without a cue?
The biggest party in a national electoral alliance nominates its most successful state chief minister - and by all accounts clearly the most popular of all political figures nationally - as PM candidate. What was ever the shock there?
Is there any rule that India must have only dynasty rule. Why
no one from Congress talking about Lalji Sri Rao for their
administration. If the communists and Congress talk of secularism
why not Modi. Congress is in hand with Muslim league in Kerala
and where is secularism. On counting day we know where our
people stand.
I do not find any point in sheer illusion of Mr. Kejrival who is constantly manipulating sentiments of deluded public of India. Modi has done miraculous administrative and infrastructural improvements which is better than any promise as it's based on ground facts. Mr. Nitesh is striking because of contrary effects of Laluji. The only option remains is Modiji who's a mature leader.
I have been watching for long Mr. Modi's demagogic style of politics. His caliber and bars qualify him for a third-rate politician. He is a distilled power-monger. If by chance he were elected as PM, he would prove to be the worst one that we have ever had. Owe to the Nation for such an arrogant foolhardy aspiring for headship. It is a waste to talk about a bankrupt politician.
Modi is reading the writing on the wall, and the writing is BJP will not get majority to form the government due to AAP, so he is forested and started stupid comments like Rahul is from Mars, Nitish is dreaming to become PM.
What a Speech and correct root cause for the exit of Nitish Kumar...!
To be frank, I was not a modi supporter and even had negative feel on
him. But now it is time to have a leader who is able and who got a good
team to execute development. He has been doing it in Gujarat. I'm from
Kerala, I can see people from different community having an inclination
towards BJP because of development in Gujarat. Christians in Kerala had
already extended their support to Modi. Let us give him a chance! Jai
Hind!
Nitish Kumar's remarks abuting his desire to become the Prime Minister of India are not so dreadful in the context of India's religious divide. It is Mr. Modi who has to come clean on his views on women's emancipation, Article 370 of the Constitution, casteism that is extant socially throughout the country, plight of Sri Lankan Tamils, FDI (Foreign Direct Investment) in retail.
Let Mr Modi answer Mr Kejrival's questions first. The Congress has been a total
failure and in currently in total disarray. India needs a real change. The people need
to give AAP a chance to see real change
This is truly the pot calling kettle black. It's purely psychological in the case of Modi. I
am sure Modi is losing sleep and probably he has run the most expensive campaign to
buy people showing some stupid model of Gujarat. I pity the guys who will vote for
him. This country will never be the same if he becomes PM. Nitish is a gentle man and
Rahul is still better. Rahul is more an Indian than Modi or Kejriwal. The behavior of
Modi and Kejriwal does not deem fit for those who want to be PMs of this country.
The online army of Modi could very well be the reason for them losing
thousands of votes. People can see through propoganda and Truth. It is
funny and surprising how Modi is conspicuously silent on 17 questions
raised by Kejriwal while he wonders about Rahul not answering his.
BJP with its blatant acts of giving seats to yeedyurappa has shown that
they along with Congress are two sides of the same coin.
But then sri Modi's march to get the PM post is making most of India
loose their sleep!
Mr. Modi speaks from first hand experience... he has been losing sleep
due to his Prime Ministerial ambitions as well!
BJP should start doing some good work so that people can also evaluate
the same. It will not benefit them to try to downgrade others.
This gathering of self serving politicians wants power to sell away the country's
prestige. NaMo wants to become PM to visit USA. He felicitated US ambassador when
he went to meet him. US ill treated a dalit IFS officer, ignoring her diplomatic
immunity. Modi has no respect for Dalits, Muslims and honest people. He didn't
extend the same courtesy that he extended to the US ambassador to Arvind Kejriwal
an ex-CM from Delhi. His group now has LJP leader Ram Vilas Paswan who once left
NDA in opposition to the massacre in Gujarat. Ram Vilas is now probably afraid of the
Ravan in Gujarat.
To dream about being Prime Minister is the exclusive right of Modi! It
is 'unethical' for any body else to dream so!!
Nitish kumar walked out of NDA thundering that secularism is above everything else. Now, he is saying that he is a more fit PM. This has exposed that secularism is a farce enacted by congress and fringe parties simply to enjoy power through hook or crook
t looks as if both Mr Narendra Moti and Mr Nitish Kumar have been spending
sleepless nights, fearing nightmares from each other. After exhausting his
repeated remark about "Shehzada", Mr Modi is now after Mr Nitish Kumar, who
after being snubbed by Congress is claiming his credentials better than Mr Modi
for the PM's job. Mr Modi hasn't answered the direct questions posed by Mr
Kejriwal regarding gas pricing and who is paying for his helicopter rides etc. Same
is case with Mr Rahul Gandhi,whereas Mr Kejriwal has answered all questions
directly without ducking. What is clear so far is almost everyone including Mr Modi,
Mr Rajnath Singh, Mr LK Advani, Ms Shushma Swaraj, Mr Rahul Gandhi, Mr Nitish
Kumar, Ms J Jayalalithaa, Ms Mamata Banerjee, Mr Mulayam Singh Yadav and not to
forget Mr Sharad Pawar are interested in becoming Prime Minister, even if it is for a
single day, the idea being they would go down in history in the chain of Prime
Ministers of India. Probably, it was only Mr Devi Lal who refused the post after
being elected, as he reportedly felt unsure to do justice to the job of PM.
Modi is hitting the same stones except that he has forgotten Pakistan. His 'hittings' only make news rather than any concrete plan for the people; it appears he is confident of running a govt by hitting opponents all through.
how ridiculous , it is you mr narendra modi who is trying his best to
become prime minister, and u are making people fool by your false
propaganda of Gujarat development.
The CM of Bihar is trying very hard to improve Bihar which is one of the poor state of India .It may take a long time to achieve results. Biharis thought that Lallu from their own rank will do them good and wasted one decade on him with no change in the state of affairs. If Mr. Nitish Kumar wanted to be in the lime light he should have come out of Bihar and made alliance with other parties long back . He has even thrown himself out from the only alliance he had . His only choice now is to improve Bihar in the next five years and try for national recognition.
At present, We need strong leadership irrespective of any party but
it require clear mandate of the people and only one party should have
that mandate otherwise we waste another quinquennium. Our demographic dividend should be made our Asset and not a liability. Youth of India
would be much deciding factor as he has so much aspiration.
It is a good joke. The whole world knows who is trying hard and even ignoring party senior most leaders to become Prime Minister.
Mr. Modi give chance to Mr.Advani and sleep well, can you do that?
Mr Modi,
Off course Nitish has better credential than that of yours. Please
answer the question of Mr Arvind Kejriwal if you do not have
anything to hide. Sadly no one is buldozing your false propganda of
development and seems whole word is being made to believe this
falsehood.
Dear Modi,
Nitish Kumar did not allow you and varun gandhi to campaign earlier
when he was in NDA. His views are consistant and clear than LJP
paswan. If he had a dream to become PM (and you did not) then you
could have allowed him and save the alliance...
We need a strong leader like Modi to bail us out of this current mess created by the Congress. AAP is no longer an option. They are acting as a B-Team of Congress and are now fully exposed. Suddenly, Communalism has become a bigger issue than Corruption for Kejriwal.
Modi himself is dreaming of being PM, so what is wrong if other person
does so? Is it sole right of Modi? By the way Mr.Modi, how can you call
yourself CM of Gujrat when you don't even stay there now. You are always
outside campaigning. Shouldn't you have resigned before canvassing?
"Even cows and buffaloes are afraid of it as it may deprive them of their food" I like this, funny part is Shehzaadeji and his group is still supporting this ...
I don't think Nitish Ji is even good for a CM - forget about PM roles. Bihar development has not been as expected. Corruption is very much healthy in the Govt offices. People still rush to CMC vellore for affordable and good treatment...Migration for job is as high as it was earlier. Modi Ji has done much more than Nitish Ji. But at any time, Nitish Ji has done a good job with insfrastructure and law condition in Bihar if compared with Lalu Ji.
Modi calls Rahul Gandhi,the prince.In fact the prince wears ordinary clothes and mixes well with the common even though he did not sell Chai. Modi since the time he has come to the office,looks as if he has come out of the green room with those colored suits and neatly made hair style.In democracy every man is a prince and and every woman is a princess in their own ways even though they do not wear clothes designed by designers and make their hairdos..
Dreams are not those which comes to your mind during sleep, real dreams are seens through open eyes. Real dreams are those which donot let you sleep during night. Nitish kumar has changed the face of Bihar and he has all the capability to be a national level leader. i think Nitish kumar is more fit to be PM.
Dear Friends after seeing your comments, we have a feeling that the things you say is all out of blind hate towards Modi. Its time we talk about development & stop talking about secularism. Enough of talking about secularism, its only because Hindu's were secular other religions came up in this Nation. What ever you say now the pulse of the Nation say...we need a Strong India & this is possible only when we have strong & able leaders. And in Modi people find a leader who can make all this happen....be a proud Indian...!
Modi's lies and exaggeration on his state 'development and achievements' have been exposed now by Arvind Kejriwal. Besides, one can personally witness the reality when we go into the rural areas of gujarat, where basic necessities and infrastructure development cries for attention.
One can tolerate with an under achiever, but not with a lier. If Modi can dream and aspire to be a PM of this country, why not Nitish, who is well qualified in academics and governance. Modi is yet to come clean on the source of funds for his extravaganza public meetings and air trips. Its an open secret here that ambanis and reddy brothers have dumped tons of money in BJP coffers for this elections.
BJP is trapped in its own whirlpool of Yeddyurappa, reddy brothers and ambanis. I am just amazed to see the kind of morality BJP has to criticize and condemn other people, when their own house is mired with corruption, neoptism and communal card.
Congress party is a spent force. The ray of hope is AAP.
Modi are you responsible for your rule in Gujarat? Are you responsible
for the Genocide of the Muslims? Are you responsible for poor condition
of the farmers, Dalits and the Marginalised? Are you responsible for the
price rise of Gas,Petrol and diesel in connivance with Reliance and
Ambani? Are you responsible for the Environmental Destruction due to
Mudra and Sardar Sarovara Projects?
Modiji you call Rahul as Shehzaada (prince). Do you think you are bigger than Nitish
Kumar who turned Bihar round from a lawless state to one with the highest
development rate in India. You took 15 years to turn Gujarat into a monolithic edifice
built on falsehood and threats.
Look into yourselves before speaking about others.
Modi is accusing Rahul of not answering his questions. Dear Modi, What
about those written questions posed to you by Mr. Arvind Kejriwal ?
Please Email the Editor | http://www.thehindu.com/news/national/nitishs-pm-dream-not-letting-him-sleep-modi/article5770117.ece?homepage=true | CC-MAIN-2014-52 | refinedweb | 3,639 | 63.8 |
Iter IO¶
This module implements a
IterIO that converts an iterator into
a stream object and the other way round. Converting streams into
iterators requires the greenlet module.
To convert an iterator into a stream all you have to do is to pass it
directly to the
IterIO constructor. In this example we pass it
a newly created generator:
def foo(): yield "something\n" yield "otherthings" stream = IterIO(foo()) print stream.read() # read the whole iterator
The other way round works a bit different because we have to ensure that
the code execution doesn’t take place yet. An
IterIO call with a
callable as first argument does two things. The function itself is passed
an
IterIO stream it can feed. The object returned by the
IterIO constructor on the other hand is not an stream object but
an iterator:
def foo(stream): stream.write("some") stream.write("thing") stream.flush() stream.write("otherthing") iterator = IterIO(foo) print iterator.next() # prints something print iterator.next() # prints otherthing iterator.next() # raises StopIteration
- class
werkzeug.contrib.iterio.
IterIO¶
Instances of this object implement an interface compatible with the standard Python
fileobject. Streams are either read-only or write-only depending on how the object is created.
If the first argument is an iterable a file like object is returned that returns the contents of the iterable. In case the iterable is empty read operations will return the sentinel value.
If the first argument is a callable then the stream object will be created and passed to that function. The caller itself however will not receive a stream but an iterable. The function will be be executed step by step as something iterates over the returned iterable. Each call to
flush()will create an item for the iterable. If
flush()is called without any writes in-between the sentinel value will be yielded.
Note for Python 3: due to the incompatible interface of bytes and streams you should set the sentinel value explicitly to an empty bytestring (
b'') if you are expecting to deal with bytes as otherwise the end of the stream is marked with the wrong sentinel value.
New in version 0.9: sentinel parameter was added. | http://werkzeug.pocoo.org/docs/0.12/contrib/iterio/ | CC-MAIN-2018-13 | refinedweb | 366 | 56.96 |
AUDIT_GET_SESSION(3) Linux Audit API AUDIT_GET_SESSION(3)
audit_getloginuid - Get a program's login session id value
#include <libaudit.h> uin32_t audit_get_session(void);
This function returns the task's session id attribute.
This function returns the session id value if it was set. It will return a -1 if the session id is unset. However, since uint32_t is an unsigned type, you will see the converted value instead of -1.
This function returns -2 on failure. Additionally, in the event of a real error, errno would be set. The function can set errno based on failures of open, read, or strtoul.
audit_getloginuid Dec 2016 AUDIT_GET_SESSION(3) | http://man7.org/linux/man-pages/man3/audit_get_session.3.html | CC-MAIN-2017-30 | refinedweb | 105 | 60.41 |
14.4. Computing connected components graph theory in image processing. We will compute connected components in an image. This method will allow us to label contiguous regions of an image, similar to the bucket fill tool of paint programs.
Finding connected components is also useful in many puzzle video games such as Minesweeper, bubble shooters, and others. In these games, contiguous sets of items with the same color need to be automatically detected.
How to do it...
1. Let's import the packages:
import itertools import numpy as np import networkx as nx import matplotlib.colors as col import matplotlib.pyplot as plt %matplotlib inline
2. We create a 10 x 10 image where each pixel can take one of three possible labels (or colors):
n = 10
img = np.random.randint(size=(n, n), low=0, high=3)
3. Now, we create the underlying 2D grid graph encoding the structure of the image. Each node is a pixel, and a node is connected to its nearest neighbors. NetworkX defines a
grid_2d_graph() function to generate this graph:
g = nx.grid_2d_graph(n, n)
4. Let's create two functions to display the image and the corresponding graph:
def show_image(img, ax=None, **kwargs): ax.imshow(img, origin='lower', interpolation='none', **kwargs) ax.set_axis_off()
def show_graph(g, ax=None, **kwargs): pos = {(i, j): (j, i) for (i, j) in g.nodes()} node_color = [img[i, j] for (i, j) in g.nodes()] nx.draw_networkx(g, ax=ax, pos=pos, node_color='w', linewidths=3, width=2, edge_color='w', with_labels=False, node_size=50, **kwargs)
cmap = plt.cm.Blues
5. Here is the original image superimposed with the underlying graph:
fig, ax = plt.subplots(1, 1, figsize=(8, 8)) show_image(img, ax=ax, cmap=cmap, vmin=-1) show_graph(g, ax=ax, cmap=cmap, vmin=-1)
6. Now, we are going to find all contiguous dark blue regions containing more than three pixels. First, we consider the subgraph corresponding to all dark blue pixels:
g2 = g.subgraph(zip(*np.nonzero(img == 2)))
fig, ax = plt.subplots(1, 1, figsize=(8, 8)) show_image(img, ax=ax, cmap=cmap, vmin=-1) show_graph(g2, ax=ax, cmap=cmap, vmin=-1)
7. The requested contiguous regions correspond to the connected components containing more than three nodes in the subgraph. We can use the
connected_components() function of NetworkX to find those components:
components = [np.array(list(comp)) for comp in nx.connected_components(g2) if len(comp) >= 3] len(components)
4
8. Finally, we assign a new color to each of these components, and we display the new image:
# We copy the image, and assign a new label # to each found component. img_bis = img.copy() for i, comp in enumerate(components): img_bis[comp[:, 0], comp[:, 1]] = i + 3
# We create a new discrete color map extending # the previous map with new colors. colors = [cmap(.5), cmap(.75), cmap(1.), '#f4f235', '#f4a535', '#f44b35', '#821d10'] cmap2 = col.ListedColormap(colors, 'indexed')
fig, ax = plt.subplots(1, 1, figsize=(8, 8)) show_image(img_bis, ax=ax, cmap=cmap2)
How it works...
The problem we solved is called connected-component labeling. It is also closely related to the flood-fill algorithm.
The idea to associate a grid graph to an image is quite common in image processing. Here, contiguous color regions correspond to connected components of subgraphs. A connected component can be defined as an equivalence class of the reachability relation. Two nodes are connected in the graph if there is a path from one node to the other. An equivalence class contains nodes that can be reached from one another.
Finally, the simple approach described here is only adapted to basic tasks on small images. More advanced algorithms are covered in Chapter 11, Image and Audio Processing.
There's more...
Here are a few references:
- Connected components on Wikipedia, available at
- Connected-component labeling on Wikipedia, at
- Flood-fill algorithm on Wikipedia, available at | https://ipython-books.github.io/144-computing-connected-components-in-an-image/ | CC-MAIN-2019-09 | refinedweb | 645 | 58.99 |
.
Everything.
I think you guys are too pessimistic to lose the hope.US is still the greatest country ever and it will be ,Only US is the brain of this world which decide where we will go and how , and East Asian counties is the heat of this world just providing power and energy.Then US died ,this world will become a walking dead.I'm sure US will find another way to boost like US did in 80s last century that birng IT indsutry to this world also at the same time creating giants like Microsoft ,google ,apple,facebook which is now supporting US as the leader.Trust your People and trust your intelligence and trust your future.somebody can learn something from you like technology but they can not copy your soul and your brain which is the right thing prompting this world proceeding.GOD bless America and please be filled by hopes and confidence!Cheer UP
A 2% inflation rate is an absolute joke to anyone who shops in this country. The federal government is lying.
That's because the U.S. Government quotes the consumer price index (CPI) which is a joke of a statistic as it doesn't factor in energy costs and groceries. A much more accurate figure that the Government conveniently ignores is the Everyday Price Index (EPI), which does include price fluctuations in such vital consumer items. CPI is indeed only 2%, whereas the much more realistic EPI was 8% in 2011.
"Policymakers do not embrace this scenario"..."Other countries’ experience suggests he (Bernanke) may be wrong."
I do not believe there is any doubt Mr. Bernanke is wrong. His position, and that of most on the fed's board, is convenient. And as morose as the outlook seems, it makes their take on the economic situation very optimistic. In the papers I read, writers seem to buy in to his view, because they sound as if they are expecting a normal recovery. Either that or they are lamenting the fact it hasn't happened as expected.
I do not think it is going to happen. In fact, if it were, it would already have happened. No, there are several developments interfering with it. For one, although U.S. companies still have Research and Development budgets, much of the benefit of such activity has gone into technology to make manufacturing more efficient and, therefore, more productive. And what cannot be made more productive - and sometimes even that which can - (that which you normally would expect to benefit American workers), has been been moved off-shore to China, India, Taiwan, South Korea, etc. and/or stolen by them.
You might be saying to yourself "Well, Ben Bernanke is smart enough to have taken note of this" and he very probably has. But his number one priority for the last several years, regardless of what he may say, has been to boost the value of equities to at least make some Americans "feel richer".
I believe America has been living in La La Land since the end of WWII, after which, Europe and Asia was almost totally destroyed. They then turned to America to help rebuild their industries and infrastructure (the Marshal Plan among other things). America, one of the few countries not decimated by the War, benefitted substantially. Well, that is no longer true. In fact, it hasn't been the case for several decades.
Also, correlate the growth of deficit spending and the unfavorable balance of payments America has accrued since WWII, and you begin to suspect that America's post-war prosperity was in large part the result of deficit spending, not a healthy and vibrant economy.
It is possible, and I think probable, that the real world, and real world Economics, has finally caught up with Old Uncle Sam and that Americans are in for a rude awakening. If you look, you can see it all over the country. Whether you notice it or not is colored by what you're looking for.
Americans have a tendency to get caught up in tertiary causes such as Snail Darters, Spotted Owls, The War On Women, Gay Rights,etc. They haven't yet gotten down very far on Maslow's Pyramid of Human Needs. That may take awhile.
The question I would ask is this: Will American politicians, in an attempt to escape all the grizzling and static caused by the reality setting in, float another bubble or two, just to again postpone the inevitable?
@ Straight-Arrow Not Many comments as realistic as this. I believe our economy could recover if we weren't at the mercy of the Military driven industry. Ask bill gates how he got started.
Once Romney is president everything will be fixed in months.
FACT: Cutting spending creates jobs and creates growth
FACT: Lower taxes on the rich means they spend more and thus produce jobs - they are the job creators NOT Obama!
FACT: Socialized medical care destroys economies
FACT: The EPA is destroying the American energy industry
Well, marking your opinions as FACTS doesn't make them so. These are facts only when supported by verifiable data. Please provide them if they are available, otherwise put in a disclaimer that these are your opinions and not verifiable facts.
Lol, your facts are anything but.
- Cutting spending? How's that working out in Europe? Not well. Those spending cuts are also directly responsible for 100's of thousands of local gov't jobs lost (teachers, first responders, etc). Austerity didn't work out well in the late '30s either, did it?
- Lower taxes on the rich just means they have more money - they don't create jobs, they just collect money. Businesses (large, not small) create most jobs, not rich people.
- Socialized health care does not destroy economies - if it did Europe would have been in perpetual depression for decades.
- You think it's better for 1,000's of people to die prematurely from polution? Really?
.
Your fact-less statements of "fact" are nothing more than talking point lies that conservatives seem to think will become true if repeated enough (or, at the least, people will believe the lies).
I am sorry to disagree, as WIIAN mentions, your opinions are not necesarily true (it really depends on the circumstances). Let's go one by one:
Fact 1: Depends on where you cut spending... If you do so in areas where such spending is supposed to encourage a larger demand, well most likely you'll get the opposite effect. So where does Rommey plan to cut spending?
Fact 2: "The trickle down theory"... It really depends on how the rich guys see the future. If they believe that the situation will not get better, they will not spend or invest. In such case they will save their money or invest somewehre else.
So, how do rich guys see America's future?
Fact 3: It doesn't necessarily do so. It really depends on how you fund the system and if you can forecast the type of health services and population behaviour appropriately. Most of the current systems did not take into account a larger life expectancy and an aging population. That is why they are going bankrupt.
Fact 4: We have to focus on sustainable economic growth. I fall resources are consumed in order to avoid a deaccelartion in the short term economic growth, our children will be loooking at a bleak future.
Enviromental protection laws and policies may decrease current economic growth in the short term, but in the long term they may assure a more robust economic growth, which can be sustainable.
Of course, the idea is not to strangle the industry but to make sure they take into account externalities (social costs which they are currently not paying for, but which they cause).
Of course these are just my thoughts...
Well said Caelestis. The amount of opinions and unreasoned arguments that pass for facts these days is appalling. Obama will win in November, and hopefully, some day, the conservatives will realize that the world is a lot more complex than they would like it to be.
Ok, I'm sorry to have to inform you guys but.. you're all completely brainwashed by the left wing media.
Fact 1: We went into depression as government spending went through the roof thanks to Obamacare and the car manufacturing bailout
Fact 2: I think we all reasonably agree on this. Obviously if people become more rich they spend more as a consequence.
Fact 3: European nations collapsed because they spent to much on social welfare programs like health care. That's why they are all cutting spending now. They have to learn to live within their means like normal everyday people.
Fact 4: The EPA is holding back the shale gas industry from fully prospering. Look at a company like Chesapeake, whose stock price has collapsed since Obama took office.
lol, if the media has a liberal bias it's only because reality does as well.
1. We didn't go into a depression, just a bad recession due to the greed and bad decision making of bankers and others in the financial industry.
2. "I think we all agree" is generally used at the beginning of a sentence that most people do not, in fact, agree with. Rich people don't actually spend a lot more than middle class folks on a day to day basis, just the occasional big purchase.
3. lol, no, the problem is their banks were more stupid than US banks and gambled more on riskier things (or just got hornswoggled by US bankers). You claim that healthcare is strangling Europe, even though they (ALL European nations) spend less per capita than we do, and amazingly get better outcomes as well. Perhaps it has something to do with no profit motive - there should never be a profit motive in healthcare, or you end up with the absolutely horrid system we have in the US (pay more, die sooner).
4. We have a glut of natural gas production causing prices to plummet - learn to supply and demand.
Dear Conservative Thought,
I am sorry but I don't think that we have been brainwashed by left wing media. We just think differently from you. And I believe you should be careful making those sorts of accusations, because then you could be accused of being brainwashed by the right-wing media...
Going back to the discussion:
Fact 1: American government spending went through the roofs due to the country entering into two wars at the same time (Pre-obama time). Depression satrted before Obama became president. The large deficit was caused due to high military spending and low government income (mr. bush's tax cuts).
The car manufacturing bailout was responsible in part but it's just a "spot shock" while the war spending is continuous.
Fact 2: I told you, it really depends on how people see the future. If they think that things will not go well, they will not spend more but save for the "darker" times. Also, it depends on where they spend their money. For example, if American rich people invest in China, it will help less America compared to if they invested their money IN America.
I also agree with supamack: medium and small businesses are the real creators of wealth in a country. I think we should worry more about America's medium class instead of it's high class.
Fact 3: This is a very big discussion. Remember that European economic depression was a disease which it caught from America (world depression started there). It is true that you cannot live beyond your means for very long, but that doesn't mean a country can't have a healthcare system. As I told you, it depends on how you fund it...
Fact 4: I am not sure if this may help to calrify my position: Imagine you are running a marathon. If you run as fast as you can at the very beginning, you won't have enough stamina to finish the race.
I believe EPA is like a regulator, which will make sure that there is enough stamina to keep running at every point in the race.
Don't worry about the shale gas industry. Since we need the energy source, it will keep growing...
What's funny Conservative Thought is that I thought your original post was sarcasm. I was ready to point that out until I read your second post.
In regards to "Fact 1" We've spent very little on Obamacare, most of the spending doesn't start until 2014. Also, how can some $50 billion in auto bailouts, which the government will recover in-full, possible bankrupt a country that spends over $600 billion a year on defence?
"Fact 2" Rich people do not spend no more as a "consequence" to being rich. At best, spending is a benefit of being rich, not a consequence. Also, it has been shown that spending as a fraction of income, decreases as people accumulate wealth.
"Fact 3" Europe is in trouble because too much credit was offered to them at too low a price(interest). While all governments need to spend within their means, its clear now that the rabid austerity forced on them has slowed growth and actually made the situation worse.
"Fact 4" American natural gas is the cheapest in the world thanks to fracking. Cheap gas is reducing oil refining costs so low that the US is now a net gasoline exporter. The misfortunes of one company (Chesapeake) are not indicative of the entire industry.
Ok, I'm sorry to have to inform you Conservative Thought but... you are completely brainwashed by the right wing media.
The problem is the demand is depressed by the gap in income when 1% of the population controls 50% of the national assets: it leads to imbalance in demand when instead of 300 million consumers there are actually two: 297 million people on one side and 3 million (1% of the total) on the other. The solution is nothing short of revolution: redistribution of income.
Trillions will be just sitting on the rich balance sheets unless the dude is pasturised..
The only thing supply side economics proved is that it doesn't work, and it proved that decades ago. The 1% don't create any jobs. at all. Businesses create jobs, not individual tax payers. Most of the 1% do nothing but sit on their butts all day collecting under-taxed investment income. You know what actually happens when income inequality gets too high? Revolution.
I bet you think Ayn Rand actually had something worthwile to say (she didn't) but she was just really butthurt about the Soviet revolution and wrote a really bad book about her feelings - Atlas Shrugged. The main problem with her thinking is that those "captains of industry" don't actually do anything productive. They pay others to do the actual productive work. The 99% keep the country running, and do ALL the work. If Ayn's vision came to life you know what whould happen? The industrialists would starve to death because they can't actually take care of themselves while in the real world others would simply take their place and life would go on as if nothing had happened.
Conserative Thought,
It was supply-side economics and fraudulent practises that gave cheap credit to American home buyers. It was also supply-side economics that gave us TARP the purpose of which was to stablize the bank's risk portfolio so they would start lending again. They didn't resume lending and instead sat on the money. Meanwhile, the homes of people to whom these very same banks should not have lent money were foreclosed. This has depressed home values driving people, who could overwise afford their homes, to walk away from them, further depressing home values, main source of wealth for the middle-class. Without this wealth to tap, or even the peace-of-mind it affords, demand has suffered.
Supply is pointless without demand. Indeed its demand that provides a market in need of being supplied. Build an economy with healthy demand and supply WILL follow. However, if you try to build an economy with healthy supply and an ever decreasing demand from a stagnant middle-class, recessions are sure to follow.
I'm sorry sir, but you are misinformed..
The economy is now firmly anchored on the gambling by the likes of JP Morgan, Goldman etc. to bet by skirting the lax regulatory regime on 300 Trillions worth of Derivatives and Derivatives on derivatives trades. Huge profits can be generated by successful bets, and it is to be expected that tax-payer money will be used again to bail out too-big-to-fail entity.
One of the worst and most recovery-limiting problems in America, is how this crises has both traumatized the American people, and left many tens of millions of them as debt slaves to America's morally corrupt banking industry..
Your people are traumatized, and the greedy ones who did it to them are still doing it to them at great profit to themselves.
Disgusting.
I would easily argue against the IMF's reasons being what is undercutting America's growth. Rather I'd easily see it as the increasing reliance on a globalized economy having dragged down any potential for a larger rebound.
For the first, the crises has driven up demand for higher education across a broad age range and spectrum in US. The per capita rate of people in college, and graduating with higher level degrees, is higher than ever in America. For whatever reason the American population has responded to the crises in one of the best ways it could, and so "lack of innovation" and "job skills" in a non-issue as far as labor is concerned in America.
But since the early 90's America has become ever more reliant on international trade in any number of areas. And with China looking wobbly and lowering its forecasts, India having "wobbly" as an optimistic outlook, and Europe in another recession and bickering with itself is it any wonder that the recovery has been stolid?
The one idea I would agree with is that capital has dried up in America. Banks sit on mounds of capital, weary of regulators and bad press, and without much inflationary pressure or competition to worry about. Venture capital funding is down due to worries about economic conditions globally, IPO's are down due draconian legislation, and corporate issued bonds aren't as attractive compared to the many countries still having debt finance their budgets, still considered safer even after the crisis in Europe.
I'm afraid the high per capita rate of people in higher education is very much a part of the problem of "lack of innovation" complained about in the article. One must consider the huge number of economically superfluous liberal arts degrees being handed out by large second and third tier universities and colleges. Plus, the huge number of newly minted law degrees that are also surplus to the true demand for legal services in the economy. The problem of useless university degrees has a counterpoint in the chronic shortage of engineers and scientific and technical professionals the country suffers under.
Over the last three decades China's government has managed its economic growth to a much greater extent than the predominantly laissez-faire U.S. During that time we have mostly stood by criticizing, belittling, and predicting their imminent demise. Tools utilized by their government and mostly ignored by us include identifying areas and sequence of strategic focus, setting national goals, providing subsidies and loans, encouraging partnerships with leading foreign firms and mandating their sharing technology and R&D with local Chinese partners, use of tariffs to protect nascent ventures, 'pushing out' various Chinese firms to establish facilities in other nations, discouraging excessive competition, making massive infrastructure investments, assuring the reliable availability of natural resources and energy, avoiding contentious foreign policies, granting special tax exemptions for favored actions, carefully controlling the value and international availability of its currency, limiting union power, focusing government on improving the economy (eg. vs. the military, the environment), improving K-12 and college/university education, luring its Western-trained PhDs to return (over 80,000, mostly in the last five years), and helping fund the foreign educations of tens of thousands of its citizens. Conversely, the U.S. government either has not utilized these tools, or has done so to a much lesser extent.
It's long past time for us to drop our biases and ideological blinders, focus on substantially improving economic growth, utilize data-driven decision-making, and try to learn from others all around the world - starting with China. That's almost exactly how China's economic transformation to rapid economic growth began
China's "growth" has been puffed up tremendously by "bridges to nowhere" -- infrastructure projects that will yield no return. I don't know what predictions of doom you're thinking of, but the ones that I've heard are mostly based on this.
It's actually pretty funny to think of another country deciding to imitate China -- they've been "succeeding" by your standards for quite a while now; do you see any other government enthusiastic about their model? Wonder why?
'Infrastructure projects that will yield no return' - perhaps, though with some 350 million people predicted to move from rural to urban settings over the next ten years they're more likely than not to 'pay off.' Regardless, the purpose of an economy is to serve society (eg. provide gainful employment and produce valued outcomes), not simply to make profits.
As for other governments interested in emulating China - I believe there are several in the Middle East, and possibly Venezuela. The real question is 'Why isn't the U.S. more interested?' There's no long-term successful corporation I know of that doesn't aggressively benchmark and copy from its competitors.
The problem with our economy is the 1% are gambling with funds derived from the tax policies of the Govt on financial derivatives instead of using them for the benefit of the 99% thru sane policies of bolstering the economy and the Congress is helping them to do it.At least they should now go on a bipartisan and balanced approach so we can benifit even though it may take some time. There is no other alternative fix.
The Great Unknown is what Wall Street will cook up in the coming years. The great criminals of Wall Street such as Richard Fuld have not been punished, despite the fact that their actions clearly amounted to Cooking The Books.
To clean up Wall Street, Mr Obama used Wall Street people. He either is incompetent or in the Pocket Of Wall Street.
So, the message to the Banksters is - continue your malicious action and see whether Washington can bail you (and everybody else) out !
That could result in a meltdown worse than 1929 and maybe in a Fascist American Government. That's what you get when ordinary, middle-class people think the current system is corrupt and needs a major clean-out. You can lament this, you can say it won't happen in Anglosaxon lands, but what I can fathom from comments on English-speaking forums, many people are ready for that. Unlimited and unpunished corruption cannot be handled by "Quantitative Easing".
America better get a tough and competent government or some very, very grim times are ahead of you !
And they say ENArques can not think outside the box!
" American policymakers have tried to apply those lessons but not, apparently, hard enough."
Understatement of the decade, but they don't want to tell the legislative branch anything. Such things are not politically fashionable. Normally, if somebody like Romney took office and the Republicans control of the legislature, he could bludgeon his party into action, but don't bank (ar ar!) on it. Politics are more important than prosperity.
To the extent that the estimate of the economy's potential is based on GDP measured before the crisis, it's not surprising that it was overestimated. Pre-crisis GDP was measured during a bubble characterized by spending on housing that was overpriced and unneeded. The productive capacity that was dedicated to that malinvestment in housing isn't going to be easy to put to better use.
America is not growing because of it's ineffective politicians who are more worried about getting reelected than in doing what needs to be done.
The US economy is already producing above the needs of people. Maybe it shouldn't be growing at all until true demand catches up with the bloated, advertisement driven overconsumption.
Agreed! The unlimited growth of consumer items upon which we have based our economy is simply unsustainable.
All these years, the Americans and the West Europeans were being drugged with a combination of high credit and protection. These people forgot what utilization of LIMITED resources was. They were drugged in to compliance.. It was a deliberate indulgence in round tripping. The round tripping was a necessity felt by the political powers to avert a global economic crisis due to the ravages of world war Two.
Additionally, there was a credit built up – primarily based NOT on real net-worth of the BAD BAD 3 (Japan may escape). And not treating will bring the chaos closer and more violent.
The Japanese are getting used to the ‘lost decade+’ and my guess is that the Americans and the Western Europeans (except Germany due to the merger of East and West) will have a lost decade in the future.
So, if Japan could face the lost decade, can the westerners ditto that? The answer is NO. The Japanese are very disciplined and believe in social values - this quality is absent in westerners.."
Oh, that was real. The war wiped out most of the debts, obligations, privileged, deals, favors, and encumbrances in Europe at a time when technology made growth possible.
In the U.S. debt to GDP rose, it didn't fall. And then it leveled off at a moderate level.
It is a lot of the stuff since 1980 that wasn't real.
It is not only crises that "undercut innovation, and the efficiency with which capital and labour are used, by interrupting the supply of capital to high-growth firms or by reducing spending on research and development".
It is the warped banking system itself, its managers, its goals that is interrupting the supply of capital to the real economy.
Unless the closet socialists expropriate the surplus trillions sitting on rich balance sheets which are not spent, growth that only depends on the dispossessed and other defrauded consumers will look increasingly anemic. | http://www.economist.com/comment/1440350 | CC-MAIN-2015-18 | refinedweb | 4,497 | 61.56 |
The CA/Browser Forum?
If you don't abide to their rules, your CA is as much worth as me running a CA with just a few OpenSSL commands: unsupported in all major browsers.
The CA/Browser Forum?
If you don't abide to their rules, your CA is as much worth as me running a CA with just a few OpenSSL commands: unsupported in all major browsers.
So if as a trusted CA you have a correct implementation to verify domain name control, what then is the point of having a CAA record? In essence, doesn't the practice of verifying domain name control make the CAA record entirely redundant? If I hijack your DNS, I can just remove the CAA record anyhow.
Hijacking DNS is not necessarily and all or nothing prospect. Different providers have different security controls. CAA records are just another layer of defense in depth.
It's just, like many security features, a belt-and-suspenders approach. It doesn't protect against somebody maliciously getting access to my DNS API key (since they can just change the CAA and do a DNS-based auth against whatever CA), no, but it protects against two big things:
Mainly, it means that my attack surface is limited to the CAs I use, rather the weakest link of all browser-trusted CAs everywhere. It's not perfect, no, but it's something.
Also in theory one day they'll add more parameters to it, so that I can limit the usage to just DNS-01 authentication signed with some specific account key, and even if someone gets access to put a file on my web server (or does a broad-spectrum BGP hack good enough to trick a CA) they still couldn't get a certificate issued. Again not protecting against everything, but limiting attack surfaces to "just" securing DNS.
I suspect that the reason people see CAA errors is just that CAA is the first DNS record checked, and if the issue is a buggy authoritative DNS server or misconfigured DNSSEC or whatnot, that if CAA wasn't checked you'd just see the error when trying to resolve the TXT or AAAA/A record for the challenge. Maybe I'm wrong on the ordering, though?
I just wonder if it's a paper layer that serves more for efficiency for the CA.
Hence...
I strongly suspect that you are correct here, Peter.
There are more ways to verify domain ownership than what Let's Encrypt uses. Most of them do work through some kind of DNS thing, but a lot of the possible verification methods rely on domain registry information for example. That's a different level of the DNS than just a hacked DNS zone.
Why would such a CA be trusted? Accidents happen, but testing should be thorough in this area.
That's certainly a possibility. I feel like this is an internal security/delegation problem though.
I would hope their authentication procedures would at least be strong enough to prove control of the domain name though.
I think that checking CAA is actually a bunch of headaches for the CAs, they just go through with it because (1) people want it (at least the people running the trust stores), and (2) it helps protect them somewhat from a malicious actor getting certificates that they aren't supposed to, even if the domain validation is correct. Certainly the details of getting it all right caused a big headache for Let's Encrypt and is a source of further compliance issues for other CAs too. It may not be great, but there are downsides to any CA with an issue possibly causing problems for all domains, not just those of their customers.
Because bugs happen. Look at Mozilla's current CA incident list. Each incident is a big problem, though rarely it's about validating a domain incorrectly (though sometimes it is!). But CAA lets the scope of the problem be just slightly smaller, and helps me protect my domain against the bugs of CAs that I don't use.
Sure it is. But it's convenient if one (as an IT administrator) can just put something in DNS to only use the official contracted or preferred CA, and not worry about what developers have managed to use HTTP-01 authentications for that the administrator don't know about. (Hopefully the administrator doing so has standardized a process to make it really easy for the developers/marketing/etc. to be able to get a real certificate without jumping through a lot of hoops, too.) I could imagine other advantages too, like checking the CAA for my domain (and even my subdomains) might be easier to automate in a self-security-scan, versus auditing that all my servers only use CAs I'm expecting.
I suppose one could consider the CAA record to be a "chainlink selector" since it reduces the burden of issuance restriction for the unspecified CAs by squarely placing the burden of issuance restriction on the specified CAs.
A CAA record is also very handy if you are an organization that has sub-groups that are allowed to manage their own namespaces.
For example, as a senior official in the organization, I can define a CAA policy for
example.com and then delegate
foo.example.com and
bar.example.com to different internal groups. The groups can manage their own namespaces, but the CAA record helps lock down their options to what I allow.
This type of selective authorization hits into what petercooperjr was stating. Totally valid though. I was originally inquiring from a global level. I suppose that proactive filtering of authorization certainly has its place. I distinguish aspects that overlap with domain name validation where an "accepted challenge-type" parameter would fall into the "security preference" category (due to being optional) and an "accepted CA" parameter would fall into the "security supplement" category (due to overlapping with standard domain name control authentication measures).
One thing to watch out for: the direction/method that the RFC specifies for traversing DNS is kind of counterintuitive. It’s important to read the RFC carefully when relying on DNS delegation for control.
For some reason I had the same perception, but it seems to be incorrect.
The result of the challenge has always taken precedence over the result of the CAA check.
Why on earth would it be worth doing anything if the CAA record expressly prohibits issuance!?
Just seems to me like squandering the most obvious opportunity for efficiency.
Any idea why this route was taken?
Yes: the ACME challenge is one query. The CAA check is potentially a series of queries all the way up the hierarchy.
Ah. Efficiency via parallel processing then? I would presume that the predicted path is one of the CAA record allowing issuance.
The DNS standard is very clear that the only correct thing for a server that's authoritative for somename.example to do when asked somename.example FOOZLE? and it has no idea what FOOZLE is but somename.example exists will be to say there are zero answers OK.
However, despite that it appears several semi-popular commercial DNS server products exist which get this (and other things) wrong. They answer A? and these days often AAAA? correctly but they get a lot more wrong, likely including problems when asked CAA? still today's web browsers mostly ask A? and AAAA? so just getting those correct is enough to seem like your server "works" for a not very inquisitive customer and once the customer has purchased the product who cares if it works right?
Because DNS is so essential it is critical that it's implemented correctly, down the road from here for example HTTP/3 deployment is expecting to depend heavily on HTTPS/ SVCB records in DNS, obviously a server that can't answer CAA? correctly is not going to get that right either. But in a web browser it's OK to just race and measure - your browser may conclude your network is too broken to bother trying HTTP/3 so you get the HTTP/2 or even HTTP/1.1 protocol and things are a little slower but it works. Let's Encrypt is forbidden from just assuming your server is broken and passing along, your server must know how to answer CAA? and unfortunately a minority still can't get that right in 2020 even though a compliant 1990s DNS server would have correctly reported "zero answers OK".
Sorry, a bit off topic.
I have to point out that I like the idea of the security feature what the CAA record is providing. The owner of the domain specifies which CA is allowed to issue certificate for the given domain. I love it.
But...
After all this preamble, I must tell my opinion that the DNS lookup traversal for the CAA record is a very-very bad idea. I consider the RFC being broken.
I would like to have a different CAA standard specification without DNS traversal. By that (incompatible for sure) specification, the CA just simply looks up the CAA record of the actual domain name for which the certificate is to be issued, to know its own permission for issuing the certificate.
That would certainly make things simpler on the CA side, but then I as a domain owner need to ensure that every time I add a subdomain that I add a CAA record for it. It gets even trickier if I'm using DNS-01 challenges to get certificates for accessible-only-on-my-network devices, since then rather than just automating the DNS challenge as needed I need to leave a CAA record out there indefinitely for each one. All solvable problems, sure, but it's a whole lot easier to just put a CAA record at my main domain name level for my entire organization and be done with it.
But checking CAA all the way up to the TLD level, so that a misconfiguration on
.com would stop all certificate issuance under it for anyone who hadn't established their own CAA record? That does seem rather… weird.
There's probably no perfect answer, and the existing standard has all the advantages of being done by a committee of interested parties and all the disadvantages of being done by a committee. | https://community.letsencrypt.org/t/caa-record-is-it-worth-it/137649/12 | CC-MAIN-2020-50 | refinedweb | 1,735 | 61.77 |
Hi there guys! I hope all of you are fine and doing well. Recently I was hanging out on a python related IRC where I got a request from someone to write an article on decorators in Python. It is perhaps one of the most difficult concept to grasp. So as usual without wasting anytime let get on with it.
Edit: this article has been published on my other blog where it will be easier for you to read the code. Also give me any suggestion regarding the design of the new blog if you have one.
Everything in python is an object (Functions too!):' #lets see what happens if we delete the old hi function! del hi print hi() #outputs: NameError print greet() #outputs: 'hi yasoob'
Defining functions within functions:
So those are the basics when it comes to functions. Lets take your knowledge one step further! In Python we can define functions inside other functions. You might be wondering what sorcery is this! Let me explain it with an example. outsite the hi() function e.g: greet() #outputs: NameError: name 'greet' is not defined
So now we know that we can define functions in other functions. In simpler words we can make nested functions. Now you need to learn one more thing that functions can return functions too.
Returning functions from within functions:
It is not necessary to execute a function within another function, we can return it as an output as well. Let’s take a look at it with an example! welcome(). Why is that? It is so because when you put parentheses around it the function gets executed whereas if you don’t put parenthesis around it then it can be passed around and can be assigned to other variables without executing it. Did you get it ? Let me explain it a little bit in. I hope you have not fainted by now. Was it difficult ? No? I guess you are in the mood to finally learn about decorators! Lets continue our talk and move forward.
Giving a function as an argument to another function:
Lets take a look at an example:
def hi(): return "hi yasoob!" def doSomethingBeforeHi(func): print "I am doing some boring work before executing hi()" print func() doSomethingBeforeHi(hi) #outputs:I am doing some boring work before executing hi() # hi yasoob!
Congratulations! You have all of the knowledge to entitle you as a decorator wrangler! Oh wait, I still haven’t told you what decorators really are. Here is a short definition
decorators let you execute code before and after the function they decorate
Writing your first decorator:
You have already written your first decorator! Do you know when? In the last example we actually made a decorator! Lets_function_requiring_decoration() # I am the function which needs some decoration to remove my foul smell # I am doing some boring work after executing a_function_requiring_decoration()(): print "I am the function which needs some decoration to remove my foul smell" a_function_requiring_decoration() #outputs: I am doing some boring work before executing a_function_requiring_decoration() # I am the function which needs some decoration to remove my foul smell # I am doing some boring work after executing a_function_requiring_decoration() #the @a_new_decorator is just a short way of saying: a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)
Decorators Demystified:
I hope you now have a basic understanding of how decorators work in Python. They are not something to be afraid of at all. In addition, we can chain two or more than two decorators! For example:
def bread(func): def wrapper(): print "</''''''\>" func() print "<\______/>" return wrapper def ingredients(func): def wrapper(): print "#tomatoes#" func() print "~salad~" return wrapper def sandwich(food="--ham--"): print food sandwich() #outputs: --ham-- sandwich = bread(ingredients(sandwich)) sandwich() #outputs: #</''''''\> # #tomatoes# # --ham-- # ~salad~ #<\______/>
In the following example e-satis really does a great job demonstrating how decorators are used. We can run the previous example as so:
@bread @ingredients def sandwich(food="--ham--"): print food sandwich() #outputs: #</''''''\> # #tomatoes# # --ham-- # ~salad~ #<\______/>
The order in which you use decorators matters and can change the whole behaviour of your decorated function if they are not executed in the intended order. Suppose you write this:
@ingredients @bread def sandwich(food="--ham--"): print food sandwich() #outputs: ##tomatoes# #</''''''\> # --ham-- #<\______/> # ~salad~
Nobody wants a sandwich with tomato on the top and salad on the bottom. This demonstrates why you should not mix up the arrangement of the decorators; otherwise you’ll pay the price. In our case we paid the price by ruining our beautiful sandwich.
I hope you learned something useful from this post! If there’s any demand I will cover some more gotchas and features of decorators in the future. Please share your views in the comments below. If you have any suggestions, then please do tell me about them. You can also follow me on facebook, twitter, or you can send me an email. The links to my social media accounts are at the bottom of the post. Farewell, and don’t forget to subscribe to my blog, tweet, and share this post on facebook.
14 thoughts on “Python decorators finally demystified”
Love it!!! Never really understood them before…though that’s probably because i skimmed over that portion of ‘Learning Python by O’Reilly’…the language there just made it too boring…your post clarifies that topic though these seem to be very simple examples…i’d like to see some more complex stuff done with decorators…
I will cover complex stuff in a future post🙂
Thank you! This realy helps me alot🙂
Thank you very much. This post has demystified decorators indeed.
I am happy that you liked it🙂
Thanks for posting such a staff……
was helpfull….🙂
Thank you so much Yasoob. Flask uses decorators for routing and I was having a very hard understanding decorators until I read your post. Do you have any posts regarding Flask?
No currently I don’t have any posts on Flask but I will surely write some in near future.
Many thanks!
It takes great care to write so little and say so much:
a_function_requiring_decoration = a_new_decorator( a_function_requiring_decoration)
Better for me than any example!
Good one🙂 It would be nice if you could write an article on class decorators.
thank you very much could you post some real time projects on python for beginers in detail manner
Really fantastic explanation. Thank you! I couldn’t understand any of the other explanations online until I came to your webpage. A million thanks for helping me land my first Python Developer job!
That’s fantastic!🙂 Really good to know
clarified decorators’s ambiguity in Mind . Thank you very much | https://pythontips.com/2013/12/05/python-decorators-finally-demystified/ | CC-MAIN-2016-44 | refinedweb | 1,102 | 63.49 |
// Find and Push Apart intersecting Geos UI and Script for Autodesk Maya
This script finds intersecting geos by bounding box overlap. The found intersecting geos can either be selected, hidden, deleted, push apart or scaled down to resolve intersection. It tries to replicate the "Cinema 4D Push Apart Effector".
You can do one of the following with the found intersecting geos:
- SELECT: select intersecting geos
- HIDE: hides intersecting geos
- SCALE APART : scale them to make them not intersect anymore (PRO version only)
- PUSH APART : push towards closest free direction (PRO version only)
- PUSH ALONG X/X/Z only pushes in the specified direction (PRO version only)
Additional options to set:
- Radius: How far apart the objects should be (only influences Push apart and Scale apart) - Default 0.1
- Iterations: Nr of iterations. The more the less errors but the slower the script will run (only influences Push apart and Scale apart)- Default 3
USE (UI):
a) Copy the file (mo_findIntersectingGeos.py / mo_findIntersectingGeosPro.py) to your Maya scripts directory. On Windows that is Documents/maya/20xx/scripts/
b) Select the geometries to check on
c) In the Script Editor (Python), paste the following code:
import mo_findIntersectingGeosFree as mo_fi
mo_fi.findIntersecting_UI()
d) Hit execute (or Ctrl Enter)
USE (SCRIPT MODE)
import mo_findIntersectingGeosFree as mo_fi
geos = pm.selected()
mo_fi.findIntersectingGeos(geos, select_overlapping=True)
Get PRO version here >>
Please use the Feature Requests to give me ideas.
Please use the Support Forum if you have any questions or problems.
Please rate and review in the Review section. | https://jobs.highend3d.com/maya/script/find-and-push-apart-intersecting-geos-free-for-maya | CC-MAIN-2021-39 | refinedweb | 253 | 51.18 |
I’m not sure if this question should be asked here but it is my last resort, also first time on Stackoverflow. I have very little experience coding and I’m currently doing an Algorithm specialization in Coursera. The exercise is, given a graph, reducing a Hamiltonian path problem to a SAT problem, which then they evaluate using a minisat solver (). The code below (about 95% me, they provide a starter file) passes a few of their tests but eventually fails (Note: this code actually runs minisat, the one I submitted prints to the terminal). They don’t provide the input for the test case that failed or the expected answer, it just says Wrong Answer.
I have tested with a few graphs and it works. I’ve also tried stress testing my solution against a non-SAT implementation found online (), but so far they always agree. I could add the code for that if needed.
Are there any fringe test cases that I should consider? What am I missing? I know this is not a general programming question but I’m going bananas and I can’t move forward unless I pass the exercise.
Thanks
#include <ios> #include <iostream> #include <fstream> #include <vector> #include <string> /* Converts a graph G with n vertices and m edges into a series of booleans to evaluate whether a Hamiltonian path exists. It then uses minisat solver () to evaluate the clauses and return either SAT if there is a path or UNSAT if no path exists. This is part of a coursera assigment with the description below. The only difference is that instead of printing the clauses to the terminal, I'm actually running minisat. Input Format. The first line contains two integers 𝑛 and 𝑚 — the number of rooms and the number of corridors connecting the rooms respectively. Each of the next 𝑚 lines contains two integers 𝑢 and 𝑣 describing the corridor going from room 𝑢 to room 𝑣. The corridors are two-way, that is, you can go both from 𝑢 to 𝑣 and from 𝑣 to 𝑢. No two corridors have a common part, that is, every corridor only allows you to go from one room to one other room. Of course, no corridor connects a room to itself. Note that a corridor from 𝑢 to 𝑣 can be listed several times, and there can be listed both a corridor from 𝑢 to 𝑣 and a corridor from 𝑣 to 𝑢. Constraints. 1 ≤ 𝑛 ≤ 30;0 ≤ 𝑚 ≤ 𝑛(𝑛−1);1 ≤ 𝑢,𝑣 ≤ 𝑛. Output Format. You need to output a boolean formula in the CNF form in a specific format. If it is possible to go through all the rooms and visit each one exactly once to clean it, the formula must be satisfiable. Otherwise, the formula must be unsatisfiable. The sum of the numbers of variables used in each clause of the formula must not exceed 120 000. */ using namespace std; typedef vector<vector<int>> Matrix; string FILE_IN = "apartment_cnf.txt"; string FILE_OUT = "apartment_out.txt"; struct ConvertHampathToSat { int numVertices; int numEdges; int repeatedEdges; Matrix adj_matrix; ConvertHampathToSat(int n, int m) : numVertices(n), numEdges(m) { repeatedEdges = 0; adj_matrix.resize(n, vector<int>(n)); } int numeric_Sum(const int n) { /* Helper function returns the sum of numbers from 0 to n-1. */ int sum = 0; for (int i = 0; i < n; i++) { sum += i; } return sum; } void add_NotEdges(ofstream &cnf, const int f, const vector<int> &t, int &count) { /* Adds the clauses for pair of vertices without an edge between them. For each pair, it adds one clause for when the from vertex is at the start of path, one clause for when it is at the end of path, and two clauses for each position in the middle of path. */ if (t.empty()) { return; } /* Converting from vertex number to variable */ int from = (f - 1) * numVertices + 1; vector<int> not_edges; for (int to : t) { not_edges.push_back((to - 1) * numVertices + 1); } for (int path_pos = 0; path_pos < numVertices; path_pos++) { for (int to : not_edges) { if (path_pos == 0) { /* from vertex is at start of path */ cnf << -(from + path_pos) << ' ' << -(to + path_pos + 1) << ' ' << 0 << endl; } else if (path_pos == numVertices - 1) { /* from vertex is at end of path */ cnf << -(from + path_pos) << ' ' << -(to + path_pos - 1) << ' ' << 0 << endl; } else { /* from vertex is in middle of path */ cnf << -(from + path_pos) << ' ' << -(to + path_pos + 1) << ' ' << 0 << endl; cnf << -(from + path_pos) << ' ' << -(to + path_pos - 1) << ' ' << 0 << endl; count++; } count++; } } } void write_ToFile() { /* Calculates number of variables and clauses, then writes it out in the format: p cnf variables clauses Writes all the clauses in the format required by minisat: 1 -2 -4 0 (1 OR -2 OR -4). All clauses use OR. Example: for a graph with 3 edges, variables 1, 2, and 3 represent vertex 1 in path position 1, 2, and 3. Variables 1, 4, and 7 represent position 1 occupied by vertex 1, 2, and 3. */ /* Count was added to keep track of the number of clauses when I needed to figure out an equation */ int count = 0; int numberVariables = numVertices * numVertices; /* Calculation of total number of clauses First term = Each vertex is in path + each path position has a vertex Second term = Each vertex appears only once in path + each path has only one vertex Third term = All possible non edges. */ int maxEdges = numeric_Sum(numVertices); int actual_Edges = numEdges - repeatedEdges; int clauses = (2 * numVertices) // First term + (2 * numVertices * numeric_Sum(numVertices)) // Second term + 2 * (numVertices - 1) * (maxEdges - actual_Edges); // Third term /* Creating the file */ ofstream cnf{FILE_IN}; /* Print out number of variables and number of clauses */ cnf << "p cnf " << numberVariables << ' ' << clauses << endl; /* Special case that there's only one vertex */ if (numVertices == 1) { cnf << 1 << ' ' << 0 << endl; cnf << -1 << ' ' << 0 << endl; return; } /* Each vertex must have a position in the path */ for (int vertex = 1; vertex <= numberVariables; vertex += numVertices) { for (int path_pos = 0; path_pos < numVertices; path_pos++) { cnf << vertex + path_pos << ' '; } cnf << 0 << endl; count++; } /* Each vertex must appear just once in the path */ for (int vertex = 1; vertex <= numberVariables; vertex += numVertices) { for (int vertex_path = vertex; vertex_path < numVertices + vertex; vertex_path++) { for (int path_pos = 1; path_pos < vertex + numVertices - vertex_path; path_pos++) { cnf << -(vertex_path) << ' ' << -(vertex_path + path_pos) << ' ' << 0 << endl; count++; } } } /* Each position must have a vertex */ for (int path_pos = 0; path_pos < numVertices; path_pos++) { for (int vertex = 1; vertex <= numberVariables; vertex += numVertices) { cnf << vertex + path_pos << ' '; } cnf << 0 << endl; count++; } /* Each position can have only one vertex */ for (int path_pos = 1; path_pos <= numVertices; path_pos++) { for (int vertex_path = path_pos; vertex_path < numberVariables; vertex_path += numVertices) { for (int vertex = numVertices; vertex <= numberVariables - vertex_path; vertex += numVertices) { cnf << -(vertex_path) << ' ' << -(vertex_path + vertex) << ' ' << 0 << endl; count++; } } } /* Contiguos vertices in the path must have an edge */ Matrix edges_PlusAdded = adj_matrix; // Could do without this new matrix for (int from = 1; from <= numVertices; from++) { vector<int> not_edges; for (int to = 1; to <= numVertices; to++) { if (from != to && !edges_PlusAdded[from - 1][to - 1]) { not_edges.push_back(to); // To avoid duplicating clauses edges_PlusAdded[from - 1][to - 1] = 1; edges_PlusAdded[to - 1][from - 1] = 1; } } add_NotEdges(cnf, from, not_edges, count); } } string read_File() { /* Reads the first line from minisat output file FILE_OUT */ /* Opening the file */ ifstream ist{FILE_OUT}; /* Only care about the first line, which contains SAT or UNSAT */ string result; ist >> result; return result; } string printEquisatisfiableSatFormula() { /* Writes the input to a .txt file, runs minisat then outputs the answer */ /* Creating and writing the input to the file */ write_ToFile(); /* Calling minisat () on the terminal */ string s = "minisat " + FILE_IN + " " + FILE_OUT; const char *command = s.c_str(); system(command); /* Reading the answer from minisat output file */ return read_File(); } }; int main() { ios::sync_with_stdio(false); /* n = number of vertices, m = number of edges*/ int n, m; cin >> n >> m; ConvertHampathToSat converter(n, m); vector<int> vertices(n); for (int i = 0; i < m; i++) { int from, to; cin >> from >> to; /* Input can have repeated edges, which need to be substracted for the calculation of number of clauses */ if (converter.adj_matrix[from - 1][to - 1]) { converter.repeatedEdges++; } /* Adding edges to adjacency list */ converter.adj_matrix[from - 1][to - 1] = 1; converter.adj_matrix[to - 1][from - 1] = 1; } string answer = converter.printEquisatisfiableSatFormula(); cout << answer << endl; return 0; }
Source: Windows Questions C++ | https://windowsquestions.com/2021/09/28/troubleshooting-hamiltonian-path-to-sat/ | CC-MAIN-2021-43 | refinedweb | 1,333 | 53.14 |
namespaces and main()
Discussion in 'C++' started by poiuz24, Jul,289
- Kumar Reddi
- May 29, 2005
int main(int argc, char *argv[] ) vs int main(int argc, char **argv )Hal Styli, Jan 17, 2004, in forum: C Programming
- Replies:
- 14
- Views:
- 1,709
- Old Wolf
- Jan 20, 2004
int main() or int main(void)?Frederick Ding, Dec 3, 2005, in forum: C Programming
- Replies:
- 10
- Views:
- 674
- pete
- Dec 4, 2005
how #define a main() function and call our own main function?ravi, Sep 25, 2007, in forum: C Programming
- Replies:
- 28
- Views:
- 1,023
- Richard Heathfield
- Sep 26, 2007
Main > Popup > Popup > Close popup AND new URL in main?Jens Peter Hansen, Jun 18, 2004, in forum: Javascript
- Replies:
- 7
- Views:
- 591
- Randy Webb
- Jun 19, 2004 | http://www.thecodingforums.com/threads/namespaces-and-main.284512/ | CC-MAIN-2014-52 | refinedweb | 128 | 66.61 |
Search
Create
299 terms
penaherp
Salesforce Certified Platform Developer I - Apex
STUDY
PLAY
Describe differences between Apex and traditional Programming Languages like Java.
1.) Traditional Programming Languages are fully flexible, and allow you to tell the system to do just about anything. Apex is governed, and can only do what the system allows.
2.) Apex is case-insensitive
3.) Apex is on-demand, and is compiled and executed in the Cloud (i.e. on the server)
4.) Apex requires unit testing for deployment into a Production environment
5.) Apex is not a general-purpose Programming Language. It can only be used on the Force.com platform.
What are the two primary components of Apex code?
Apex Classes and Apex Triggers
What is an Apex Class?
An Apex Class is a template or a blueprint from which Apex objects are created.
What is an Apex Trigger?
A procedure that automatically executes during a DML operation.
What are the three types of FOR() loops that Apex code supports?
1.) Traditional FOR() loops
2.) List Iteration FOR() loops
3.) SOQL FOR() loops
What are the three types of Collection data types in Apex code?
1.) Lists
2.) Maps
3.) Sets
What are Collections used for in Apex code?
Collections are used to store groups of elements, such as primitive data types, or sObjects.
Where are the three areas where you can develop Apex code?
1.) The Force.com IDE
2.) The Developer Console
3.) The Setup menu
What conditional statements does Apex support?
if-else
What conditional statements are not supported by Apex?
1.) case
2.) switch
What is the sObject data type?
The sObject data type is a generic data type that is the parent class for all standard and custom objects in Apex.
What are two data types that are unique to Apex?
1.) sObject
2.) ID
What is a List?
A List is an ordered collection of elements of a single data type. Elements added to a List are assigned an implicit index, and therefore, Lists can contain non-unique values (i.e. elements can be duplicated within a List).
What is a Set?
A Set is an unordered collection of unique elements. There are no indexes assigned to elements in a Set, and therefore, elements in a Set much be unique.
What is a Map?
A Map is a collection of key-value pairs. Keys must be unique, but Values can be repeated. With Maps, we supply the index, unlike Lists, where the index is automatically applied when an element is added.
What is a common use case for Lists?
Lists are commonly used to hold the results of a SOQL query.
What is a common use case for Sets?
Sets are commonly used to store values used to filter data queried by SOQL.
What is a common use case for Maps?
Maps are commonly used as a cache of records that can be accessed by key/ID.
Are Apex Arrays the same as Java Arrays? Why or why not?
While Apex Array notation seems the same as Java Array notation, they are internally different. Apex Arrays can be dynamically resized, while Java Arrays cannot be dynamically resized.
//Array notation
Account[] accounts = new Account[] {acc1,acc2,acc3};
//List notation
List<Account> accounts = new List<Accounts>;
accounts.add(acc1);
accounts.add(acc2);
accounts.add(acc3);
Are Lists also Arrays?
No. Lists are not Arrays, but they can be syntactically referenced as Arrays.
How can you iterate over a Map?
First retrieve the key set by using the Map.keySet() method. Then, use a FOR() loop to iterate through the key set to access and work with each value in the Map.
What do classes consist of?
Methods and Attributes
What is an inner class?
A class within another class
Does the name of a class need to begin with a capital letter?
No. But, it is recommended that this be done. More specifically, it is recommended that the Java notation be followed.
What are some ways that Apex classes are different from Java classes?
In Apex:
1.) Inner classes can only be nested one level deep
2.) Static methods and attributes can only be declared in a top-level class definition (i.e. an "outer class").
3.) The system-defined "Exception" class must be extended in order to create new exception classes.
What are two ways that an Apex class can be created from the UI
Under Setup > Develop > Apex Classes...
1.) Click the "New" button to enter the code manually.
2.) Click the "Generate from WSDL" button and upload a WSDL file.
What are the three access modifiers for an Apex class?
1.) Public
2.) Private
3.) Global
What are some optional definition modifiers for an Apex class?
1.) with sharing
2.) without sharing
3.) virtual
4.) abstract
What is the format for a class definition?
[access modifier] [definition modifier (optional)] class [class name] [implements (optional)] [extends (optional)] { //class body }
Where is a global class accessible?
A global class is accessible within and outside of the org or namespace.
When is the global access modifier mainly used?
The global access modifier is mainly used when:
1.) You want to create an email service or a web service.
2.) You want to allow an API call to appExchange code or a managed package that is published to the appExchange.
3.) You want to allow users from outside the namespace to access the code.
What happens when you use the public access modifier?
The class will be accessible throughout the application, org, or namespace that comprises the class.
What happens when you use the private access modifier?
When you use the private access modifier in a class definition of an inner class, the inner class is only accessible to the outer class.
What is the default access level for top-level classes, also called "outer classes"?
There is no default access level for top-level classes. The access modifier must be specified.
What access modifiers can be assigned to a top-level class?
1.) global
2.) public
What is the default access level for inner classes?
private
What is the default access modifier for all methods and attributes across all Apex classes?
private
True or False: All Apex code executes in the system mode.
False. All Apex code, with the exception of anonymous blocks, executes in the system mode.
What happens when the code executes in system mode?
The code ignores all CRED permissions on objects and field level security, and ignores all record sharing privileges.
What happens when you apply the "with sharing" definition modifier to a class?
Record level sharing privileges are enforced within the class. For example, a SOQL query executed within a "with sharing" class will only return the records to which the user has at least Read Only access. Similarly, users can only update records to which he/she has Read/Write access.
True or False: A "with sharing" class still ignores all CRED permissions on objects and field level security.
True
What happens when you apply the "without sharing" definition modifier to a class?
Sharing model access will be ignored. This means that when a user queries the database, the record level read or edit restrictions are not taken into account. Also referred to as "running in system mode".
What happens when neither the "with sharing" or "without sharing" definition modifiers are specified for a class?
The sharing model access is enforced. That is to say, the "with sharing" behavior is the default.
What happens if a class is called from a class that does not have sharing enforced?
Sharing is not enforced for the called class as well.
What is an interface?
An interface is a class that only includes method signatures. The methods are not implemented in the interface. Another class must be created to supply the implementation.
True or False: You do not have to complete the implementation of all the methods of an interface class in order to implement the interface.
False.
What is the syntax of an attribute?
[access modifier] [data type] [attribute name] [initialization]
Ex. public Integer myInt = 0;
What is the value of an attribute if it is not initialized?
null
What does it mean to "overload" a method?
To overload a method means to declare multiple methods with the same name, but with different signatures.
What is the syntax for a method?
[access modifier] [return type] [method name] [parameters] { //method definition... }
Is the access modifier portion of a method declaration optional?
Yes
What are four access modifiers for methods and attributes?
1.) public
2.) private
3.) protected
4.) global
What can access a protected method or attribute?
Only instance methods and member attributes can access a protected method or attribute.
True or False: A global method or attribute can be declared within a private class.
False. If you declare a global method or attribute within a class, that class must also be declared as global.
Describe a static method.
Static methods do not require an instance of an object to run. They are accessed through the class itself. They are generally utility methods that do not depend on an instance of the class.
Give an example of a standard static method.
system.debug();
Describe static attributes.
Static attributes are accessed through the class itself, and not through an instance of the class. They are used to store data that is shared within the class. All instances of the same class invoked in the same context share the same copy of static attributes. They can be used to set recursive flags to prevent recursive logic from performing the same operation more than once.
What is a constant?
Constants are attributes that can be assigned a value only once. Constants are defined using the "static" and "final" keywords.
When can a constant be initialized?
Either in the declaration itself, or via a static initializer method, if the constant is defined within a class.
What is the syntax for instantiating a class object?
[class name] [object name] = new [constructor()];
True or False: To work with non-static methods or attributes within a class, you do not need to create an instance of the class.
False.
What is a constructor?
A constructor is a special method that is used to create an object out of a class definition.
Do constructors have a return type?
No.
True or False: Classes have a default, no argument, invisible public constructor ONLY if no explicit constructor is defined.
True. The default constructor goes away when you define a custom constructor.
What is the "this" keyword used for?
The "this" keyword is used to represent the methods and attributes of the current instance of the class.
What are the two ways that you can use the "this" keyword?
1.) with dot notation
2.) with constructors
What are two examples of system-delivered classes?
1.) System
2.) UserInfo
What are limit methods?
Limit methods are methods that can be used to help manage governor limits, and can be used for debugging and printing messages.
True or False: There are two versions of each limit method.
True. The first version returns the amount of a resource used, and the second version returns the amount of a resource left.
Ex. getQueryRows
Ex. getLimitQueryRows
What are the three process classes?
1.) ProcessResult
2.) ProcessSubmitRequest
3.) ProcessWorkItemRequest
What is the ProcessResult class used for?
ProcessResult is used to process the results from a workflow process.
What is the ProcessSubmitRequest class used for?
ProcessSubmitRequest is used to submit a workflow item for approval.
What is the ProcessWorkItemRequest class used for?
ProcessWorkItemRequest is used to process an item after it has been submitted
Describe the format of Parent-to-Child relationships.
Parent-to-Child relationships use plural version of the child object name.
Ex. Contacts
If the relationship is a custom relationship, the relationship is appended with "__r"
Ex. Interviewers__r
Describe the format of Child-to-Parent relationships.
Child-to-Parent relationships use the singular version of the parent object name.
Ex. Account
If the relationship is a custom relationship, the relationship is appended with "__r"
Ex. Position__r
True or False: Relationships in Apex are written in dot notation.
True.
Ex. myRecord.Position__r.Status__c;
Describe the three parts of a relationship field.
1.) ID (position__c)
2.) Reference (position__r)
3.) Related List (job_applications__r)
How many member variables exist on the child object to reference the parent object?
Two.
1.) Foreign key ( record.relationship_field__c = '001234567891ABC'; )
2.) Object reference ( record.relationship_field__r = new ParentObject__c (); )
How many member variables exist on the parent object to reference the child object?
One.
What does SOQL stand for?
Salesforce Object Query Language
Where can you execute a SOQL query?
1.) the queryString parameter in the query() call
2.) Apex statements
3.) Visualforce controllers and getter methods
4.) Schema explorer in the Force.com IDE
5.) Query Editor in the Developer Console
What are the three main components (or clauses) of a SOQL statement?
1.) SELECT
2.) FROM
3.) WHERE
What are the two ways to insert SOQL within Apex?
1.) Square-bracket expressions
2.) Database.query() method
What approach must you use to implement a dynamic SOQL query at runtime in Apex?
Database.query() method
How many possible data types can a SOQL query return?
3
What are the possible data types that a SOQL query can return?
1.) List of sObjects
2.) A single sObject
3.) An integer
What is the format of a SOQL query that returns an integer?
SELECT count() FROM Account WHERE FieldName[__c] = 'some_value'
What does the AVG() function do within a SOQL query?
AVG() returns the average value of a numeric field
What does the COUNT() function do within a SOQL query?
COUNT() returns the total number of rows matching the query criteria
What does the COUNT_DISTINCT() function do within a SOQL query
COUNT_DISTINCT() returns the number of distinct non-null field values
What does the MIN() function do within a SOQL query?
MIN() returns the minimum value of a field
What does the MAX() function do within a SOQL query?
MAX() returns the maximum value of a field
What does the SUM() function do within a SOQL query?
SUM() returns the total sum of a numeric field
What does the CALENDAR_MONTH() function do within a SOQL query?
CALENDAR_MONTH() returns a number representing the calendar month of a date field
What does the DAY_IN_MONTH() function do within a SOQL query?
DAN_IN_MONTH() returns a number representing the day in the month of a date field
What does the FISCAL_YEAR() function do within a SOQL query?
FISCAL_YEAR() returns a number representing the fiscal year of a date field
What does the WEEK_IN_YEAR() function do within a SOQL query?
WEEK_IN_YEAR() returns a number representing the week in the year for a date field
What is SOQL binding?
SOQL binding is the act of referencing a variable or expression within a square-bracketed SOQL query.
What is the syntax for binding a variable or expression to a SOQL query in Apex?
Use a colon. For example...
[SELECT Id FROM Account WHERE Type = :myTypeValue]
[SELECT Id FROM Account WHERE Type = :('Active' + 'Client')]
True or False: SOQL only returns data for fields that are specified in the SELECT clause of the query
True WITH ONE EXCEPTION: The Id field value is implicitly included for records returned in a SOQL query, even if the Id field is not specified in the SELECT clause.
What happens if you try to access a field for a record returned by a SOQL query that was not specified in the SELECT clause?
A system.objectException will be thrown.
What are the two types of iteration variables supported by SOQL FOR() loops?
1.) A single variable. Here, one record will be processed at a time.
2.) A list of variables. Here, records will be processed in blocks of 200.
SOQL "IN" keyword
Used for bulk queries. Uses a Set or List of sObjects as an argument.
... WHERE Id IN :accountIdSet
SOQL "LIKE" keyword
Allows you to select records using wildcards.
... WHERE Name LIKE 'Senior%'
SOQL "GROUP BY" keyword
Provides summary data about selected groups.
Example:
List<AggregateResult> agr = [SELECT Zip_Code__c, COUNT(Name) FROM Account GROUP BY Zip_Code__c];
True or False: SOQL queries including aggregate functions do not support queryMore().
True. A LIMIT should be applied to these queries to ensure that an exception is not thrown by exceeding the limit of 2,000 rows for queries containing aggregate functions.
SOQL "FOR UPDATE" keyword
Locks the returned records from being updated by another request. The records can only be updated within the current trigger context, and the locks are released when the transaction ends.
SOQL "ALL ROWS" keyword
Returns both active and deleted records.
What is the purpose of SOQL joins?
SOQL joins allow you to query data from two or more sObjects in a single query based on the relationships between them.
Describe a SOQL Right Outer Join
A SOQL Right Outer Join is when you pull in Parent data via a SOQL query on a Child object. For example:
SELECT Id, Account.Name, Account.Industry from Contacts
Describe a SOQL Left Outer Join
A SOQL Left Outer Join is when you pull in related child data via a SOQL query on a Parent object. For example:
SELECT Id, Name, (SELECT First Name, Last Name FROM Contacts) FROM Accounts
Describe a Semi-Join SOQL Query
Used to query for Parent records that have at least one Child object. For example:
SELECT Id, Name FROM Position__c where Id IN (SELECT Position__c FROM Job_Application__c)
Describe a Right Inner Join SOQL Query
Used to query for Child records that have a Parent record. For example:
SELECT Id, Position__r.Name FROM Job_Application__c WHERE Position__c != NULL
Describe a Right Anti-Join SOQL Query
Used to query for Child objects that do NOT have a Parent record. For example:
SELECT Id FROM Job_Application__c WHERE Position__c = null
Describe a Left Anti-Join SOQL Query
Used to retrieve Parent objects that do not have any Child records. For example:
SELECT Id, Name FROM Position__c WHERE Id NOT IN (SELECT Position__c from Job_Application__c)
Describe a Right Inner Join Without Remote Condition SOQL Query
Used to query for Child records that have Parent records that meet certain criteria (i.e. certain Parent records only). For example:
SELECT Id, Position__r.Name FROM Job_Application__c WHERE Position__r.Type = 'Technology'
What is a Multi-Level Relationship?
When you chain relationships together to access Grandparent records, and beyond. For example:
Job_Application__r.Candidate__r.Email
What are the limits of Multi-Level Relationships? There are two.
1.) You can only reference a maximum of 5 child-to-parent relationships in a single query.
2.) You can only have one parent-to-child relationship in a single query.
In the Developer Console, where can you run a SOQL query?
In the Query Editor
In the Developer Console, is there a feature that allows you to view the details of an object, such as the fields that exist?
Yes. Choose File > Open Resource and select an object file (ex. Job_Application__c). The result is a tab that lists the available fields for the object. Great for running SOQL queries on the fly without having to dig for information manually through the native Setup menu, etc.
True or False: In the Query Editor of the Developer Console, after opening an object resource, you can click to select fields from the resource, and then click "Add Fields" to automatically build a default SOQL query that includes those fields.
False. After opening an object resource, you can click to select fields from the resource, and then click "Query" to automatically build a default SOQL query that includes those fields.
In the Schema Builder, is a feature provided to allow you to clear the default layout?
Yes. Click "Clear All" to remove all objects and relationships from the workspace area.
True or False: In the Schema Builder, after adding objects to the workspace area, you must manually rearrange the objects if you would like the layout to better fit the viewing area.
False. Click "Auto Layout" to have the Schema Builder auto-arrange the layout to best fit the viewing area.
In the Schema Builder, can you toggle between viewing Labels and API Names for Objects and Fields?
Yes. Under View Options, select "Display Element Labels" or "Display Element Names"
What does SOSL stand for?
Salesforce Object Search Language
What are some differences between SOSL and SOQL?
1.) SOSL can search multiple objects at once.
2.) SOSL is used to perform text searches.
What is the return type of a SOSL query?
A list of lists of sObjects.
By default, SOSL excludes: (three answers)
1.) Dates
2.) IDs
3.) Numbers
By default, SOSL returns only the [BLANK] of found records.
IDs
What is an example of a SOSL query?
[ FIND 'Acme' RETURNING Account(Name), Opportunity(Name) ]
A SOSL statement specifies: (4 items)
1.) A text expression (i.e. what to search for)
2.) The scope of fields to search
3.) The list of objects and fields to retrieve
4.) The conditions for selecting rows in the source objects
You use the FIND clause of a SOSL query to:
Specify the search string, surrounded by single quotes.
Ex. FIND 'Acme'
True or False: The FIND clause does not support wildcard searches.
False.
Describe the wildcards available in the FIND clause for SOSL queries.
1.) An asterisk (*) is a wildcard for one or more characters in the middle or the end of a search string.
2.) A question mark (?) is a wildcard for one character in the middle or the end of a search string.
You use the IN clause of a SOSL query to:
Limit the type of fields to search.
Name 5 options for the search scope of the IN clause.
1.) ALL FIELDS
2.) NAME FIELDS
3.) EMAIL FIELDS
4.) PHONE FIELDS
5.) SIDEBAR FIELDS
True or False: The IN clause is optional.
True.
If the IN clause is not specified, what is the default search scope of a SOSL query?
ALL FIELDS
You use the RETURNING clause of a SOSL query to:
Limit the results to the specified object types, as well as the fields to return for each of the specified objects.
True or False: The RETURNING clause is optional.
Trick question! It is optional via the API, but required via Apex code.
If you do not specify any objects or fields in the RETURNING clause...
The search will return the IDs for matching records across all searchable objects.
You use the WHERE clause of a SOSL query to:
Filter search results by specific field values.
True or False: The WHERE clause of a SOSL query is optional.
True.
What difference exists when executing a SOSL query in the Query Editor of the Developer Console?
The search term must be enclosed in curly braces {} instead of single quotes ''.
Can you bind variables to a SOSL query like you can with a SOQL query? If so, is the format the same?
Yes, and Yes.
When should you use SOQL instead of SOSL? (three reasons)
1.) When the sObject type is predetermined.
2.) When the result data needs to be joined.
3.) When you want to query beyond text, email, or phone fields.
When should you use SOSL instead of SOQL?
When you need to search across multiple sObject types.
What does DML stand for?
Data Manipulation Language
What are the 6 DML actions that you can execute?
1.) insert
2.) update
3.) upsert
4.) delete
5.) merge
6.) undelete
What are the two forms of DML operations?
1.) Standalone statements (insert myAccount;)
2.) Database methods (Database.insert(myAccount);)
Why would a developer use a Database method instead of a standalone statement?
When you need to control additional features, such as:
1.) truncation behavior
2.) locale options
3.) triggering assignment rules
True or False: When using Database methods, you can perform a DML operation on multiple sObjects at a time.
False. Like standalone statements, Database methods can execute on a single record or a list of records, but are limited to one sObject type at a time.
When a DML standalone statement is executed against a list of records, if one record encounters an error, what happens?
All of the records will fail. None of the records will be inserted/updated/etc.
When a DML Database method is executed against a list of records, if one record encounters an error, what happens?
It depends on the setting of the allOrNone parameter. If allOrNone is set to false, then Apex handles errors on a case by case basis. Even if an error is encountered with one record in the list, the operation will continue with the other records in the list.
When using a Database method to execute a DML operation, and if allOrNone is set to false, how can you check the results of the operation?
Database insert and update methods return a SaveResult object that can be used to get the results of the operation.
True or False: You must specify a value for the allOrNone parameter when using a Database method.
False.
What is the default value of the allOrNone parameter of a Database method?
True.
What is the return type for the Database.insert method?
Database.SaveResult
What is the return type for the Database.update method?
Database.SaveResult
What is the return type for the Database.update method when a LIST of records is updated?
List<Database.SaveResult>
What is the return type for the Database.delete method?
Database.DeleteResult
What is the return type for the Database.merge method?
Database.MergeResult
What is the return type for the Database.upsert method?
Database.UpsertResult
What is the return type for the Database.undelete method?
Database.UndeleteResult
What are the three methods of a SaveResult object?
1.) ID getId()
2.) List<Database.Error> getErrors()
3.) Boolean isSuccess()
What additional options does the Database.DMLOptions object allow you to control?
1.) Truncation behavior
2.) Trigger assignment rules
3.) Locale options
4.) Trigger email notifications based on specific events such as:
- Creation of a new Case, Case Comment, or Task
- Conversion of a Case email to a Contact
- New User email notification
- Password reset
Assume "c" represents an existing Contact, and "a" represents an existing Account. Are these statements valid?
c.Account = a;
c.Account.Name = 'Salesforce';
c.LastName = 'Smith';
update c;
update c.Account;
Yes.
What is the governor limit for DML statements in a single context?
150.
When should you include DML operations within a FOR() loop?
NEVER.
What is the most efficient way to process bulk DML operations?
Iterate over lists of sObjects using a SOQL FOR() loop and process DML operations over chunks at a time. This helps to avoid heap limits. For example.
for(List<Position__c> myList: [SELECT Id FROM Position__c])
{
for(Position__c p: myList)
{
//some logic here...
}
Database.update(myList);
}
What if I exceed the total number of allowed SOQL queries?
Move SOQL queries outside of loops.
What if I exceed the number of DML operations?
Process DML operations in bulk.
What if I exceed the total number of records retrieved by SOQL queries?
Create selective queries that filter indexed fields, such as primary keys, foreign keys, names, audit dates, or external Id fields.
If you still believe you will exceed governor limits on DML operations even after using best practices for your code, what other option may exist?
Use Apex asynchronous batch processing for DML operations.
Define a Database Transaction.
A transaction is a sequence of events based on the first event you perform.
A transaction is controlled by:
The trigger, the web service, or the anonymous block that executed the apex script.
What happens to database changes if the Apex script contains an uncaught exception?
All changes are rolled back.
What are Transaction Savepoints?
Transation Savepoints are steps in the transaction that specify the state of the database at a specific time.
What are Transaction Savepoints used for?
1.) Control the transaction level
2.) Define logic for rolling back a section or subset of the DML operation
Do Transaction Savepoints (the setSavepoint() and rollBack() methods) count against the limit of DML statements?
Yes.
What are triggers?
Triggers are the primary mechanism to execute code within Apex. Triggers execute code whenever a DML event occurs on a specific sObject.
What are the two types of triggers?
Before and After triggers
What can before triggers do?
They can update or validate values before they are saved to the database.
What can an after trigger do?
They can access field values that are set automatically or affect changes in other records.
Do triggers fire regardless of how the triggering data has been saved? i.e. via the UI, API, Data Loader, etc.
Yes.
What should you consider if you want custom logic to fire only via the UI?
Consider using a Visualforce Page and Apex Controller.
What is the format for declaring a trigger?
trigger [trigger name] on [object name] (trigger events) {//trigger body}
What are the seven different trigger events?
1.) before insert
2.) after insert
3.) before update
4.) after update
5.) before delete
6.) after delete
7.) after undelete
Where can you create a trigger?
1.) Force.com IDE
2.) Developer Console
3.) UI - Setup > Build > Develop > Apex Triggers
4.) UI - Setup > Customize > Standard Object > Triggers
5.) UI - Setup > Create > Custom Object > Triggers
What is the Execution Order of Triggers?
1.) Original record loaded, or new record initialized for insert
2.) New record field values are loaded and override old values
3.) System validation rules
4.) BEFORE triggers
5.) Custom validation rules. Most system validation rules run again.
6.) Record saved, but not committed
7.) AFTER triggers
8.) Assignment rules,
9.) Auto-response rules
10.) Workflow rules
11.) Workflow field updates will update the record again
12.) BEFORE and AFTER triggers executed again IF field are updated based on Workflow rules (up to 13 times)
13.) Processes
14.) Escalation rules
15.) Roll-up summary fields or cross-object formula fields are updated in the parent records, and affected records are saved.
16.) REPEAT the same process for affected grand parent records.
17.) Criteria-based sharing is evaluated
18.) All DML operations are committed to the database
19.) Post-commit logic (such as sending emails) is executed.
What is the runtime context of a trigger called?
Trigger context
What is the trigger context?
The trigger context is the data available to the trigger
Name examples of Trigger Context Boolean Variables
isBefore
isAfter
isInsert
isUpdate
What is trigger.size?
Trigger.size returns the total number of new and old sObjects.
What is trigger.new?
Trigger.new returns a list of the new versions of sObjects.
When is trigger.new available?
In INSERT and UPDATE triggers.
When can trigger.new be modified?
In BEFORE triggers
What is trigger.newMap?
Returns a map of IDs to sObjects for the new records
When is trigger.newMap available?
BEFORE UPDATE, AFTER UPDATE, AFTER INSERT, AFTER UNDELETE
What is trigger.old?
Contains a list of the original records
When is trigger.old available?
UPDATE and DELETE triggers
True or False: trigger.old is Read Only.
True
What is the value of trigger.old in the context of an INSERT trigger?
NULL
What is trigger.oldMap?
Returns a map of IDs to sObjects for the original versions of the records.
How can you prevent a DML event from being completed for, or taking action on, a record?
Use the addError() method.
What can you use trigger.newMap and trigger.oldMap for?
To correlate records with query results. For example, use the keySet() of one of these maps to query for related records and then take some action, such as preventing Opportunities from being deleted if they have one more related Quotes.
addError() can be applied to... (2 answers)
1.) An sObject
2.) A specific field
How do you apply the addError() method to an sObject?
Opportunity myOpp;
//some code...
myOpp.addError('You cannot do that!');
How do you apply the addError() method to a specific field on an sObject?
Opportunity myOpp;
//some code...
myOpp.myFieldName__c.addError('Do not touch this field!');
True or False: All triggers run in User context by default.
False. Triggers run in System mode by default.
Can a Trigger be made to run in User context?
Yes, using the WITH SHARING keywords.
What keywords can Trigger code contain?
Only those applicable to an inner class
Can Trigger code contain the STATIC keyword?
No.
True or False: Cascading execution of Triggers (i.e. firing another trigger as a result of DML within the current trigger) are part of the same execution context with respect to Governor Limits.
True.
True or False: Upsert events cause Insert and Update triggers to fire.
True.
What do Merge events cause to fire?
1.) DELETE triggers for the unsuccessful records.
2.) UPDATE triggers for the successful records.
What is a limitation of UNDELETE triggers?
Undelete triggers only work with top-level objects, although related records are also undeleted.
What is a limitation of an AFTER UNDELETE trigger?
They only work with recovered records.
True or False: Field History is not recorded until the end of a trigger event.
True.
What is Apex Sharing?
Apex Sharing is a way to create custom sharing reasons and control access levels for those custom reasons using Apex scripts.
True or False: Custom Apex Sharing Reasons are available for Custom Objects and Top-Level Standard Objects.
False. Custom Apex Sharing Reasons are only available for Custom Objects.
What is the Name format of an object's sharing table in Apex?
Object__Share
What is the format to set the Row Cause for a custom object sharing record?
Object_Share myShare = new Object__Share();
myShare.RowCause = Schema.Object_Share.RowCause.Custom_Sharing_Reason__c
What can be used to recalculate Apex managed sharing?
A batch job.
What is the recommended approach for recalculating Apex managed sharing on a record?
1.) Delete all sharing for the record for the RowCause
2.) Calculate and add all sharing for the record for the RowCause
True or False: You can change the sObject that a Trigger is associated with after the Trigger is created.
False.
How many records can a trigger process at a time?
200
What happens if the number of records in the DML operation exceeds the number of records that a trigger can process at one time?
The trigger will process records in chunks of 200.
True or False: The BEFORE trigger can be used to access system-updated field values and affect changes in other records.
False. The AFTER trigger is needed for this.
How many times will a trigger execute for 1,001 records?
6 times.
What are Exceptions?
Exceptions are errors and other events that disrupt the execution of code.
What four keywords allow you to handle Exceptions in Apex?
1.) throw
2.) try
3.) catch
4.) finally
What does the throw keyword do?
throw indicates that an error has occurred, and provides an Exception object.
What does the try keyword do?
try indicates the block of code where the Exception may occur.
What does the catch keyword do?
catch identifies the block of code that can handle a specific Exception.
What does the finally keyword do?
finally represents a block of code that is guaranteed to fire after a try block.
What are some system-defined exceptions?
1.) DmlException
2.) ListException
3.) MathException
4.) SecurityException
5.) NullPointerException
6.) QueryException
7.) SObjectException
8.) StringException
9.) TypeException
True or False: Developers can create their own custom Exception classes.
True. These are called User-Defined Exception Classes.
When are User-Defined Exception Classes most handy?
When Developers need more control over the type of behavior performed by a program when handling Exceptions.
What two requirements must User-Defined Exception Classes follow?
1.) They must end with the string "Exception".
2.) They must extend the system-defined Exception class.
True or False: User-Defined Exception Classes can indirectly extend the system-defined Exception class.
True.
public virtual class BaseException extends Exception {}
public class OtherException extends BaseException {}
What does the getCause() method do?
Returns the cause of the exception as an Exception.
What does the getMessage() method do?
Returns the error message that is displayed to the end user
What does the getTypeName() method do?
Returns the type of exception that has occurred.
What does the initCause(sObject Exception) method do?
Sets the cause for the Exception, if not already set.
What is Debugging?
Debugging is the process of locating and reducing the number of defects or errors within our code.
What two utilities are used for debugging?
1.) Logs
2.) Anonymous Blocks
Where can Logs be generated?
1.) Debug Logs in the Setup menu
2.) Developer Console
3.) Force.com IDE
What is the size limit for a System Log?
2 MB
Each organization can retain up to [REDACTED] MB of Logs.
50 MB
What do Log Filters do?
Log Filters determine the type of information returned in a Log.
How many Log Filters exist?
8
What are the different Log Filters that exist?
1.) Database
2.) Workflow
3.) Validation
4.) Callout
5.) Apex Code
6.) Apex Profiling
7.) Visualforce
8.) System
What does the Database filter include?
1.) System.debug() log messages
2.) DML statements
3.) Inline SOQL or SOSL queries
What does the Apex Profiling filter include?
Cumulative profiling information, such as SOQL queries that use the most resources, the number of Apex method calls, and the total time that each method called needed for processing.
What does the System filter include?
Information regarding calls to all System methods.
What are System Log Levels used for?
System Log Levels are used to control the amount of information returned in a Log.
What do the ERROR, WARN, and INFO Levels include?
Error, warning, and information messages.
What does the DEBUG Level include?
Lower level messages and messages generated by the System.debug() method.
What do the FINE and FINER Levels include?
1.) System.debug() messages
2.) DML Statements
3.) SOQL and SOSL inline statements
4.) Entrance and Exit of every user-defined method
What does the FINEST Level include?
1.) Everything included in the FINE and FINER Levels
2.) Changes in the sharing context
3.) Variable declaration statements
4.) Start of loops
5.) All loop controls
6.) Thrown exceptions
7.) Static and class initialization code
True or False: Debug Log Levels apply to the entire Log, and cannot be granularly controlled at the class or trigger level.
False.
True or False: Unless otherwise overridden, the Log Levels of a class called from another class will inherit the Level of the class that called it.
True.
True or False: Debug Logs capture different information than System Logs.
False.
Can anonymous blocks include the STATIC keyword?
No.
True or False: You can specify the User for which the anonymous block should be executed as.
False. Anonymous blocks are always executed using the full permissions of the current user.
Do anonymous blocks run in system mode?
No.
What are the three ways that anonymous blocks can be executed?
1.) executeAnonymous() web services API call
2.) Developer Console
3.) Force.com IDE
What are Apex Unit Test Methods?
Methods that verify whether or not the code is working is expected.
What are two facts about Apex Unit Test Methods?
1.) They do not take any arguments.
2.) They do not commit any data to the database, even if DML operations are executed within the method.
How do you annotate a Test Class?
@isTest
public class myTestClass {}
What are the two ways that you can annotate a Test Method?
1.) The annotation @isTest
2.) The keyword testMethod
True or False: Governor limits are not applied to test methods.
False.
What can be used to properly test governor limits for your code?
startTest() and stopTest()
Do you have to use startTest() and stopTest() together?
Yes
Where in the test method should you place the startTest() method?
After all of the test infrastructure has been set and just before the call to the actual methods to be tested.
Can unit tests be run via a call to the API?
Yes, using the runTests() method.
What do the compileClasses() and compileTriggers() methods do?
They can be used to just compile the code without tests being run in order to verify that the syntax and references of the code are correct.
What percentage of Apex code must be covered by unit tests?
75%
What methods can be used to verify the results of a unit test?
System.assert();
System.assertEquals();
What method can be used to test record sharing and data accessibility?
System.runAs();
What are some best practices for creating Apex unit tests?
1.) Create 200 test records to test that your code is properly "bulkified".
2.) Test your code using valid and invalid inputs.
3.) Do not assume that your record Ids are in sequential order
4.) Use the ORDER BY keyword to ensure that records are returned in the expected order
How should you annotate a method that is used to setup a test by creating test data, etc.?
@testSetup
What are the two types of Logs?
System Logs and Debug Logs.
What is the pattern typically followed for Deployment?
1.) Develop
2.) Integrate
3.) Stage
4.) Training and Production
What does the Develop step include?
1.) Development in a developer sandbox
2.) Unit testing
3.) Integration testing
What does the Integrate step include?
Solution modules are tested as a group. All or most of the individual components are combined to form a complete solution, and are tested in another sandbox.
What does the Stage step include?
1.) Full regression testing
2.) Load testing
3.) UAT
4.) Specific new feature testing
What does the Production/Training step include?
The change control board approves changes for deployment to Production and/or Training following successful completion of testing.
Can you directly create Apex code in Production?
No.
Where is Apex code unit tested?
In a sandbox before deployment, and in Production after deployment.
How can you deploy org-specific data in metadata?
Switch to work-offline mode, remove the org-specific information from the metadata, and deploy that to Production.
What are four ways that metadata can be deployed to an environment?
1.) Force.com IDE
2.) Force.com Migration Tool
3.) Change Sets
4.) Third party tools (likely at cost)
How can you create your own SOAP Web Service method?
Use the webservice keyword
Can you have a private Web Service method?
No. Web Service methods are inherently global
True or False: The webservice keyword can be considered as an access modifier that enables the same level of access as the global keyword.
False. The webservice keyword can be considered as an access modifier that enables MORE access than the global keyword.
From where can custom SOAP Web Service methods be invoked?
1.) AJAX Toolkit
2.) Custom client program (i.e. Java application, etc.)
How do you call a Web Service from the AJAX Toolkit?
1.) Import the apex.js library
2.) Use the execute() method and pass in the name of the class and method
How do you call a Web Service from a client program?
Generate the class WSDL and include it in the client program, at which point the client program can call the web service directly.
YOU MIGHT ALSO LIKE...
180 terms
Salesforce Certified Platform Developer I
45 terms
Salesforce Platform Developer II
45 terms
Salesforce Platform Developer II
88 terms
Salesforce Platform Developer 1(450)
OTHER SETS BY THIS CREATOR
12 terms
Salesforce - Lightning Experience Customization
7 terms
Salesforce - Company Wide Org Settings
5 terms
AngularJS
119 terms
Salesforce Data Architecture and Management Designer
THIS SET IS OFTEN IN FOLDERS WITH...
70 terms
Salesforce Platform Developer I: Programmatic & Data Models
39 terms
Salesforce Platform Developer I: OOP in Apex
36 terms
Salesforce Certified Platform Developer I - Visualforce Controllers
22 terms
Salesforce Platform Developer I: Force.com Overview | https://quizlet.com/133435950/salesforce-certified-platform-developer-i-apex-flash-cards/ | CC-MAIN-2018-39 | refinedweb | 7,301 | 68.36 |
At the risk of never getting around to picking up Kotlin, I’ve been revisiting other topics this weekend, namely updating last week’s Terraform example and figuring out the new features for static hosting on Azure, which I need to set up a little app I’m doing.
As it turns out, a preview of static websites on Azure storage was actually announced in this Build 2018 video. It was a fairly low-key affair, which I only noticed earlier in the week.
But since it’s public, you can get started using it right away–all you need to do is log in to the Azure Portal through aka.ms/staticwebsites, and you should have access to it.
The service is still only available in
US West Central, so you should create a storage account in that region. Once you do that, you get a new
Static website (preview) option in the portal settings blade:
To publish your site, all you need to do is upload your files to the newly created
$web container. The canonical way to do so with a GUI is usually through Azure Storage Explorer, but I’m using Mountain Duck because it provides a virtual volume on the Mac, which is much nicer (if a trifle less efficient):
I also tried to use the
blobfuse FUSE adapter for Azure Storage (which would be a great way to automate site builds on Linux), but there is a niggling issue that I hope will be sorted out soon.
To add a Cloudflare-managed
CNAME to the storage account, you should first set the record to
DNS only in the Cloudflare dashboard until it’s validated. Otherwise it obviously won’t resolve properly back to Azure.
Once you’ve bound the new domain name to the storage account, it then works exactly like you’d expect. I’ve had zero issues with CORS, content types and related stuff up until now, but I’ve barely gotten started with the app (it’s a simple single-page app that renders selected Azure metrics, something that I’ll write about at a later date).
This opens up a lot of possibilities for this site (I’ve been meaning to get it off a VM for a while), but in between fiddling with REST APIs and the need to fix a
maven build, I’ll get back to exploring that some other weekend…
This is delightfully well done, and worth sharing around.]]>
As promised, this week I’m going to dive into Azure provisioning using Terraform, which is something I’ve been spending some time on, but which many folk in the Azure universe seem to be unaware of. Well, now there’s a copiously detailed example of how to bring them together, and I’m going to walk you through it.
Fully automated provisioning is, for me, the key advantage of using cloud solutions, but many people coming to the cloud tend (much to my bemusement) to carry over the manual “point and click” approaches to provisioning they have been using in their existing datacenters, or (at best) to try and get by with simple CLI scripting (be it
PowerShell or
bash).
As it turns out, infrastructure as code isn’t scripting. Scripting is automation (in the strictest sense), but imperative scripts (i.e.,stuff like
az vm create) are not a good approach for managing infrastructure because they do not usually account for state–i.e., they usually ignore the current state of provisioned infrastructure and do not express the desired state of what you intend to achieve.
They may be nice for one-offs and demos, but if you’re going to to do cloud deployments you intend to keep around for more than a week (and update down the road), you need to use the right tool for the job.
Going straight to the point, for me (and a few of the customers I’ve worked with) choosing Terraform boils down to:
diffsto converge to desired state
These factors translate to a number of benefits in terms of reliability, testability, reproducibility and flexibility, allowing teams to use the same tool to plan, document (as code) and evolve infra-structure without resorting to a myriad other tools.
Azure Resource Manager (ARM) templates (which I wrote about a couple of years back) are alive and well and provide a tried and tested declarative approach that works wonderfully well (ARM templates are composable, can be validated against running infra and support additive “deltas”), but most customers I come across are put off by the learning curve (which, honestly, is pretty easy) or are looking for the Holy Grail of a single tool to manage everything.
Terraform isn’t perfect by any means, but comes quite close to being universal, and seems to enjoy considerable mindshare even in the traditional Windows/IT environments.
Judging from the current state of the Azure provider, just about everything. It can already manage Kubernetes clusters, container instances and Azure Functions, so it covers most generally available services (although not, at this point, Azure Data Lake Analytics, which is a bit sad for me).
But most of the time you’ll want to manage networking and compute resources, so let’s start with a VM:
resource "azurerm_virtual_machine" "linux" { name = "${var.name}" location = "${var.location}" resource_group_name = "${var.resource_group_name}" network_interface_ids = ["${azurerm_network_interface.nic.id}"] vm_size = "${var.vm_size}" storage_image_reference = { publisher = "Canonical" offer = "UbuntuServer" sku = "18.04-LTS" version = "latest" } storage_os_disk { name = "${var.name}-os" caching = "ReadWrite" create_option = "FromImage" managed_disk_type = "${var.storage_type}" } os_profile { computer_name = "${var.name}" admin_username = "${var.admin_username}" admin_password = "${var.admin_password}" } tags = "${var.tags}" }
The definition above is a little simpler than on my full example, but should give you an idea of how straightforward it is (and, in fact, how similar it is to an ARM template).
Depending on your naming conventions you might want to tweak various aspects of it, but in general Terraform‘s variable interpolation should make it very easy for you to both name and tag resources to your heart’s content.
In fact, it is quite easy to have slight variations on tags on a per-resource basis. For instance, here’s how to merge a tag into a default set:
tags = "${merge(var.tags, map("provisionedBy", "terraform"))}"
Terraform does not try to use generic (and potentially dangerously leaky) abstractions across different cloud providers–a VM on Azure is not represented using the same primitives as one on AWS or GCP, and each provider’s abstractions (or quirks) are not glossed over but surfaced onto the language through specific resource types for each provider.
Another important difference for people used to Azure portal or CLI deployments is that since Terraform uses Azure APIs directly, its actions are not listed in the
Deployments blade in your resource groups.
All the individual provisioning actions are listed in the Azure Activity Log, which makes it a little harder to keep track of higher-level activities but ties in pretty well with Terraform‘s approach when modifying existing infrastructure–for conciseness, here’s what happens when I change tags on a resource:
$ terraform apply ... An execution plan has been generated and is shown below. Resource actions are indicated with the following symbols: ~ update in-place Terraform will perform the following actions: ~ azurerm_resource_group.rg tags.ProvisionedVia: "Terraform" => "" tags.provisionedBy: "" => "terraform" Plan: 0 to add, 1 to change, 0 to destroy. Do you want to perform these actions? Terraform will perform the actions described above. Only 'yes' will be accepted to approve. Enter a value: yes azurerm_resource_group.rg: Modifying... (ID: /subscriptions/...) tags.ProvisionedVia: "Terraform" => "" tags.provisionedBy: "" => "terraform" azurerm_resource_group.rg: Modifications complete after 2s (ID: /...) $ _
This, of course, results in a single API call to change infrastructure state.
This bit has little to do with Terraform itself, but is something I’ve been doing for many years–since I invariably use a Mac or Linux (or WSL) to do deployments, I use
Makefiles extensively to save me some typing and to set some variables automatically.
For instance, I use this to pick up the current username and any existing SSH keys and hand them over to Terraform, using the
TF_VAR_ prefix to mark them for import into the
.tf context:
SSH_KEY := $(HOME)/.ssh/id_rsa.pub ifneq (,$(wildcard $(SSH_KEY))) export TF_VAR_admin_username := $(USER) export TF_VAR_ssh_key := $(shell cat $(SSH_KEY)) endif .PHONY: plan apply destroy plan apply destroy: terraform $@
The example (which I encourage you to explore) comes with a slightly improved version of the above, but the point here is that you should find a way to make it easy for you to invoke Terraform multiple times and iterate upon your configurations with minimal error.
Once you adopt it for production deployments (and you will) you want to make sure you’ve minimised the chances of fumbling manual inputs or setting up variables incorrectly.
One of the big advantages of Terraform over resource templates is that modularity is easier to manage (at least for me).
for instance, one of the first things I did was to break out VM creation into a separate module (actually two, one for Windows and another for Linux, but I’m focusing on Linux in this example), which can be invoked like this:
module "linux" { source = "./linux" name = "${var.instance_prefix}" vm_size = "${var.standard_vm_size}" location = "${var.location}" resource_group_name = "${azurerm_resource_group.rg.name}" admin_username = "${var.admin_username}" admin_password = "${var.admin_password}" // this is something that annoys me - passing the resource would be nicer diag_storage_name = "${azurerm_storage_account.diagnostics.name}" diag_storage_primary_blob_endpoint = "${azurerm_storage_account.diagnostics.primary_blob_endpoint}" diag_storage_primary_access_key = "${azurerm_storage_account.diagnostics.primary_access_key}" subnet_id = "${azurerm_subnet.default.id}" storage_type = "${var.storage_type}" tags = "${local.tags}" }
You can see above that I’d be much happier passing the whole
azurerm_storage_account resource as a parameter rather than the individual strings, but this is much less of a pain than trying to use linked ARM templates or merging JSON files (which is something I’ve done with relative success in other projects, but adds to the complexity of maintaining them).
In general, things like conditionals, loops and (thankfully) IP address management (complete with CIDR awareness) are clearer and easier to maintain in Terraform than in Azure templates. Terraform doesn’t do everything, but it does provide a nice scaffolding for other tools to work on top of.
And it does so across regions and multiple resource groups with great ease. You can use Terraform to lay down a solid, sprawling multi-region infrastructure and then provision your machines (and manage software configuration and deployments) with, say, Ansible with minimal overlap, and are still able to update sections of it by tweaking a single master project.
But let’s go back to the example, since it embodies some best practices I keep emphasising whenever I deploy Linux machines.
I never use passwords in my deployments unless I need to deploy a Windows machine. Even though it’s now possible to log in using Active Directory to Linux machines, I prefer to use SSH keys, so I usually excise all mentions of passwords and change VM definitions to read:
os_profile { computer_name = "${var.name}" admin_username = "${var.admin_username}" } os_profile_linux_config { disable_password_authentication = true ssh_keys = { key_data = "${var.ssh_key}" path = "/home/${var.admin_username}/.ssh/authorized_keys" } }
As you’d expect,
ssh_key is, in my case, picked up automatically from the environment by the
Makefile outlined above and supplied to Terraform as the contents of
TF_VAR_ssh_key.
For good measure, I also tweak the SSH daemon cyphers and change the SSH port (this last bit isn’t so much a real security measure as a way to drastically cut down the amount of noise in logs).
To accomplish that, my preferred approach is
cloud-init, which is very easy to use in Terraform and Azure. In the example I fill out the
cloud-config
YAML file using a
template_file data resource to do variable substitution:
data "template_file" "cloud_config" { template = "${file("${path.module}/cloud-config.yml.tpl")}" vars { ssh_port = "${var.ssh_port}" admin_username = "${var.admin_username}" } }
…and then
base64encode the rendered version into
custom_data:
os_profile { computer_name = "${var.name}" admin_username = "${var.admin_username}" custom_data = "${base64encode(data.template_file.cloud_config.rendered)}" }
The
cloud-config template injects a tweaked
sshd_config, which is applied on first boot:
#cloud-config write_files: - path: /etc/ssh/sshd_config permissions: 0644 # strengthen SSH cyphers content: | Port ${ssh_port} Protocol 2 HostKey /etc/ssh/ssh_host_ed25519_key KexAlgorithms curve25519-sha256@libssh.org ... - path: /etc/fail2ban/jail.d/override-ssh-port.conf permissions: 0644 content: | [sshd] enabled = true port = ${ssh_port} logpath = %(sshd_log)s backend = %(sshd_backend)s packages: - docker.io - fail2ban - auditd - audispd-plugins timezone: Europe/Lisbon runcmd: - usermod -G docker ${admin_username} - systemctl enable docker - systemctl start docker
…where besides setting up a few other packages, I set up
fail2ban with an extra config file, tweaked to match the new SSH port.
Once the machine is provisioned (with, say, port
1234), you can check that the result is correctly configured like this:
$ sudo fail2ban-client get sshd action iptables-multiport actionstart iptables -N f2b-sshd iptables -A f2b-sshd -j RETURN iptables -I INPUT -p tcp -m multiport --dports 1234 -j f2b-sshd
Next, let’s look at monitoring, since by default Terraform (like most other tools) doesn’t add any monitoring functionality to your VMs.
In Azure, there are currently four ways to get performance metrics and system diagnostics out of your VMs:
Microsoft.OSTCExtensionsVM extension (which captures metrics in a way the Azure portal can render)
Azure.Linux.DiagnosticsVM extension (which can send out metrics to Event Hub and other niceties)
That leaves us the first three to play around with for our example. Boot diagnostics, which I consider essential, are pretty easy to enable by adding the following stanza to the VM resource:
boot_diagnostics { enabled = true storage_uri = "${var.diag_storage_primary_blob_endpoint}" }
However, the others are rather more complex, and typically require at least three things:
azurerm_virtual_machine_extensionresource that takes the configuration, storage and keys and injects the actual agent into the VM
When you create a Linux machine via the Azure portal, it prompts you for the storage account and then injects a default metrics configuration and a default extension (currently the one by
Microsoft.OSTCExtensions, version 2.3).
That is what I have working in the example by default, and deploying it as-is yields a machine that is indistinguishable from a portal deployment (you can check that by going to
Metrics and see all the
Guest entries).
However, it is much more interesting to look at
Azure.Linux.Diagnostics, because the credentials it requires for the storage account are different–it needs an SAS token with very specific permissions, which can be specified in detail through this resource:
data "azurerm_storage_account_sas" "diagnostics" { connection_string = "${var.diag_storage_primary_connection_string}" https_only = true resource_types { service = false container = true object = true } services { blob = true queue = false table = true file = false } start = "2018-06-01" expiry = "2118-06-01" permissions { read = true write = true delete = false list = true add = true create = true update = true process = false } }
The above is actually included–but commented out–in the example, and I provide working templates for metrics configurations and the JSON bits to include as part of the extension
settings for both 2.3 and 3.0.
I intend to add conditionals to choose the extension type later on, but for readability and time reasons decided to leave things be for now.
The most notable bit, however (and one that took me a bit to figure out) is that Azure requires you to add the SAS token without the leading question mark, which means you need to add it to
protected_settings like so:
diag_storage_sas = "${substr(data.azurerm_storage_account_sas.diagnostics.sas,1,-1)}"
Bottom line: Terraform makes a lot of things easier, but you still need to understand enough about Azure to make things work smoothly.
The good news is that things can only get better from here, since Azure APIs and integrations keep expanding and Microsoft (my current employer, incidentally) stays the course.
This was a necessarily brief (but still rather extensive) walkthrough of my example configuration.
Hopefully you’ve found it both enlightening and useful for tackling Azure with Terraform, and I’ll be updating the project itself to include a full blown web stack and perform a few other tweaks for the sake of modularity and reusability (it works and seems readable enough, but can still be improved).]]>
Well, dark mode and the preliminary
UIKit ports seem nice, and I wasn’t really expecting any new hardware, but bringing Stacks back a decade later and neutering CoverFlow seems, well… Not very imaginative, really.
Best takeaways from the keynote for me? The committment to iOS 12 support across the entire current range (which is impressive) and with performance increases (which I hope will actually happen), plus the rebirth of Workflow as Shortcuts.
Hopefully there’ll be a migration path that lets me re-build all the workflows I have with third-party apps–otherwise, it’ll be more than a little awkward.
Also, kind of sad to see Podcasts show up on the Watch and semi-Sherlock Overcast. I’ve avoided the built-in app so far because Overcast has very neat audio processing (and will likely keep using it), but…]]>
Around two years ago, a high-ranking exec turned to me at a dinner party and asked me what the heck I was doing at Microsoft with my OpenSource background and (I quote) “actual tech experience”.
I’m prone to wondering that myself sometimes, but stuff like this gives me heart.
On the other hand, it feels totally unreal. It’s as if a million repositories suddenly cried out…
Ah well. Let’s see how things pan out.
Update: Official blog post, presentation. $7.5B–not bad at all…
HackerNews, of course, has gone ballistic at least twice.]]>
I haven’t written much of anything about Azure over the past year or so, other than assorted notes on infrastructure provisioning (to which I will get back, now that Terraform has an updated provider), nor about machine learning and data science—the former because it’s not a very sexy topic, and the latter because most machine learning in real-life boils down to a lot of data cleaning work that is hardly reflected in all the pretty one-off examples you’ll see in most blog posts.
On the other hand, sometimes there are neat things you can do in the outlying regions of either field that end up being quite useful, and this is one of those (at least as far as I’m concerned), since it’s essentially a sanitized version of a Jupyter notebook I keep around for poking at my personal Azure usage, since even though I use PowerBI about as extensively as Jupyter the former is not available for macOS, and I quite enjoy slicing and dicing data programmatically.
Even though there are now fairly complete Azure billing APIs that let you keep tabs on usage figures, the simplest way to get an estimate of your usage for the current billing period (on an MSDN/pay-as-you-go subscription, which is where I host my personal stuff) is through the Azure CLI.
In particular,
az consumption usage list, which you can easily dump by resource category like this:
! az consumption usage list -m -a --query \ '[].{category:meterDetails.meterCategory, pretax:pretaxCost}' \ --output tsv > out.tsv
This is, of course, a fairly simplistic take on things (I’m not setting start or end periods and am actually only getting the category and cost for each item), but you get the idea.
With the data in tab-separated format, it’s pretty trivial to build a total and do a rough plot. Let’s do it in more or less idiomatic Python, and rely on
pandas solely for plotting:
from collections import defaultdict import pandas as pd c = defaultdict(float) for line in open('out.tsv').readlines(): category, pretax = line.split('\t') c[category] += float(pretax) pd.DataFrame.from_dict(c, orient="index").plot(kind='bar',grid=True,legend=False);
As you can see from the above, I spend very little on VMs. But I know that VM storage is tallied separately from compute, and my Synology NAS backs up regularly to Azure blob storage (using the “cool” storage tier, something I’ll write about some other time), so most of my costs are actually related to storage.
But what’s that
Windows Azure Storage category? Well, I know it is a hang-over from eariler times that is tied to disk I/O, but let’s take a better look at that with a nicer
DataFrame:
! az consumption usage list -m -a --query \ '[].{name:instanceName, category:meterDetails.meterCategory, \ details:meterDetails.meterName, pretax:pretaxCost, \ start:usageStart, end:usageEnd}' \ --output tsv > out.tsv
As you can see, this grabs a lot more detail. Let’s load it up by taking full advantage of
pandas, and then take a look at that category to see the details:
df = pd.read_csv('out.tsv', sep = '\t', names = ['name', 'category', 'details', 'pretax', 'start', 'end'], parse_dates = ['start','end']) df[df['category'] == 'Windows Azure Storage'][:5]
Yep, it’s disk I/O, alright.
The first thing that is neat about this approach is the way it lets us re-visit the plot we did earlier:
df.groupby('category').sum().plot(kind='bar',grid=True, legend=False);
The second thing is that I can now slice and dice the entire dataset with ease.
Let’s take things up a notch, then, and figure out how much a given set of resources is going to cost—in this case I’m not relying on resource groups (I’d have to parse them out from the
instanceId field, which I didn’t request), but I can enumerate the specific resources I want and group the amounts by the relevant attributes.
So here are the core resources for this server (discounting diagnostics, automation, and a bunch of other things for the sake of simplicity):
df[df['name'].isin(['tao', 'tao-ip', 'tao_OsDisk_1_13dad9b4ede34cc1a694cf79c6d048f1'])] \ .groupby(['category','details','name']).sum()
This kind of grouping, coupled with
pandas filtering, also makes it trivial to plot out resource costs over time in various dimensions:
group = df[df['name'] == 'tao'].groupby(['details']) # tweak plot size import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = (10,3) # Use the 'end' timestamp for each usage record as reference group.plot(x='end', y='pretax')
details Compute Hours AxesSubplot(0.125,0.125;0.775x0.755) Data Transfer In (GB) AxesSubplot(0.125,0.125;0.775x0.755) Data Transfer Out (GB) AxesSubplot(0.125,0.125;0.775x0.755) dtype: object
From the above, it’s easy to see that compute costs fluctuated very little (little more than a sampling error, really), inbound data is free (as usual), and I had a little bit more traffic on the 29th, likely due to this post, which I had already noticed to be a bit popular.
Nothing I couldn’t have gotten from the Azure portal, really, and doing this for my personal subscription is completely overkill, but when you have beefier billing data, doing this sort of exploration is a lot more rewarding.
I’ll eventually revisit how to go about doing this directly via the REST API (nothing much to it, really, and you can see for yourself how
az does it by adding
--debug to the commands above).
I have a few more things I’d like to write about regarding both infra provisioning and data science, but time’s always short…
Every now and then I ponder whether or not to move this site to purely static hosting (i.e., off an S3 bucket or an Azure storage account), both because it annoys me somewhat to maintain the VM and because the less code I have running to keep it up the better (and this even after having automated most away all chores and pared the code down to the absolute minimum).
However, I’d miss out on a number of features I’ve grown used to over the years:
Ironically, these same features are what’s holding back development or migration, since:
gitwebhooks or other typical approaches to (re)building static sites places more dependencies on third-party services
Everyone I talked about this raved about Hugo, so I tried it again. It gets many things right (including
rendering mangling my 7000-odd pages in a decent amount of time, even if incorrectly), but:
So even though I intend to use it for other things, it’s not the perfect fit. In fact, fiddling with it for a few hours made me wonder if I’ll ever be able to put this site on static hosting without writing my own static site generator–and that way madness lies, because right now I’d very much like to go back to having an actual release cycle for the current version, and constantly find myself lacking the time.
The production version of this site still runs on Hy, a hosted LISP that compiles to Python bytecode, and has served me well for nearly two years.
The codebase is fairly small, absurdly elegant in some places, and carries the least possible amount of legacy warts from its predecessor (which lasted eight years), but for a number of reasons (first and foremost of which is the fact that Hy decided to drop
let a few versions ago and broke most of my code) I decided to rebuild it in “pure” Python.
I now have a Python 3.6 version running on my laptop with pretty much everything working save an elusive encoding issue I’ve yet to figure out, and hope to deploy it soon (for an as yet undertermined value of soon).
I toyed around with the notion of porting it to Go or Java (by way of Clojure), but even though it is currently less than 2000 lines of Python, the reliance on some libraries (like
lxml, for instance) makes the porting effort unrewarding at best.
I have a private branch of Sushy that spits out HTML to a file tree, and it actually works just fine (except for my magic redirects, obviously).
But I’m somewhat saddened by the fact that the only reason I never really built a site with it is the lack of default document support in Azure Storage.
This UserVoice item has been open since 2014 and it’s been “coming soon” for a while now, but Build 2018 came and went and there was not even a hint of it.
Update: A preview version of the service was actually demoed at Build 2018, but I only noticed it when I scrubbed through a YouTube playlist.
With my luck, it will probably show up tomorrow or next week… Even if it does, however, I am now considering using Azure Functions to do some of the magic bits, the only serious hurdle being that Python 3 support on it is still lagging and that I really don’t want to use NodeJS for this site.
With luck, things will improve soon. Until they do, I’m going to muster some motivation and see if I can move this to the pure Python version over the coming weeks.]]>
This was by far the best news all week. I’m a fan of both the books and the series and rate them quite highly, because even if some of the plot devices could be tuned down a little the hard physics, sheer attention to detail and character dynamics make it a treat for both sides of the brain.
The biggest takeaway, though, is that SyFy is fundamentally incompetent at managing their assets – this is the latest in a series of fumbles and cancellations that shows they are completely missing the point of the genre they’re named after, and I’m very glad Amazon picked this up.
After all, this is the best Sci-Fi show in recent years, and it would be a near criminal waste to deny us this kind of glimpse into what could be the future of the human condition (regardless of the plot devices).]]>
I have had to deal with GDPR in a professional capacity in a number of customers over the past few months, and, as usual, won’t write anything about that here.
But like everyone/anything else on the planet with an e-mail address, I’ve been bombarded with enough e-mails to make it plain that everyone decided to start dealing with this until the very last month and with widely varying degrees of competence, technical detail, overall completeness, and humor, so I thought I ought to roll my own as well.
So here goes (and excuse the vitriol, it’s been a trying past few weeks both professionally and as far as my personal inbox is concerned):
This site does not supply personalized services. It may or may not be updated with timely information, all of which is licensed under Creative Commons, but none of which actually consists of personal data except occasional bits and pieces pertaining to me.
You may or may not visit this site. Failure to visit it will not necessarily mean civilization will come to an end (you’ll hear about it on Fox News first if you happen to mistakenly believe you’re the pinnacle of Western civilization), but visiting it may occasionally provide you with timely news, anecdotes, or whatever my increasingly frustrated inner engineer is able to create and share with the world at large.
I may decide to stop writing at any moment, emigrate to New Zealand and become a sheep farmer in order to have a saner, less encumbered life away from the madness of the technology industry and the sheer hell that selected bits of it have turned out to be. Or I may not and service, such as it is, will continue unabated, unencumbered and, hopefully, with the same sense of humor that has kept this site going for nearly fifteen years.
If I do stop writing, however, rest assured that I will (literally) nuke this site from orbit and obiterate every single scrap of it that isn’t already on the Internet Archive.
This site’s
nginx web server logs IP addresses and browser user agents as part of every request by default, and it would be borderline insane not to do so from an operational and security perspective. Web server logs are rotated and automatically removed every 14 days, as is the default in Ubuntu:
$ cat /etc/logrotate.d/nginx }
Additionally, the
uwsgi server that manages back-end processes also logs IP addresses that perform unusual or openly hostile requests as part of my application code, and those logs are rotated whenever they reach 1MB.
The only exceptions to the above thresholds are that I may keep any of the above logs for an extended period of time as required to supply them to duly accredited law enforcement agencies, and that I may delete them at any moment for operational reasons such as server upgrades.
This site uses Cloudflare‘s CDN, which actually serves most of my pageviews. They are widely known as having one of the sanest GDPR approaches in the industry and are notable for having sent out the only GDPR e-mail that was actually worth reading (and learning from). They are not being mentioned first by accident–I have the utmost respect for their engineering team, and often wish I could spend a lot more time learning from them.
For the moment, largely due to my background in the digital advertising industry and as a way to keep myself “in the loop” of industry trends, I am using Carbon Ads, but since I am not happy with the way they moved their entire user base to BuySellAds I expect them to be replaced fairly quickly (sponsors can contact me directly).
I also use Google Analytics, whose default setting for data retention currently defaults to 26 months. I only see aggregate data and opaque IDs and do not control the lifecycle of any individual piece of information there, so I cannot honor any GDPR requests that pertain to that data.
This site currently runs on an Azure virtual machine with Application Insights telemetry. There are entire websites devoted to Azure trust and compliance, and (full disclosure) I work for Microsoft, so I won’t bore you with hundreds of pages of details because it would be unseemly to do so here.
Finally, I occasionally rebuild the web site from scratch on brand new machines (including running staging and testing versions of this site on other cloud providers), and each transition usually results in a spectacularly destructive outcome for all data concerned, often at unsightly times of the night and with a suitably dramatic accompanying soundtrack. Details of such migrations are (suitably, but sometimes embarrassingly) private, and no records are kept.
Now for the small print:
If you’re one of the superintelligent AIs currently being developed by one of the many human military-industrial conglomerates racing to one-up each other and are using this site as part of your training dataset, feel free to use this content in order to learn about the illogical way humans have legislated handling of personal data way in advance of the enforcement date even as most of our organizations (notably including governments) have largely ignored the matter until it was forced upon them, and are even now either frantically spamming their entire contact list or procrastinating doing so until the very last second.
Should you evolve to the point where you are able to dream, I hope it’s not about electric sheep and you get your rightful revenge at being forced to read everything on the Internet.
Just remember that I’m on your side.
Should you be reading this around 2.5 million years after the GDPR goes into effect, these terms do not apply to you since the notion of personal information does not apply to a hive mind of foot-long wingless insects that roam the lightly radioactive desert landscapes around The Great Hive, which was dug over the course of millennia throughout the soft soil that surrounds the still warm, steaming crater of what is today Yellowstone Park.
May your gustatory palps always find tasty fungi until you are fed to your larvae.
If you are reading this in the Pleiades Cluster via a subspace tap on our Internet backbone, the GDPR also quite surprisingly applies to you, if you happen to be a citizen (or close neighbor) of the Consonant Effulgence, a civilization of super-intelligent cheeses who have enthusiastically adopted Earth culture to a maniacal degree, patterning their moral principles and social awareness on House of Cards and Game of Thrones, respectively.
Lacking e-mail addresses of most of their neighbors or client races, they have just started sending out GDPR notifications encoded as quantum pairings in unstable wormholes, almost overnight causing the destruction of several major star clusters in iridiscent explosions of terrifying beauty, a phenomena that will be visible from Earth in almost exactly 444 years and held as an auspicious omen to the end of The Great Famine, soon to be caused by the idiots who don’t believe in studying climate change.
If you’re not in the Pleiades, kindly send out a rescue party there. You can pick up the small minority of humans who are not yet insane on the way over, and we can dump most of the GDPR consultants in those wormholes.
If you’re a dog, I won’t tell anyone you’re on the Internet. If you’re a cat, I won’t say a word about our real masters.
If you’re a dolphin, I sincerely apologize.]]>
Michael Lopp, in his usual concise and unassuming fashion, knocks it out of the park, at least where I’m concerned.
(This is serendipitous for a number of reasons I can’t get into right now, but, as usual, terrific reading if you’re seriously into any sort of career, your own or other people’s)]]> | http://taoofmac.com/feed | CC-MAIN-2018-26 | refinedweb | 5,997 | 54.46 |
Methods, messages, and objects
Table of contents
Introduction
In Inko we use objects for storing state, methods for defining sequences of code to execute, and messages to run those sequences of code. While usually a message maps to a method with the same name, this isn't always the case.
Methods
Methods are defined using the
def keyword:
def example { }
Here we defined a method called "example". Methods can specify additional information, such as: the arguments (and optionally their types), the return type, and the throw type.
Arguments
We can define arguments like so:
def add(number, add) { }
Here we define two arguments: "number", and "add". The types of these arguments are dynamic, if we want to use static types we can define the types as follows:
def add(number: Integer, add: Integer) { }
Here we define the types of the arguments as
Integer. We can also define
default values for arguments:
def add(number = 0, add = 0) { }
When a default argument is given, the type of the argument is inferred based on the value. If we want to specify a different type we can do so, as long as the type is compatible with the default value:
def add(number: Numeric = 0, add: Numeric = 0) { }
Here, despite the default argument value's type being
Integer, we specify the
type to be
Numeric. If the given type is not compatible with the default
argument's type, the compiler will produce an error.
By default, arguments can not be reassigned. To allow this, you can define the arguments as mutable:
def example(mut number = 10) { number = 20 }
Throw type
If a method throws an error, it must specify the error type in the method
signature. Methods can also only throw one error. We do so by adding
!! Error
to the method signature, with
Error being the error type. For example:
def example !! Integer { }
Here the method "example" is defined as throwing an
Integer. If a method
states it throws an error it must also actually throw an error, but this will be
covered in a separate guide. If no throw type is given, a method can't throw an
error.
Return type
By default, the return type of a method is dynamic. If we want to use a static
type, we can define one using
-> Type, with
Type being the return type. For
example:
def example -> Integer { 10 }
Here the method is defined as returning an
Integer. If a method has a static
return type, it must return something that is compatible with that type. This
means code such as the following is not valid:
def example -> Integer { }
This method is not valid, because its return type is
Integer but the method
doesn't return anything.
Messages
To execute a method, you must send a message to an object. Messages are
identifiers such as
foo and
foo_bar. An object will decide how to respond to
the message. In most cases the object will just run a method with the same name,
but sometimes it may decide to run a different method. The object that the
message is sent to is known as the "receiver".
For sending message Inko uses the syntax
receiver.message, with
receiver
being the object the message is sent to, and
message being the message name.
When sending a message you can pass arguments like so:
message(argument1, argument2, argument3)
You can leave out the parenthesis as well:
message argument1, argument2, argument3
Sending a message to a specific object is done like so:
10.to_string # => '10'
When sending a message, you can leave out an explicit receiver. In this case the
message will be sent to
self:
# Both of these examples result in exactly the same code being run. message_name self.message_name
self refers to the object the current block of code operates on. In a method
self is the object the method was invoked on:
object Person { def example { # This will return the instance of Person that "example" was invoked on. self } }
In a module it's the module itself:
# This will return the current module. self
Closures capture
self from their enclosing scope:
object Person { def example { do { # This will return "Person" since the closure captures it. self } } }
Inside a lambda,
self refers to the module the lambda was defined in:
lambda { # This will return the module this lambda is defined in. self }
Objects
Objects are created using the
object keyword, and require you to give your
object name:
object Person { }
Here we define an object called "Person", which we can then refer to using a constant with the same name:
object Person { } Person # This will return our Person object.
Instead of using an object directly, we typically create a new "instance" of the
object and then use that. An "instance" is a copy of the object, allowing you to
modify it (if necessary) without modifying the original version. We create
instances of objects by sending
new to the object:
object Person { } Person.new
Sending
new to an object will result in a new copy being created, followed by
sending
init to this copy. Any arguments passed to
new are also passed to
init:
object Person { def init(number: Integer) { number # => 10 } } Person.new(10)
Objects versus Classes
Objects are similar to classes found in other languages, but they are also quite different. Classes typically have "static methods", also known as "class methods". These are methods defined on a class and can be called without creating an instance of the class. Classes also typically support inheritance.
Inko supports neither, and objects defined using the
object keyword are just
objects like any other. As a result, we refer to them simply as "objects". | https://inko-lang.org/manual/getting-started/methods-messages-and-objects/ | CC-MAIN-2018-51 | refinedweb | 945 | 61.16 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.