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 |
|---|---|---|---|---|---|
Usually we prepare WCF services and host them in IIS which is useful when there are different clients accessing the service from outside the system. But if the service is intended for local system clients, then it would be a better idea to host the WCF service as a Windows service. In this article we see how to create a WCF service and make it run as a Windows service.
Using this application as sample anybody can design their applications in n-tier model using WCF.
For this we follow a tiered architecture, where the service resides at one location, hosted at another and consumed from another location.
To have a clear understanding about what we are going to do, here is the agenda:
As our main intention is to show how to follow these steps, we are preparing a really simple service to make things less complicated. This service takes the JobId of Jobs table of default pubs database and in result gives the Job description and some other data .
So, without much ado we start building our applications.
The WCF Service Library template is present under WCF project type while creating a new project in Visual Studio.
So, create a New Project ->navigate to WCF option -> select WCF Service Library and give some name. Here we are naming it as WCFJobsLibrary.
This will create a service library with a default service interface and a class to implement it. As we don’t need them, we simply delete them and create a service with our own custom name. For this, in Solution Explorer, right click on the project, select Add -> New Item and choose WCF Service. We name it as Jobs.
This step will create an IJobs interface and Jobs class. Also, the service configuration for Jobs will be automatically written in App.Config by Visual Studio. You can see this if you scroll down to <services> tag for end point details and <behaviors> tag for service behaviour under <system.serviceModel>.
Jobs
<behaviors>
<system.serviceModel>
By default, two endpoints will be created- one which uses wsHttpBinding and a mex endpoint with mexHttpBinding. The mex endpoint provides metadata to the client for creating a proxy, the process which we’ll discuss later.
wsHttpBinding
mexHttpBinding
Right now, we’ll proceed to write the code for our service. In Jobs class we are going to define a method which returns a complex type with Job details. For this complex type we should prepare a class with all the required fields. So, add a new class from Add -> New Item and name it as Job.cs.
The class must be specified by [DataContract] attribute to make it serializable and WCF-enabled. Similarly the properties should be specified with [DataMember] attribute. As these attributes are present in System.Runtime.Serialization namespace which is not available in the class by default, we need to import that namespace.
[DataContract]
[DataMember]
System.Runtime.Serialization
using System.Runtime.Serialization;
namespace WCFJobsLibrary
{
[DataContract]
public class Job
{
[DataMember]
public string Description { get; set; }
[DataMember]
public int MinLevel{get;set;}
[DataMember]
public int MaxLevel { get; set; }
}
}
Now, our next step is to add the contract. For this, in IJobs interface we specify our methods and decorate them with [OperationContract] attribute.
[OperationContract]
[ServiceContract]
public interface IJobs
{
[OperationContract]
DataSet GetJobs();
[OperationContract]
Job GetJobInfo(int Jobid);
}
Here the two methods perform nearly the same action, with a slight difference that GetJobs() method will fetch all the records in the Jobs table, whereas GetJobInfo() will fetch only the record matching the given Jobid.
GetJobs()
GetJobInfo()
GetJobs() returns a DataSet which is an in-built complex type, whereas GetJobInfo will return Job type which we have already defined in our Job class.
GetJobInfo
We implement the IJobs interface in Jobs class. For this we go to Jobs class and right click on IJobs and select Implement Interface option to implement IJobs interface automatically in Jobs class. When this is done, we get empty methods where we have to write our code. The code for the methods is written as follows:
IJobs
public class Jobs : IJobs
{
#region IJobs Members
public System.Data.DataSet GetJobs()
{
SqlConnection cn = new SqlConnection("data source=mytoy; user
id=sa; database=pubs");
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("Select * from jobs", cn);
da.Fill(ds, "jobs");
return ds;
}
public Job GetJobInfo(int Jobid)
{
SqlConnection cn = new SqlConnection("data source=mytoy; user id=sa;
database=pubs");
cn.Open();
string sqlstat = "select * from jobs where job_id=" + Jobid;
SqlCommand cmd = new SqlCommand(sqlstat, cn);
SqlDataReader dr=cmd.ExecuteReader();
Job jobObj=new Job();
if(dr.Read())
{
jobObj.Description=dr["job_desc"].ToString();
jobObj.MinLevel=Convert.ToInt32(dr["min_lvl"].ToString();
jobObj.MaxLevel=Convert.ToInt32(dr["max_lvl"].ToString();
}
else
jobObj.Description="-1";
return jobObj;
}
#endregion
}
There’s nothing much to discuss in this code, which performs the task of retrieving required data from the database. For clarity, all the connection strings and statements are hard-coded here, but you can do it in a standard way. The main thing to note here is that these two methods are getting data from database and returning it in complex types.
With this our service is ready. To pack it in an assembly we should build the project. After successfully building, we’ll get a dll in bin folder of project directory which is WCFJobsLibrary.dll.
Testing the WCF Service
After the library is built, run the assembly. This will host our service in the test environment. A new icon appears in task bar which shows that the service is hosted.
Also a test client window is opened which gives the status information that the service is successfully added.
The service client has the information of the address and binding that is used. It even has the info of the methods that are available for consumption. In test environment, some methods may not be supported, which is because some complex types are not supported by the test client. For whichever methods are not supported, an exclamation mark appears beside the name of that method as shown in above screenshot for GetJobs().
Nevertheless, we can test the other method GetJobInfo(). Just click on that service method in test client window and it will show the service info at the right side of the window. This info is divided into Request and Response parts. In Request the parameter names, their values and types are listed. Similarly in Response the info of return types are given. When we enter a parameter value in Request and press the invoke button, it will give the result in Response as shown in screenshot below.
But if the test client window is closed, the service is also removed from the host environment. To make the service independent of this test client, we have to detach the test client from the project. To do this go to WCFJobsLibrary properties and move to the Debug tab. Here we’ll find the test client name in command line arguments box. Removing the client name from that box will detach the client from the service.
WCFJobsLibrary
As we have successfully tested the service, our next step is to consume it. For this we create a windows app as our client.
Create New > Project > Windows Forms App and name it as ConsumeJobs.
We design the form as shown below with a textbox to provide the JobId, a button to invoke the sevice and a few more textboxes to display the results. Similarly we use a DataGridView and another button to display all the records in Jobs table.
JobId
To communicate with the service, the client should have a proxy.
For creating a proxy the client needs the reference of WCF service.
For adding reference go to Solution Explorer and right click the project (client app) and choose Add Service Reference. A window opens where we have to give the address of the service. We can copy this address from the base address in app.config file of our WCF Service Library. If the communication between the client and server is through http, then we can use that address as it is, otherwise if it is through any other channel, then we need to add ‘/mex’ at the end of the address.
For example if the base address is :
then for any channels other than http we have to add ‘/mex’ at the end like this:
After providing the address and clicking the Go button, the services available at that address are found and also a list of interfaces at that services are shown. It should be remembered that this step will be successful only if the service is running.
Select the service and provide a meaningful name for the namespace(alternately you can use the default name as well). In our case we provide the name as JobsService. When the ok button is clicked, a proxy will be created at the client with a similar name as the original class at the service, but suffixed by the word ‘client’. In the WCF Service library as our class name is Jobs, at the client side the proxy name will be JobsClient.
As the proxy class is created we can proceed to write the code in button click events of the client Windows form.
private void btnViewDetails_Click(object sender, EventArgs e)
{
//an instance of the proxy class
JobsService.JobsClient obj = new ConsumeJobs.JobsService.JobsClient();
//Reading the result into complex type object (Job type)
JobsService.Job jobObj = obj.GetJobInfo(int.Parse(txtJobId.Text));
//Displaying result in text boxes
txtDescription.Text = jobObj.Description;
txtMinValue.Text = jobObj.MinLevel.ToString();
txtMaxValue.Text = jobObj.MaxLevel.ToString();
}
private void btnShow_Click(object sender, EventArgs e)
{
JobsService.JobsClient obj = new ConsumeJobs.JobsService.JobsClient();
DataSet ds = obj.GetJobs();
dataGridView1.DataSource = ds.Tables[0];
}
We get the result from the database which is retrieved by the service program and which is in turn accessed by a proxy class at the client.
Till now we have seen about consuming the service when it is hosted in the hosting environment provided by Visual Studio. Now we’ll see how to register this service with Windows so that it runs as a Windows service.
For this, first we have to create a Windows service. This can be done from Visual Studio using the Windows Service template which can be found under Windows project type.
New > Project > Windows Service > name it as ABCService
We have to add the reference of our WCF DLL in this service. To do this, right click on the project in Solution Explorer and select Add Reference. For adding the dll in reference, select browse tab in the window that appears, and navigate to the folder where our WCF service library is located. In that location, the dll can be found inside the bin-> debug folder. When this dll is added, it is imported into the Windows service app.
Similarly we need reference of System.ServiceModel namespace because it is not available by default in Windows Service. To go to the code window of the service class, go to the design view of the service that is created by default and click on the link ‘click here to switch to code view’. This link will take you to the code view. Import the System.ServiceModel namespace here as it is required for hosting our WCF service. The default service class Service1.cs provides two events – OnStart and OnStop. We can write our code as what we want to do when our service starts and stops in these two events respectively.
System.ServiceModel
The code for this class is written as shown below:
namespace ABCService
{
public partial class Service1 : ServiceBase
{
ServiceHost sHost;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
sHost = new ServiceHost(typeof(WCFJobsLibrary.Jobs));
sHost.Open();
}
protected override void OnStop()
{
sHost.Close();
}
}
}
We are just creating a service host for our WCF library in the OnStart event and opening it. When the Windows service is closed, it should close the service host, which is specified in the OnStop event.
Merely writing this code will not suffice as we need to have the configurations also. We need to do the configurations in order that the service be hosted and run properly as needed. These configurations are to be specified in App.Config file in the Windows Service app. As this file is not available by default, we have to create it by adding it as a new item and selecting the Application Configuration File template.
The created App.Config file has empty configurations i.e. no configurations are specified under <configuration> tag. Instead of tediously writing all these configurations we can just copy them from the App.Config of our service library. Copy everything available under <system.serviceModel> and paste it in App.Config of the windows service.
Now build the service. This will complete our steps of hosting our WCF service as a Windows service. Now only thing remaining is to register it with Windows OS.
ServiceProcessInstaller
ServiceInstaller
Click on ServiceProcessInstaller and set its account property to local system.
Now, click on ServiceInstaller and provide some display name, say, ABCNITJobsService. Also choose the start type- manual or automatic or Disabled. In our case we can either choose manual or automatic.
ABCNITJobsService
This exe file should be registered with Windows OS to make it run as a service.
In that path write the command InstallUtil ABCService.exe which registers the service with Windows OS.
Once it is registered with Windows, we can see it in the services list.
(Control Panel > Administrative Tools > Services)
If it is not automatically started, we can start it manually by clicking the start link.
As the service is running as a Windows service there is no need for our WCF service library to be running. We can close it and can use the service from Windows environment.
Note: If Vista OS is used, then it should be run in Administrator mode for hosting. | http://www.codeproject.com/Articles/38160/WCF-Service-Library-with-Windows-Service-Hosting?fid=1543822&df=90&mpp=25&sort=Position&spc=None&tid=4015234 | CC-MAIN-2014-41 | refinedweb | 2,314 | 64.81 |
If the replica count is set to 100, and the demand is too little, even then the 100 pods will be up and running. This results in waste of CPU and memory resources. Yes, it offers reliability, in the sense that if a node crashes and pods within it die, the Replica Set controller would try to bring back the number of pods back to 100 by spawning pods in other nodes. The application stays online.
In a more abstract sense, the Replica Set would try to achieve a desired state of the cluster and would look at the current state and figure out how it can achieve the desired state.
However, we would like something a bit more sensitive to the real-world demand. Enter Horizontal Pod Autoscaler. It is the job of Horizontal Pod Autoscaler to scale the application up when there is need for it and then scale it back down once the workload drops.
Why use a Horizontal Pod Autoscaler?
As the name suggests, this component would scale your application automatically. In the cloud, this can really help you reduce the compute and memory resources you will be billed for. Since the Autoscaler is sensitive to the resource utilization, when it sees that a lot of pods are just sitting idle it scales the application down and when the demand on those pods increases it scales the application up by creating new pods and the load gets distributed to those.
It can save you both valuable time and compute resources. You won’t have to worry about what the Replica count should be for your pods when writing a deployment, autoscaler would manage that for you.
Initial Setup
First and foremost requirement would be for you to have a running Kubernetes cluster. Use Katacoda Playground which is perfect for experimentation and learning about Kubernetes. The next thing you would require is a metric server.
This add-on to your Kubernetes system (kube-system namespace) would gather metrics such as CPU and memory usage from two different perspective:
- Resource used by each pod
- Resource consumed at each node
Metrics from both the perspective are crucial in helping Autoscaler decide what its next move should be. To add metric server to your Kubernetes cluster, follow this guide. Now we are ready to see Horizontal Pod Autoscaler in action.
Using the Autoscaler
To see the Autoscaler working, we need a test application. Let’s create a simple php-apache server and expose it as a service.
--port=80
The image used in here is one of the sample images provide by the Kubernetes project. It performs some CPU intensive tasks and makes the process much more apparent by doing so.
To autoscale this deployment, we need to inform the autoscaler what are the minimum and maximum number of pods that we will allow and CPU percentage that they are allowed to use. There are many more factors that you can consider like memory, storage and network as well.
In the current state, since no one is consuming this service, it will most like stay at the minimum value. You can check the state of all autoscaled deployment in the default namespace by running:
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE
php-apache Deployment/php-apache 0%/50% 1 10 1 2m
Generating Load and Testing the Autoscale Feature
You can see the number of replica is still only one and CPU load is insignificantly low. We can create additional load and see how the autoscaler responds to it. The service that exposes our php-apache pods is not exposed to the outside world, so we will create a temporary pod and open an interactive shell session in that pod.
This will allow us to communicate with all the services available in the cluster, including the php-apache service.
/ #
You will notice that the prompt will change indicating that we are inside this container. Let’s now try and put some load on our service by repeatedly making requests. In the new prompt, let’s run the following while loop:
Open a new terminal, since we can’t let this loop terminate just yet. Upon inspecting the autoscaler you will see the CPU utilization and upon listing the pods you will see there are now multiple instances of php-apache server,
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE
php-apache Deployment/php-apache 121%/50% 1 10 4 1h
$ kubectl get pods
NAME READY STATUS RESTARTS AGE
busybox 1/1 Running 0 6m
php-apache-8699449574-7qwxd 1/1 Running 0 28s
php-apache-8699449574-c9v54 1/1 Running 0 10h
php-apache-8699449574-h9s5f 1/1 Running 0 28s
php-apache-8699449574-sg4hz 1/1 Running 0 28s
Terminate the while loop and the number of pods will die down to one in a few minutes.
Conclusion
So that’s a simple demonstration of Horizontal Pod Autoscaler. Remember to have a functional metrics-server for your cluster and while creating a deployment keep the replica count at 1. The horizontal pod autoscaler will take care of the rest. | https://linuxhint.com/kubernetes_horizontal_pod_autoscaler/ | CC-MAIN-2021-21 | refinedweb | 849 | 58.32 |
Haskell: Reading files
In writing the clustering algorithm which I've mentioned way too many times already I needed to process a text file which contained all the points and my initial approach looked like this:
import System.IO main = do withFile "clustering2.txt" ReadMode (\handle -> do contents <- hGetContents handle putStrLn contents)
It felt a bit clunky but I didn't realise there was an easier way until I came across this thread. We can simplify reading a file to the following by using the readFile function:
main = do contents <- readFile "clustering2.txt" putStrLn contents
We need to read the file in the IO monad which explains why we have the 'do' notation on the first line.
Another thing I didn't realise until recently was that you don't actually need to worry about the 'do' notation if you try to read from the IO monad inside GHCI.
In this context we're reading from the IO monad when we bind 'readFile' to the variable 'contents' since 'readFile' returns type 'IO String':
> :t readFile readFile :: FilePath -> IO String
We can therefore play around with the code pretty easily:
> contents <- readFile "clustering2.txt" > let (bits, nodes) = process contents > bits 24 > length nodes 19981 > take 10 nodes [379,1669,5749,6927,7420,9030,9188,9667,11878,12169]
I think we're able to do this because by being in GHCI we're already in the context of the IO monad but I'm happy to be corrected if I haven't explained that correctly.
About the author
Mark Needham is a Developer Relations Engineer for Neo4j, the world's leading graph database. | https://markhneedham.com/blog/2013/01/02/haskell-reading-files/ | CC-MAIN-2019-13 | refinedweb | 271 | 60.38 |
Subject: Re: [OMPI devel] [OMPI svn-full] svn:open-mpi r20568
From: George Bosilca (bosilca_at_[hidden])
Date: 2009-02-17 11:18:25
I guess that if the free function supports the NULL pointer we should
do the same...
george.
On Feb 17, 2009, at 07:35 , Jeff Squyres wrote:
> On Feb 16, 2009, at 9:16 PM, George Bosilca wrote:
>
>> Based on several man pages, free is capable of handling a NULL
>> argument. What is really puzzling is that on your system it
>> doesn't ...
>>
>> I tried on two system a 64 bits Debian and on my MAC OS X with all
>> memory allocator options on, and I'm unable to get such a warning :(
>
> Remember that the warning is in our code -- opal/util/malloc.c:
>
> -----
> void opal_free(void *addr, const char *file, int line)
> {
> #if OMPI_ENABLE_DEBUG
> if (opal_malloc_debug_level > 1 && NULL == addr) {
> opal_output(opal_malloc_output, "Invalid free (%s, %d)",
> file, line);
> return;
> }
> #endif /* OMPI_ENABLE_DEBUG */
> free(addr);
> }
> -----
>
> Are you saying that we should remove this warning?
>
> --
> Jeff Squyres
> Cisco Systems
>
> _______________________________________________
> devel mailing list
> devel_at_[hidden]
> | http://www.open-mpi.org/community/lists/devel/2009/02/5442.php | CC-MAIN-2013-48 | refinedweb | 176 | 53.34 |
ISWCTYPE(3) NetBSD Library Functions Manual ISWCTYPE(3)Powered by man-cgi (2020-09-24). Maintained for NetBSD by Kimmo Suominen. Based on man-cgi by Panagiotis Christias.
NAME
iswctype -- test a character for character class identifier
LIBRARY
Standard C Library (libc, -lc)
SYNOPSIS
#include <wctype.h> int iswctype(wint_t wc, wctype_t charclass);
DESCRIPTION
The iswctype() function returns a boolean value that indicates whether a wide character wc is in charclass. The behaviour of iswctype() is undefined if the iswctype() function is called with an invalid charclass (changes of LC_CTYPE category invalidate charclass) or invalid wide character wc. The behaviour of iswctype() is affected by the LC_CTYPE category of the current locale.
RETURN VALUES
The iswctype() returns: 0 wc is not in charclass. non-zero wc is in charclass.
ERRORS
No errors are defined.
SEE ALSO
setlocale(3), towctrans(3), wctrans(3), wctype(3)
STANDARDS
The iswctype() function conforms to ISO/IEC 9899/AMD1:1995 (``ISO C90, Amendment 1''). NetBSD 9.99 March 4, 2003 NetBSD 9.99 | http://man.netbsd.org/iswctype.3 | CC-MAIN-2021-04 | refinedweb | 168 | 50.43 |
Quick tests
Sometimes a project demands that we code in a thorough, “belt and suspenders” fashion.
However many times it just isn’t necessary to go through all of the trouble — particularly when you’re trying out a new API for the first time and you really don’t need to build a production-ready project.
I find myself often throwing together a quick app to test something — in most cases I create a single button to initiate the test.
This article takes a look at three ways to accomplish this task. Pick the one which is right for you and the project you are working on.
Generally speaking an Android application’s UI is defined within an XML layout file. When you create a new project in Eclipse, the Android Developer Tools provide a layout (main.xml) that looks like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
android:orientation="vertical"
android:layout_width="fill_parent"
android:
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:
</LinearLayout>
Now, let’s add a Button widget to the mix,named “Hit Me”.
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hit Me"
andorid:
This Button needs to trigger an action in our code, so let’s have a look at the Java code behind this user interface.
Note that in order to work with a Button in code we need to import android.widget.Button.
import android.widget.Button;
And to wire up the handlers we define an instance of the android.widget.Button at the class level:
private Button btnHitMe = null;
Now, let’s get a reference to the widget within the onCreate method of our Activity class:
btnHitMe = (Button) findViewById(R.id.btnHitMe);
The R.id.btnHitMe enumeration is automatically generated by the Android Developer Tools when the main.xml file is modified and saved. When the optional android:id attribute is included in the definition of the widget as shown in the earlier listing, the ADT automatically creates the enumerations to identify this widget throughout the project. These values are stored in R.java. Never modify this file by hand — it is a fool’s errand as it is constantly being re-written by the tools.
Once we have a valid reference to the widget from findViewById, we need to set up the click handler to process Button interaction:
bHitMe.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
// process the button tap
}
});
Within this anonymous class we implement whatever code is relevant for our test.
Here is the complete code for this anonymous handler approach, choosing to display a Toast notification when the Button is tapped, or “clicked”.
package com.msi.linuxmagazine.hotwiregui;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.widget.Toast;
public class HotWireGui extends Activity {
private Button btnHitMe;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnHitMe = (Button) findViewById(R.id.btnHitMe);
btnHitMe.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
// process the button tap
(Toast.makeText(HotWireGui.this,"Clicked Me!",Toast.LENGTH_LONG)).show();
}
});
}
}
This code works fine though some Java folks might argue that anonymous classes are evil or some such other religious view about this code. Perhaps it is a bad habit, but not a topic for today’s discussion.
Evil or not, I prefer to not write all of this code so I tend to “cut-n-paste” this code from one project to the next. Let’s look at another approach — having the class itself be the “listener”.
Class level listener
The next approach to look at is where we have the Activity class implement the OnClickListener rather than employing an anonymous class.
To do this we need to import the Interface:
import android.view.View.OnClickListener;
Then we indicate that the class implements the Interface:
public class HotWireGui extends Activity implements OnClickListener
Of course, then we must actually implement this interface which means that we need a method named onClick which takes a single View argument. The full code is shown here:
package com.msi.linuxmagazine.hotwiregui;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.widget.Toast;
import android.view.View.OnClickListener;
public class HotWireGui extends Activity implements OnClickListener{
private Button btnHitMe;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnHitMe = (Button) findViewById(R.id.btnHitMe);
btnHitMe.setOnClickListener(this);
}
public void onClick (View v) {
// process the button tap
if (v.getId() == R.id.btnHitMe) {
(Toast.makeText(HotWireGui.this,"Clicked Me in onClick method!",Toast.LENGTH_LONG)).show();
}
}
}
Things to note about this code:
From a read-ability perspective, this approach may be easier as we’re not dealing with the nameless anonymous class. When there are many Buttons in play a bunch of calls to findByView followed by setOnClickListeners and the accompanying enclosed methods can be a bit tedious to sift through in the code — let alone write in the first place. With this single click handler and comparisons the code can be a bit easier to read and maintain. One downside however is that this one method is likely going to handle ALL clicks in the Activity.
OK, so let’s say you’re super lazy and you just don’t even want to do this modest amount of coding?
What can we do to wire up a Button without:
Can this really be done? Yes — let’s look at a really quick and dirty way to implement a click handler for an Android Button to help you build simple apps without the fuss of all of that boiler-plate code.
Cheating?
We start by looking at the code — there’s just not much to it so we’ll just walk through it quickly.
We start out with the Button definintion in the layout file — we need to make a small change there. Don’t worry, it’s worth it.
<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Hit Me”
android:id=”@+id/btnHitMe”
android:onClick=”HandleButton”
/>
This looks identical to the version we saw earlier with the exception that there is a single addition of a new attribute, namely android:onClick.
The value assigned to this attribute, HandleButton, refers to a developer-supplied method with the “onClick” signature of (View v).
Let’s have a look at the Java code implementing this Activity.
package com.msi.linuxmagazine.hotwiregui;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class HotWireGui extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void HandleButton(View v) {
if (v.getId() == R.id.btnHitMe) {
(Toast.makeText(HotWireGui.this,"Hot wired Button!",Toast.LENGTH_LONG)).show();
}
}
}
Note that the Button class is not imported. There is no definition of a Button instance. No calls to findViewById. No calls to setOnClickListener. No extra sets of curly braces to match up on the anonymous class’ onClick handler, etc.
We must however provide a method with the correct signature. In this case we’ve called it HandleButton.
In the code we evaluate the passed-in View instance and check it’s Id. If it matches the one we’re looking for we implement our code. This same routine can handle an arbitrary number of Button’s on the screen.
The other neat thing here is that we can have an arbitrary number of these methods, named however we like, to further segregate the code for the Buttons. Want a different click handler name for a set of Buttons? No problem, just reference it appropriately in the XML layout file for the android:onClick attribute.
I stumbled upon this approach when writing a remote control for a robot with a bunch of buttons. Coding all of that boiler-plate code just bothered me and I was pleased to settle upon this approach.
Is it right for you? Perhaps. Let me know what you think.
Usually posts some very exciting stuff like this. If you are new to this site.
The time to read or take a look at the content material or sites we have linked to below.
Normally I don’t read article on blogs, however I would want to
state that this write-up very pressured me to take a look at and do so!
Your writing taste has become amazed me. Thanks a lot, very nice article.
Here is my web site CharitaTFava
Always a massive fan of linking to bloggers that I really like but don?t get a great deal of link love from.
Every when in a while we pick blogs that we read. Listed beneath would be the most current sites that we select.
Below you will come across the link to some sites that we think you should visit.
Although sites we backlink to below are considerably not connected to ours, we really feel they may be essentially worth a go by way of, so possess a look.
Here is a superb Blog You might Find Interesting that we encourage you to visit.
We like to honor several other web websites around the web, even though they aren?t linked to us, by linking to them. Under are some webpages worth checking out.
Check beneath, are some totally unrelated sites to ours, nonetheless, they are most trustworthy sources that we use.
Below you?ll discover the link to some web-sites that we assume it is best to visit.
Check beneath, are some absolutely unrelated sites to ours, nevertheless, they are most trustworthy sources that we use.
Very few web-sites that occur to become detailed below, from our point of view are undoubtedly properly worth checking out.
Here is a good Blog You might Come across Intriguing that we encourage you to visit.
We prefer to honor numerous other world wide web web pages on the internet, even when they aren?t linked to us, by linking to them. Under are some webpages worth checking out.
We prefer to honor many other net web-sites around the net, even when they aren?t linked to us, by linking to them. Beneath are some webpages really worth checking out.
Usually posts some really interesting stuff like this. If you?re new to this site.
Just beneath, are several entirely not associated websites to ours, however, they’re certainly worth going over.
We came across a cool web site that you just could possibly appreciate. Take a appear for those who want.
One of our visitors not long ago recommended the following website.
Check below, are some totally unrelated internet websites to ours, nevertheless, they’re most trustworthy sources that we use.
Please stop by the web pages we follow, like this one, as it represents our picks from the web.
Wonderful story, reckoned we could combine a handful of unrelated information, nevertheless really really worth taking a appear, whoa did one particular study about Mid East has got much more problerms as well.
Although sites we backlink to beneath are considerably not connected to ours, we feel they’re in fact worth a go via, so have a look.
After all, what a great site and informative posts, I will upload inbound link – bookmark this web site? Regards, Reader.
Always a big fan of linking to bloggers that I enjoy but don?t get lots of link enjoy from.
Every as soon as inside a even though we decide on blogs that we study. Listed below would be the most current websites that we choose.
We prefer to honor several other net web-sites on the internet, even when they aren?t linked to us, by linking to them. Underneath are some webpages really worth checking out.
Check below, are some absolutely unrelated web sites to ours, even so, they may be most trustworthy sources that we use.
That may be the end of this post. Right here you will uncover some websites that we feel you?ll enjoy, just click the links.
Please pay a visit to the web pages we follow, like this a single, as it represents our picks in the web.
Here are some links to web-sites that we link to for the reason that we think they are really worth visiting.
Please check out the internet sites we stick to, like this one, because it represents our picks from the web.
Here are some hyperlinks to web-sites that we link to for the reason that we think they are worth visiting..
Wonderful story, reckoned we could combine some unrelated data, nevertheless truly really worth taking a look, whoa did 1 find out about Mid East has got a lot more problerms also.
The information talked about inside the article are a few of the ideal available.
The information and facts mentioned within the write-up are several of the top available.
We came across a cool site that you simply might love. Take a look in the event you want. | http://www.linux-mag.com/id/7844/ | CC-MAIN-2017-09 | refinedweb | 2,180 | 57.57 |
denodeno
A JavaScript runtime using V8 6.8 and Go.
Supports TypeScript 2.8 out of the box.
No package.json, no npm. Not backwards compatible with Node.
Imports reference source code URLs only.
import { test } from "" import { log } from "./util.ts"
File system and network access can be controlled in order to run sandboxed code. Defaults to read-only file system access. Access between V8 (unprivileged) and Golang (privileged) is only done via serialized messages defined in this protobuf: This makes it easy to audit.
Single executable:
> ls -lh deno -rwxrwxr-x 1 ryan ryan 55M May 28 23:46 deno > ldd deno linux-vdso.so.1 => (0x00007ffc6797a000) libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f104fa47000) libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f104f6c5000) libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f104f3bc000) libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f104f1a6000) libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f104eddc000) /lib64/ld-linux-x86-64.so.2 (0x00007f104fc64000)
Always dies on uncaught errors.
Supports top-level await.
Aims to be browser compatible.
Can be used as a library to easily build your own JavaScript runtime.
StatusStatus
Segfaulty.
No docs yet. For some of the public API see
And examples are around here:
Roadmap is here:
Compile instructionsCompile instructions
I will release binaries at some point but for now you have to build it yourself.
You need Protobuf 3. On Linux this might work:
cd ~ wget unzip protoc-3.1.0-linux-x86_64.zip export PATH=$HOME/bin:$PATH
Then you need
protoc-gen-go and
go-bindata and other deps:
go get -u github.com/golang/protobuf/protoc-gen-go go get -u github.com/jteeuwen/go-bindata/... go get -u ./...
Installing
v8worker2 is time consuming, because it requires building V8. It may take about 30 minutes:
go get -u github.com/ry/v8worker2 cd $GOPATH/src/github.com/ry/v8worker2 ./build.py --use_ccache
You might also need Node and Yarn.
Finally the dependencies are installed.
Now you can build deno and run it:
> make [redacted] > ./deno testdata/001_hello.js Hello World >
make commandsmake commands
make deno # Builds the deno executable make test # Runs the tests. make fmt # Formats the code. make clean # Cleans the build. | https://www.ctolib.com/ry-deno.html | CC-MAIN-2019-09 | refinedweb | 381 | 55.3 |
Is FREAK still in OpenCV 3?
I am tinkering with OpenCV 3 in C++ Visual Studio 2012. I built it from Github. Now, I would like to use FREAK but while I can create BRISK or ORB object, I am not able to create a FREAK extractor.
Is anyone successful with this? I should mention that since I am not that experienced with OpenCV, it might only be that I am following a OpenCV 2.4.X tutorials and that they are no longer compatible with the new version. If so, any doc or example would be welcome!
Here is the doc I am using right now.
EDIT : I think that I have not built the xfeatures2d module. Is it necessary for OpenCV 3 and if yes, is there some way to build it without building the entire OpenCV 3 project?
EDIT 2 : So, as pointed in the answer, you have to build the xfeatures2d module, AND use the namespace "using namespace xfeatures2d;" or declare it every time (like you would do for cv:: or std::). | https://answers.opencv.org/question/45103/is-freak-still-in-opencv-3/?sort=latest | CC-MAIN-2019-43 | refinedweb | 176 | 82.14 |
Net::XMPP2 - An implementation of the XMPP Protocol
Version 0.14
use Net::XMPP2::Connection;
or:
use Net::XMPP2::IM::Connection;
or:
use Net::XMPP2::Client;
NOTE: Net::XMPP2 is deprecated, for the newest version of this module look for the AnyEvent::XMPP module!
This is the head module of the Net::XMPP2 XMPP client protocol (as described in RFC 3920 and RFC 3921) framework.
Net::XMPP2::Connection is a RFC 3920 conformant "XML" stream implementation for clients, which handles TCP connect up to the resource binding. And provides low level access to the XML nodes on the XML stream along with some high level methods to send the predefined XML stanzas.
Net::XMPP2::IM::Connection is a more high level module, which is derived from Net::XMPP2::Connection. It handles all the instant messaging client functionality described in RFC 3921.
Net::XMPP2::Client is a multi account client class. It manages connections to multiple XMPP accounts and tries to offer a nice high level interface to XMPP communication.
For a list of "Supported extensions" see below.
There are also other modules in this distribution, for example: Net::XMPP2::Util, Net::XMPP2::Writer, Net::XMPP2::Parser and those I forgot :-) Those modules might be helpful and/or required if you want to use this framework for XMPP.
See also Net::XMPP2::Writer for a discussion about the brokeness of XML in the XMPP specification.
If you have any questions or seek for help look below under "SUPPORT".
One of the major drawbacks I see for Net::XMPP2 is the long list of required modules to make it work.
For the I/O events and timers.
The former Net::XMPP2::Event module has been outsourced to the Object::Event module to provide a more generic way for more other modules to register and call event callbacks.
For writing "XML".
For parsing partial "XML" stuff.
For SASL authentication
For SASL authentication
For stringprep profiles to handle JIDs.
For SSL connections.
For SRV RR lookups..
Here are some notes to the last releases (release of this version is at top):
Only minor additions and bugfixes. PLEASE NOTE: This is the last release of this module under the name Net::XMPP2. All further releases will be done under the name AnyEvent::XMPP!
API CHANGE: The connects are now non-blocking, you should revisit the places you use the
connect method of Net::XMPP2::Connection/::IM::Connection directly!
Implemented XEP-0054 and XEP-0153 (see Net::XMPP2::Ext::VCard), on top of that a serious bug in
split_jid in Net::XMPP2::Util was fixed and a
connect_timeout argument can be set now for Net::XMPP2::Connection.
Aside from that a few changes here and there, but nothing serious, see the
Changes file.
Mainly a maintenance release. The
init method for the connection classes have been made implicit on connect. So you should not call it yourself anymore.
Aside from that there were some documentation fixes in Net::XMPP2::Client.
Other additions were the xmpp_datetime_as_timestamp in Net::XMPP2::Util and the nick collision callback in Net::XMPP2::Ext::MUC, to change the nick when the nick has already been taken when joining a room.
The tests have been tweaked a bit and a Pod::Coverage test has been added.
Fixed some bugs and implemented an old/ancient authentication method used by some very old (jabberd 1.4.2) servers. Also implemented a chat session tracking mechanism to help the users of Net::XMPP2::Client to get their message to the right resource. (See also the method
send_tracked_message of Net::XMPP2::IM::Account).
Just a bugfix release. Last change before the last release introduced a bug with namespace handling in resource binding.
Lots of bugfixes and minor changes you might want to read about in the
Changes file. Added some examples which might be useful.
Introduced a character filter on the low XML writer level which will filter out not allowed XML characters to prevent unexpected disconnects. Arguably this is the programmers fault but I hope noone is confuses if this module tries everything to be as reliable as possible.
Many small changes in Net::XMPP2::Event. Implemented XEP-0199 (XMPP Ping) and also whitespace pings in Net::XMPP2::Connection.
Also fixed some bugs.
For further details look in the
Changes file.
The event API has been changed a bit, it's possible to intercept events now, see Net::XMPP2::Event.
Implemented the old legacy XEP-0078 (IQ authentication), see also Net::XMPP2::Ext for some notes about it.
Some bugs with JID preps have been fixed and some functions for JID handling have been added to Net::XMPP2::Util.
Reworked the subscription system a bit, you now have to reply with 'subscribed' yourself, etc. (See also Net::XMPP2::IM::Connection about subscriptions).
Implemented following new XEPs:
- XEP-0082 - XMPP Date and Time Profiles - XEP-0091 - Delayed Delivery (legacy) - XEP-0092 - Software Version - XEP-0203 - Delayed Delivery (new)
For further information about them see Net::XMPP2::Ext.
I also started an implementation of XEP-0045 (Multi User Chats), please consult the test t/z_05_muc.t and the API at Net::XMPP2::Ext::MUC for the already working features. (Very basic MUCing should work, but there are lots of edges still with error reporting and all the other nice features).
Also enhanced the message API a bit see Net::XMPP2::IM::Message and the methods of other classes that generate messages (eg. like
make_message).
There has been a considerable efford in test writing. Added instructions about the test suite below in section "TEST SUITE".
And another API change:
reply_iq_result and
reply_iq_error now attach a from attribute themselves (see Net::XMPP2::Connection).
I added some unit tests and fixed a lot of bugs. The unit tests are mostly for me (the AUTHOR) to not accidentally release a buggy version with too ugly show stopper bugs.
The tests require network access to a jabber server and won't run unless you set the right environment variable. If you want to run these tests yourself you might want to take a look at Net::XMPP2::TestClient.
After realizing that in band registration in Net::XMPP2::Ext was already in in version 0.03 I finally had to implement it.
While implementing in band registration I implemented XEP-0066: Out of Band Data. You can now receive and send URLs from and to others. See also Net::XMPP2::Ext::OOB.
I also fixed some bugs in Net::XMPP2::Ext::Disco.
For older release notes please have a look at the Changes file or CPAN.
There are still lots of items on the TODO list (see also the TODO file in the distribution of Net::XMPP2). Net::XMPP2: Net::XMPP2 itself, so if you find something where Net::XMPP2 gurantee Net::XMPP2 means more time for bug fixing and improvements and new features. Net::XMPP2 I try to provide low level modules for speaking XMPP as defined in RFC 3920 and RFC 3921 (see also Net::XMPP2::Connection and Net::XMPP2::IM::Connection). But I also try to provide a high level API for easier usage for instant messaging tasks and clients (eg. Net::XMPP2::Client).
This module also supports TLS, as the specification of XMPP requires an implementation to support TLS.
Maybe there are still some bugs in the handling of TLS in Net::XMPP2::Connection. So keep an eye on TLS with this module. If you encounter any problems it would be very helpful if you could debug them or at least send me a detailed report on how to reproduce the problem.
(As I use this module myself I don't expect TLS to be completly broken, but it might break under different circumstances than I have here. Those circumstances might be a different load of data pumped through the TLS connection.)
I mainly expect problems where available data isn't properly read from the socket or written to it. You might want to take a look at the
debug_send and
debug_recv events in Net::XMPP2::Connection.
See Net::XMPP2::Ext for a list.
Following examples are included in this distribution:
This example script just connects to a server and sends a message and also displays incoming messages on stdout.
This is a more advanced 'example'. It requires you to have Gtk2 installed. It's mostly used by the author to implement proof-of-concepts. Currently you start the client like this:
../Net-XMPP2/samples/devcl/# perl ./devcl <jid> <password>
The client's main window displays a protocol dump and there is currently a service discovery browser implemented.
This might be a valuable source if you look for more real-world applications of Net::XMPP2.
See below.
See below.
These three scripts implements a global room scan.
conference_lister takes a list of servers (the file is called
servers.xml which has the same format as the xml file at). It then scans all servers for chat room services and lists them into a file
conferences.stor, which is a Storable dump.
room_lister then :).
This is a (basic) skeleton for a jabber component.
This is a simple out of band file transfer receiver bot. It uses
curl to fetch the files and also has the sample functionality of sending a file url for someone who sends the bot a 'send <filename>' message.
This is a example script which allows you to register, unregister and change your password for accounts. Execute it without arguments for more details.
This is a small example tool that allows you to fetch the software version, disco info and disco items information about a JID.
This is a simple bot that will read lines from a file and recite them when you send it a message. It will also automatically allow you to subscribe to it. Start it without commandline arguments to be informed about the usage.
This is a simple example script that will retrieve the roster for an account and print it to stdout. You start it like this:
samples/# ./retrieve_roster <jid> <password>".
Robin Redeker,
<elmex at ta-sa.org>, JID:
<elmex at jabber.org>
Please note that I'm currently (July 2007) the only developer on this project and I'm very busy with my studies in Computer Science in Summer 2007.pp::XMPP2
You can also look for information at:
IRC Network: Server : chat.freenode.net Channel : #net_xmpp2 Feel free to join and ask questions!:
For pointing out a serious bug in
split_jid in Net::XMPP2::Util and suggesting to add a timeout argument to the
connect method of Net::XMPP2::SimpleConnection.
For pointing out some typos.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. | http://search.cpan.org/dist/Net-XMPP2/lib/Net/XMPP2.pm | crawl-002 | refinedweb | 1,784 | 65.62 |
Your search did not match any results.
We suggest you try the following to help find what you’re looking for:
The REST JDBC driver is a stateless Type 3 JDBC driver, providing a common interface for RESTful interaction with the database. It allows JDBC applications to communicate with cloud databases using the standard JDBC API without the need of raw REST calls or a separate SDK.
At a high-level, an application communicates with the database using the REST JDBC driver. The driver uses the REST Enabled SQL feature in Oracle Rest Data Services (ORDS) to send and receive information from the Database.
The REST JDBC driver requires ORDS 17.3.0 or later.
Follow these instructions to download and install the latest version of ORDS.
Setup
Here is a sample Connection string and Driver string that could be used with the REST JDBC driver.
String DRIVER = "oracle.dbtools.jdbc.Driver"; String DB_URL = ""; String USER = "HR"; String PASS = "debjani";
Note: The schema name has to be specified in the URL.
A similar sample that would be used with the Oracle thin driver is below.
String DRIVER = "oracle.jdbc.driver.OracleDriver"; String DB_URL = "jdbc:oracle:thin:@example.us.oracle.com:1521/orcl"; String USER = "HR"; String PASS = "debjani";
Therefore, a java application intending to use the REST JDBC driver only needs to swap the driver name and the database URL.
Here's an example with the connection string URL and the REST JDBC Driver String inside of a java application.
```java public class Example { public static void main(String[] args) {
String USER = "HR", PASS ="debjani" String driver = "oracle.dbtools.jdbc.Driver" String DB_URL = "" Properties cred = new Properties(); cred.put("user", USER); cred.put("password", PASS); try { Connection conn = DriverManager.getConnection(DB_URL, cred); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("select 'Hello World' from dual"); while(rs.next()) { System.out.println(rs.getString(1)); } stmt.close(); } catch(SQLException e) { e.printStackTrace(); }
} } ```
Quickstart - Using the Example Project with the REST JDBC Driver
Download the JDBC REST Example zip file. This is an eclipse project which includes several sample programs that describe how to use various features in the driver.
Download SQLcl sqlcl-17.2.0.184.1230 from the OTN page.
$ unzip RESTJDBC_source_beta.zip $ unzip sqlcl-17.2.0.184.1230-no-jre.zip $ cp sqlcl examples/src $ ant
After the project is built, you can run each example by right clicking on the java file and choosing:
"Run as -> Java Application"
Java Commandline with REST JDBC
You can also do this from the command line. Explode the zip file and go to the examples directory. From here you can run
$ant compile This will build the examples and put them into the
built directory. You can run each one from the command line like this
java -cp built/classes:lib oracle.dbtools.jdbc.examples.BasicExample
You will need to change the connection string in the examples to connection to your REST service. See below for details.
Using SQLcl with REST JDBC
Follow these steps to use SQLcl with the REST JDBC driver:
sqlcl/lib
To use SQLcl with the REST JDBC driver, you can start as follows:
sql USER/PASS@http://<host>:<port>/ords/user/
You can download the source for the REST JDBC Driver from the opensource page. This source is for the driver only. To build the driver code, you will need:
When you have downloaded the source and exploded the zip file do the following:
$ unzip [RESTJDBC_source_beta.zip]() $ cp sqlcl-17.2.0.184.1230-no-jre.zip source $ cd source
Follow [these instructions on authenticating a third party application against ORDS] () to generate a
clientID and
clientSecret and add this information to
oracle/dbtools/util/JDBCSessionType.java.
Then run:
$ ant The output from the build is summarised below
``` Buildfile: /source/build.xml
clean:
unzip_sqlcl: [echo] Download SQLcl Beta [sqlcl-17.3.0.248.1158-no-jre.zip] from OTN to this directory [unzip] Expanding: /source/sqlcl-17.3.0.248.1158-no-jre.zip into /source
compile: [mkdir] Created dir: source/built/classes [javac] Compiling 41 source files to /source/built/classes [javac] /source/src/oracle/dbtools/jdbc/BLOB.java
jar: [copy] Copying 1 file to /source/built/classes [jar] Building jar: /source/built/oracle.dbtools.jdbcrest.jar
BUILD SUCCESSFUL Total time: 2 seconds
```
The following datatypes are not yet supported by the REST JDBC driver:
Since the driver is RESTful, each new query to the database is a new connection and each request to the database is auto-committed. Consequently, the REST JDBC driver does not support rollbacks either. Stateful transactions can be implemented with PL/SQL but the state is not preserved across statements.
For large ResultSets, ORDS supports ResultSet pagination. The REST JDBC Driver automatically requests more pages as required by the JDBC API.
The
setFetchSize methods in the JDBC API can be used to alter pagination in the REST JDBC Driver. In the REST JDBC driver, the default number of rows fetched from the database at a time is 25. This value is configurable upto the max number of rows that can be set in ORDS (500), using the
setFetchSize methods in Statement and ResultSet.
The total number of rows to be fetched from the database is set by
setMaxRows in Statement. The REST JDBC driver issues the query against ORDS after the end of each fetch and until all the rows specified by maxRows has been obtained.
Since the driver does not support transactions, the state of the database may change in between fetches. This means that if there are DDLs or DMLs in between fetches, results from the driver will be indicative of the latest state of the database, regardless of which state the query was started on.
The REST JDBC driver is based on the REST web standards and is affected by constraints of the REST architectural style. Additionally, since the driver communicates with ORDS in JSON, there are a few limitations from the JSON standard.
getStringmethods in ResultSet are called on a datetime object, the result is returned in the ISO 8601 format. This is because ORDS converts datetime values in the Oracle Database to ISO 8601 strings.
This Driver release is covered by the Oracle Technology Network Free Use Developer License. | https://www.oracle.com/database/technologies/appdev/sqldev/rest-driver-readme.html | CC-MAIN-2021-49 | refinedweb | 1,044 | 56.35 |
Closed Bug 1408175 Opened 4 years ago Closed 3 years ago
Crash in Msg
Strip Quoted Printable
Categories
(MailNews Core :: Backend, defect)
Tracking
(thunderbird58 fixed, thunderbird59 fixed)
Thunderbird 59.0
People
(Reporter: wsmwk, Assigned: jorgk-bmo)
Details
(4 keywords, Whiteboard: [regression: ~2017-09-26])
Crash Data
Attachments
(1 file, 1 obsolete file)
#1 crash for nightly crash first appears in 58.0a1 build 20170926030204 3de52e42-1d5b-4518-98d8-9e6450170929 report bp-bf6c97df-aa8e-4b0e-a642-1565f0171012. 0 xul.dll MsgStripQuotedPrintable(unsigned char*) C:/builds/moz2_slave/tb-c-cen-w64-ntly-000000000000/build/mailnews/base/util/nsMsgUtils.cpp:1595 1 xul.dll nsMsgDBFolder::decodeMsgSnippet(nsTSubstring<char> const&, bool, nsTString<char>&) C:/builds/moz2_slave/tb-c-cen-w64-ntly-000000000000/build/mailnews/base/util/nsMsgDBFolder.cpp:5683 2 xul.dll nsMsgDBFolder::GetMsgTextFromStream(nsIInputStream*, nsTSubstring<char> const&, unsigned int, unsigned int, bool, bool, nsTSubstring<char>&, nsTSubstring<char>&) C:/builds/moz2_slave/tb-c-cen-w64-ntly-000000000000/build/mailnews/base/util/nsMsgDBFolder.cpp:5623 3 xul.dll nsMsgDBFolder::GetMsgPreviewTextFromStream(nsIMsgDBHdr*, nsIInputStream*) C:/builds/moz2_slave/tb-c-cen-w64-ntly-000000000000/build/mailnews/base/util/nsMsgDBFolder.cpp:5758 4 xul.dll nsImapMailFolder::ParseMsgHdrs(nsIImapProtocol*, nsIImapHeaderXferInfo*) C:/builds/moz2_slave/tb-c-cen-w64-ntly-000000000000/build/mailnews/imap/src/nsImapMailFolder.cpp:2948 5 xul.dll `anonymous namespace'::SyncRunnable2<nsIImapServerSink, nsIImapProtocol* __ptr64, bool* __ptr64>::Run C:/builds/moz2_slave/tb-c-cen-w64-ntly-000000000000/build/mailnews/imap/src/nsSyncRunnableHelpers.cpp:147 6 xul.dll nsThread::ProcessNextEvent(bool, bool*) xpcom/threads/nsThread.cpp:1037
Looking at the stack, we see nsImapMailFolder.cpp:2948. That code reads: inputStream->ShareData(msgHdrs, strlen(msgHdrs)); GetMessageHeader(msgKey, getter_AddRefs(msgHdr)); if (msgHdr) { nsCOMPtr<nsIInputStream> stream(do_QueryInterface(inputStream)); GetMsgPreviewTextFromStream(msgHdr, stream); <=== 2948. } That line was changed here a few days before: Boris, anything springs to your mind here? If the crash had started two days later, I would have blamed it on bug 1403393 and friends which adopted stream related Necko changes. But given that the crash is already present on 26th Sept, we can rule that out.
Flags: needinfo?(bzbarsky)
The change quoted in comment 0 looks ok to me. Looking at the actual callstack, we end up in MsgStripQuotedPrintable which takes "unsigned char *src" and assumes it's null-terminated, looping until it hits src[srcIdx] == 0. We end up crashing when trying to write to dest[destIdx++]. Note that dest == src. On the way to MsgStripQuotedPrintable we go through nsMsgDBFolder::decodeMsgSnippet which is doing: MsgStripQuotedPrintable((unsigned char *) aMsgSnippet.get()); where aMsgSnippet is an nsCString. The caller of decodeMsgSnippet is GetMsgTextFromStream, which does: decodeMsgSnippet(NS_ConvertUTF16toUTF8(encoding), !reachedEndBody, msgText); where msgText came from: nsAutoCString msgText; and then various append calls... This all looks legit to me, assuming searchfox is not out of date on comm-central. If you wanted to be sure, you could try backing out bug 1371893 (since m-c still has stringstream inheriting from inputstream) and see whether that helps. But I would be pretty surprised if it does.
Flags: needinfo?(bzbarsky)
Thanks for the detailed analysis. I landed bug 1371893 since bug 1401171 was landed which had grabbed the original part 4 of bug 1371699 (attachment 8876568 [details] [diff] [review]). But by the looks of it that was pre-mature since it affected nsIMultiplexInputStream and not nsIStringInputStream. Hard to decide whether I should try a backout. Wayne, if I backout bug 1371893, how fast do we get results?
Flags: needinfo?(vseerror)
(In reply to Jorg K (GMT+2) from comment #3) > ... > Wayne, if I backout bug 1371893, how fast do we get results? Within 1-4 days. Avg is 1 crash per day, prox every other buildid. No crashes so far with an email. Based on extensions I installed, I'd say there are 4-5 different people crashing. Interesting tidbits about the crashes - one is russian locale, with russian langpack installed bp-bf6c97df-aa8e-4b0e-a642-1565f0171012 (comment 0) - different person with en-US locale has ruendict@russia.ru installed bp-2eb535a9-c267-48a9-b389-afc600171010 ( ?) - 90% are a specific build of win10 (except one linux), but only 24% of nightly crash reports are that win10 build. (from 11 crash reports [1]) - a couple appear to have no addons installed [1]
Flags: needinfo?(vseerror)
OK, I'll back it out as an experiment, however, very hard to understand why bug 1371893 should be the cause.
Flags: needinfo?(jorgk)
I backed it out, leaving NI to check results and reland.
(In reply to Boris Zbarsky [:bz] (no decent commit message means r-) from comment #2) > Looking at the actual callstack, we end up in MsgStripQuotedPrintable which > takes "unsigned char *src" and assumes it's null-terminated, looping until > it hits src[srcIdx] == 0. Agreed. > The caller of decodeMsgSnippet is GetMsgTextFromStream, which does: There is a change from Bug 1402750 (push date 2017-09-25 23:35 +0000): | - msgHeaders.Append(NS_LITERAL_CSTRING("\r\n")); | + msgHeaders.AppendLiteral("\r\n"); Comment to 'AppendLiteral': | // AppendLiteral must ONLY be applied to an actual literal string. | // Do not attempt to use it with a regular char* pointer, or with a char | // array variable. Use Append or AppendASCII for those. Comment to 'nsTSubstring' | * nsTSubstring is an abstract string class. From an API perspective, this | * class is the root of the string class hierarchy. It represents a single | * contiguous array of characters, which may or may not be null-terminated. If I count that together and still speculate that a server supplies an article min LF line breaks, this could be the explanation for overwriting the NULL termination and finally for the crash.
Thanks for looking at it, but bug 1402750 was motived by bug 870698: "\r\n" is a literal string. Where do you see the problem? I agree that bug 1402750 landed an bit of refactoring. I'm happy to agree that I messed up somewhere.
(In reply to Jorg K (GMT+2) from comment #8) > Thanks for looking at it, but bug 1402750 was motived by bug 870698: > Where do you see the problem? This is just a wild guess from me. It would fit in time with the appearance of this bug. But unfortunately I can not check this because my server automatically repairs the line breaks. Possibly Comment 6 already shows an effect.
(In reply to Jorg K (GMT+2) from comment #6) > I backed it out, leaving NI to check results and reland. Still crashing with bug 1371893 backed out on 2017-10-14: - 20171015040550 - 2017-10-15 - 20171017030201 - 2017-10-17
I will re-land bug 1371893 now.
Flags: needinfo?(jorgk)
bp-7583742f-ed8a-4c09-8749-bdbd40171019 buildid 20171016040337 onno crashed. He has no other notable crash history. Different person (the only other one with an email address) 218cf4f4-ad08-4532-a8d7-9f3c90170929 2017-09-29 MsgStripQuotedPrintable 58.0a1 f67e4e9f-702c-4d2c-a75f-dbac20170917 2017-09-17 MimeMultipart_parse_eof 57.0a1 We will need to see what shakes out in a few days as users get updated to current versions of newly resumed nightly builds.
Crashes continue up through the latest builds. Ray has crashed at least twice - bp-9956b3ec-2fb2-4ba2-994f-b028f0171030 bp-ac222de9-761e-4b38-ba92-9946b0171022
Keywords: regression, regressionwindow-wanted, topcrash-thunderbird
#1 crash for 58 beta, so this must block 59 release. Ideally we'd push a patch into a 58 beta. (#2 crash for nightly) examined last month of crashes - almost every user has no prior crashes so this is definitely a regression, not a case where a signature morphed. Walt crashed once - bp-c263d1af-29cf-4e98-a4e3-69fd00171104 with 58.0a1
status-thunderbird58: --- → affected
status-thunderbird59: --- → affected
tracking-thunderbird58: --- → ?
tracking-thunderbird59: --- → ?
Hardware: Unspecified → All
Any chance to get a reproducible case? I've looked at the code again, like Boris already did in comment #2, and don't see anything obvious.
Eric, operating on the string buffer of an nsCString here MsgStripQuotedPrintable((unsigned char *) aMsgSnippet.get()); is clearly hacky, but is it also crashy?
Flags: needinfo?(erahm)
> Any chance to get a reproducible case? I don't have high hopes, even though at least two users crash frequently. But I will continue to try.
FWIW The only solid common theme in crash comments is downloading mail.
> is clearly hacky, but is it also crashy? In theory it could be. For example, aMsgSnippet could be pointing into immutable memory, and you're casting away const. You should really be using BeginWriting() to get a writable pointer, at the very least.
Boris, I fully agree with your comment #19. Would you be so kind as to look at this patch for me. I noticed that passing a char* wasn't really required.
Assignee: nobody → jorgk
Status: NEW → ASSIGNED
Flags: needinfo?(erahm)
Attachment #8934553 - Flags: review?(bzbarsky)
Comment on attachment 8934553 [details] [diff] [review] 1408175-MsgStripQuotedPrintable.patch >+ buf.SetLength(--bufLength); Why not just "bufLength - 1"? bufLength is unused after this point, and it would be a lot clearer what's going on... r=me Whether this fixes the crashes, we'll see.
Attachment #8934553 - Flags: review?(bzbarsky) → review+
(In reply to Boris Zbarsky [:bz] (no decent commit message means r-) from comment #21) > Why not just "bufLength - 1"? bufLength is unused after this point, and it > would be a lot clearer what's going on... I'll do that. > r=me Thanks! > Whether this fixes the crashes, we'll see. Indeed.
Addressed comment.
Attachment #8934553 - Attachment is obsolete: true
Attachment #8934579 - Flags: review+
If nightly is working then I will have affected users give it a shot. Otherwise, will need a try build.
Whiteboard: [regression: ~2017-09-26]
Also, if we manage to reenable nightly automatic updates (disabled because of on add-ons issues), we should know the effectiveness of the fix within a day or two via nightly users.
Pushed by mozilla@jorgk.com: pass nsCString to MsgStripQuotedPrintable() instead of a raw char pointer. r=bz
Status: ASSIGNED → RESOLVED
Closed: 3 years ago
Resolution: --- → FIXED
It will be in tomorrow's Daily.
Target Milestone: --- → Thunderbird 59.0
Comment on attachment 8934579 [details] [diff] [review] 1408175-MsgStripQuotedPrintable.patch (v1b) Uplift won't do harm. If it still crashes, we might even get more information.
Attachment #8934579 - Flags: approval-comm-beta+
tracking-thunderbird58: ? → ---
tracking-thunderbird59: ? → ---
Beta (TB 58):
No crashes with 12-06 and 12-07 builds, plus I have two testers who used nightly and report success. Also no new crashes according to topcrash. So I think it is killed. Thanks for all the diagnosis and patch.
Status: RESOLVED → VERIFIED | https://bugzilla.mozilla.org/show_bug.cgi?id=1408175 | CC-MAIN-2021-17 | refinedweb | 1,732 | 59.5 |
Computer Science Archive: Questions from November 04, 2009
- Anonymous askedYou are required to write a program for Movie Rental Store. Th... Show more
Problem Statement: Movie Rental Store
You are required to write a program for Movie Rental Store. Thebasic idea is that user/reader will provide customer information,movie name, and number of days. Upon this information your programwill calculate the charged amount for that movie.
Detailed Description:
1. The program should display
Please provide customer Name:
Please provide Movie Description.
Enter ‘R’ for Regular Movie.
Enter ‘C’ for children Movie.
Enter ‘N’ for New Released Movie.
Enter ‘E’ for English Movie.
Then your program should take these inputs,
2. Depending upon the choices that user hasentered, your program will further display the prompt
3. If user has entered Movie description, thenyour program should prompt the user to enter the Movie Name andNumber of days.
-----------------------------------------------------------------
Movie Name :
Number of day’s:
-----------------------------------------------------------------
4. After getting all this information, nowwrite a function which will calculate rental/charged amount on thebasis of this information.
To calculate rental/charged amount we will use this formula:
Rental amount = charged amount * number of days
Charged amount will be different for different movies accordingto following description:
Regular Movie: 40 RS
Children Movie: 30 RS
English Movie: 50 RS
New release: 100 RS
After calculating charged amount for this movie and display iton the screen.
Sample Output
Please provide customer Name: Aftab
Please provide Movie Description:
Enter ‘R’ for Regular Movie:
Enter ‘C’ for children Movie:
Enter ‘N’ for New Released Movie:
Enter ‘E’ for English Movie:
R
Please provide following information:
Movie Name : Jinnah
Number of day’s: 3
Final output:
-----------------------------------------------------------------
Customer Name: Aftab
Movie Type : Regular
Movie Name : Jinah
Number of day’s: 3
Your Rental Amount is: 120 Rs
-----------------------------------------------------------------• Show less0 answers
- Anonymous asked0 answers
- Anonymous asked0 answers
- Anonymous asked
Q 2.1:
Generate hexadecimalmachine code for the following MC68000 instructions.
i. MOVE.L (A2) ,D4
Q 2.1:
Generate hexadecimalmachine code for the following MC68000 instructions.
i. MOVE.L (A2) ,D4
ii. ADD.L A5 , D6
iii. ROL #3 , D4
iv. BGT -240 answers
- Anonymous asked
Q : Write a note on thefollowing
Q : Write a note on thefollowing
1. Describe the components of Computer-based informationsystems.
2. Describe various types of information systems bybreadth of support.• Show less1 answer
- Anonymous askeds and odd n... Show more
Consider the EVEN-ODD language of strings, defined over ?={a,b}, having even number of a’s and odd number ofb,s.
a) Build an FA for the givenlanguage
b) Build a Transition Graph (TG)that accepts the same language but has fewer states than FA.
c) Find the Regular Expression(RE) corresponding to TG accepting EVEN-ODD language (Show all possiblesteps)• Show less0 answers
- Anonymous askedHello users I am struggling with a particular task. I amtrying to create a catalog page for a websit... Show moreHello users I am struggling with a particular task. I amtrying to create a catalog page for a website based on online movietickets. I have a PHP code that does not work properly I willinsert the HTML code as well. What i am looking to do is whenthe user selects a particular movie from the HTML page the PHP pageshould come up and display the selection as well as the price andprint a receipt. Please help if you can.
PHP
<html>
<head>
<title>eyecatalog</title>
</head>
<body>
<h3><center>C</center></h3>
<?
print <<<HERE
//variables
thisIsIt: $thisIsIt <br>
pActivity: $pActivity <br>
laCitizen: $laCitizen <br>
cRetreat: $cRetreat <br>
sawVI: $sawVI <br>
<hr>
HERE;
$total = 0;
if (!empty($thisIsIt))
{
print ("You chose Michael Jackson's thisis it <br> \n");
$total = $total + $thisIsIt;
} // end if
if (!empty($pActivity))
{
print ("You chose Paranormal Activity<br> \n");
$total = $total + $pActivity;
} // end if
if (!empty($laCitizen))
{
print ("You have tickets for Law AbidingCitizen <br> \n");
$total = $total + $laCitizen;
} // end if
if (!empty($cRetreat))
{
print ("You chose couples retreat<br> \n");
$total = $total + $cRetreat;
} // end if
if (!empty($sawVI))
{
print ("You chose Saw VI<br>\n");
$total = $total + $sawVI;
} // end if
print "The total cost is $$total \n";
?>
</body>
</html>
HTML
<html>
<head>
<title>EyeWatchCatalog</title>
</head>
<body bgcolor="Silver">
<h1><center><</center></h1>
<br>
<center> Todays Top Five Movies Playing in a Theater nearyou.</center>
<form action ="eyecatalog.php">
<h3>Top Five Box office movies currentlyplaying</h3>
<ul>
<li><input type ="checkbox"
name="thisIsIt"
value="1.05">Michael Jackson's This Is It $1.05
</li>
<li><input type ="checkbox"
name="pActivity"
value="2.40">Paranormal Activity $2.40
</li>
<li><input type ="checkbox"
name="laCitizen"
value=".90">Law Abiding Citizen $.90
</li>
<li><input type ="checkbox"
name="cRetreat"
value="1.40">Couples Retreat $1.40
</li>
<li><input type ="checkbox"
name ="sawVI"
value="2.75">Saw VI $2.75
</li>
</ul>
<input type ="submit">
</form>
<p>
<center>
</center>
</p>
</body>
</html>
• Show less0 answers
- Anonymous askedb.... Show moreGenerate hexadecimal machine code for the followingMC68000 instructions• Show less
a. MOVE.L (A2) ,D4
b. ADD.L A5 ,D6
c. ROL #3 , D4
d. BGT -240 answers
- Anonymous askedWrite a GUI program to convert all letters in a string to uppercase letters, For example, Alb34ert w... More »1 answer
- Anonymous askedRule 1... Show moreDescribe a good method to show that 2n is in EVEN. Given thefollowing recursive definationRule 1 : 2 is in EVEN.Rule 2 : If x and y both in even, then so x+ y• Show less0 answers
- Anonymous asked0 answers
- Anonymous asked0 answers
- Anonymous asked0 answers
- Anonymous asked(340,215) an... Show more
Question 1:
Write a C++ programwhich will draw a triangle having vertices at (300,210),
(340,215) and(320,250). Centre of the triangle lies at (320,240).
Your program shouldperform the following transformations.
1. Translatetriangle using translating factor tx = 20 and ty = 30
2. Rotate triangleat centre using angle = ð /2
3. Scale triangle atcentre using scaling factor Sx = 3 and Sy = 2• Show less0 answers
- Anonymous asked
Q # 1. Generate hexadecimal machine code for thefollowing MC68000 instructions. [3*4=12]
a. MOVE.L... Show more
Q # 1. Generate hexadecimal machine code for thefollowing MC68000 instructions. [3*4=12]
a. MOVE.L (A2) , D4
b. ADD.L A5 , D6
c. ROL #3 , D4
d. BGT -24
Q # 2. Consider the short section of MC68000 code below,which is executed with the initial conditions given. What valueswould DO, Dl, and D2 have after execution? [2*3=6]
Initial conditions:
DO = OH
Dl = 1H
D2 = 1OH
Code:
ORG $2000
ADD DO, DlDBLE D2, $2000 • Show less0 answers
- Anonymous asked(2, 17, 40, 27,... Show more
Construct a B+-tree for the following set of key values:
(2, 17, 40, 27, 37, 22, 7, 11, 4, 13)
Assume that thetree is initially empty and values are added in agiven order (don’t sort the key values).Construct the B+ - tree for the cases where the number of pointersthat will fit in a node is 4 (n=4) (Important:Show the progression, not only the final result)
Showthe progress (in graphs) of the same B+-Tree index (as in question6.1) after each of the following series of operations.(Important: Show the progression, not only thefinal result)
a ) insert 9
b) insert 5
c) insert 6
d) delete 27
e) delete 17
f) delete 13• Show less0 answers
- Anonymous askedThe if and print statements in this php code does not work on mycomputer it just shows as text, any... Show moreThe if and print statements in this php code does not work on mycomputer it just shows as text, any suggestions??
<html>
<head>
<title>login page</title>
</head>
<body bgcolor="DeepSkyBlue" style="color:gray">
<form action="index.php" method=get>
<h1 align="center" style="color:gray" >Welcome to this simpleapplication</h1>
<?
session_start();
if( $_SESSION["logging"]&& $_SESSION["logged"])
{
print_secure_content();
}
else {
if(!$_SESSION["logging"])
{
$_SESSION["logging"]=true;
loginform();
}
elseif($_SESSION["logging"])
{
$number_of_rows=checkpass();
if($number_of_rows==1)
{
$_SESSION[user]=$_GET[userlogin];
$_SESSION[logged]=true;
print"<h1>you have loged in successfully</h1>";
print_secure_content();
}
else{
print "wrong pawssword or username, please tryagain";
loginform();
}
}
}
function loginform()
{
print "please enter your login information to proceed with oursite";
print ("<<tr><td>username</td><td><</td></tr><tr><td>password</td><td><</td></tr></table>");
print "<input type='submit' >";
print "<h3><a href='registerform.php'>registernow!</a></h3>";
}
function checkpass()
{
$servername="localhost";
$username="root";
$conn= mysql_connect($servername,$username)ordie(mysql_error());
mysql_select_db("test",$conn);
$sql="select * from users where name='$_GET[userlogin]' andpassword='$_GET[password]'";
$result=mysql_query($sql,$conn) or die(mysql_error());
return mysql_num_rows($result);
}
function print_secure_content()
{
print("<b><h1>himr.$_SESSION[user]</h1>");
print "<br><h2>only a logged in usercan see this</h2><br><Logout</a><br>";
}
?>
</form>
</body>
</html>
• Show less1 answer
- Anonymous asked0 answers
- Anonymous asked0 answers
- Anonymous askedProblem1: Buying bo... Show more
AssignmentWrite goals and sub-goals while givingsolution to the problems • Show less0 answers
- Anonymous askedYou are required to develop a simple GUI (Graphical userinterface) applicati... Show more0 answers
- andyherebi asked3 answers
- andyherebi askedWrite a program that prompts the user to input a positiveinteger and then outputs the individual dig... Show more
Write a program that prompts the user to input a positiveinteger and then outputs the individual digits of the number.• Show less2 answers
- Anonymous askedYour assignment must be... Show more
SOFTWARE ENGINEERING
(Fall 2009)
Assignment No. 2
Max Marks: 20
Due Date:
Your assignment must be uploaded/submitted before or on6th November 2009.
Objective
- To assess youroverall understanding of Software Requirements Engineering
- To see yourskills in making a Business Model of the system
- To check yourlevel of understanding for Functional and Non FunctionalRequirements.
- How we createBusiness Requirements
-
Uploading instructions:
Please view the Assignment Submission Processdocument provided to you by the Virtual University for uploadingassignments.
o The assignment should be in .docformat.if:
o The assignment is submitted after due date.
o The submitted assignment file is corrupted.
o The assignment is copied.
o The assignment material is directly copied from internet.
Note:
Your answer must follow the below givenspecifications. You will be assigned no marks if you do not followthese instructions.
· Font style:“Times New Roman”
· Font color:“Black”
· Font size:“12”
· Bold for heading only.
· Font inItalic is not allowed at all.
· No formattingor bullets are allowed to use.
Assignment No. 2Cs 504 SoftwareEngineering
Total Marks 20 Marks
Note: - Recall the lectures delivered for Data flowmodeling, object oriented and analysis design.
Purpose of the Assignment
The purpose of this assignment is to make you familiarize aboutsoftware Engineering practices being done in the industry.
Assignment
This assignment has following steps:
- Analysis Notepad core functionalities
- Make Use Case Diagram of these functionalities (at least 5 UseCase)
Artifacts:
Students are required to provide a Microsoft Word file.
It should include the following items:
- Brief report on analysis
- Use Case Diagram
Marking Scheme
Note: Draw all diagrams in Microsoft Word file.• Show less0 answers
- Anonymous asked1 answer
- Anonymous asked0 answers
- Anonymous asked0 answers
- Anonymous asked0 answers
- Anonymous askedQ.1 Write a pattern that matches words beginningwith C or CR, Followed byO or OO or EE,followed by P... Show moreQ.1 Write a pattern that matches words beginningwith C or CR, Followed byO or OO or EE,followed by P orPS. Construct the pattern so that eachsuccessful step in the pattern matching is explicated by a printedoutput. • Show less0 answers
- Anonymous askedProblem1: Buying books related... Show more
5) Write goals andsub-goals while giving solution to the problems• Show less0 answers
- Anonymous asked0 answers
- Anonymous asked1.1) #d... Show more
Question – 1 [Marks 10](340,215) and... Show more
Question1:
Write a C++ programwhich will draw a triangle having vertices at (300,210),
(340,215) and(320,250). Centre of the triangle lies at (320,240).
Your program shouldperform the following transformations.
1. Translate triangleusing translating factor tx = 20 and ty = 30
2. Rotate triangle atcentre using angle = π /2
3. Scale triangle at centre usingscaling factor Sx = 3 and Sy = 2• Show less0 answers
- Anonymous askedDevelop a Client Server Application using Linux FIFOs. Followingare the requirements of t... Show more
Assignment
Develop a Client Server Application using Linux FIFOs. Followingare the requirements of this application.
0 answers
- The server application should run and respond to the clientapplication. Basically you have to show inter-process communicationbetween client and server processes.
- A client will give commands to the server process and theserver must execute that commands. Server will run on a separateterminal and client will run a separate terminal on the samemachine.
- If the command given by the client is successfully executed bythe server then server should send a message to the client“Command has been successfullyexecuted”.
- If the command given by the client is not executed by theserver, then server should give the message “Commandfailed to execute”.
- For example if a client gives the command mkdirCS604 from its terminal then server should create adirectory on its side with the name CS604 andrespond to the client with the message “Command hasbeen successfully executed”. Then this messageshould also be displayed on the client’s terminal.
- Similarly server should be able to execute other commands givenby the client like List, Remove Directory, Move, Copy etc.
- oldpunk askedYou are to write a program with two helper functions asdescribed below. Your pr... Show more
Strings Lab Exercise
You are to write a program with two helper functions asdescribed below. Your program will prompt the user to input asentence, which you will input with the gets function (syntax:gets(str);). Your program will then print the sentence withthe order of the words reversed.
An example run of the program, with user input underlined:
Enter a sentence: you can cage a swallowcan't you
Reversal of sentence: you can't swallow a cage canyou
You should provide two helper functions:
void replace_whitespace(char *str);
/* replaces every whitespace character in str with the null
character; uses the function isspace(char c) fromctype.h */
int get_words(char *line, chartokens[MAX_WORDS][MAX_LEN+1]);
/* Goal: to store the words from string line in the array
tokens, one wordper entry. */
Suggestion:
Have the function compute the length len of the string line,then call replace_whitespace(line).
Each separate word in the array line is now followed by one ormore null characters. Next find the start of each wordin the array and use strcpy to enter the word in the array of tokenstrings (second parameter)
You can use either a pointer or index to find the firstletter of each word. If you pass a pointer to that characteras the second argument of strcpy, it will copy theword starting at that position, since it is nownull-terminated. You then have to skip over null characters tofind the start of the next word.
Warning: you must use a count of all characters traversed(both null characters and characters read into one of theentries in token) to make sure you do not go beyond the end of theoriginal string input into the array line.• Show less1 answer
- Anonymous askeds... Show more
Question:
Consider the EVEN-ODD language of strings, defined over ?={a,b}, having evennumber of a’s and odd number of b,s.
a) Build an FA for the givenlanguage
b) Build a Transition Graph (TG) thataccepts the same language but has fewer states than FA.
c) Find the Regular Expression (RE)corresponding to TG accepting EVEN-ODD language (Show allpossible steps)• Show less0 answers
- Anonymous askedrectangl... Show more
Write a program to ask theuser to enter the width and length of a rectangle, and displaythe
rectangle’s area.The main function in this program should call the followingfunctions:
getLength – thisfunction should ask the user to enter the rectangle’s length,and then return
that values as adouble.
getWidth – thisfunction should ask the user to enter the rectangle’s width,and then return
that values as adouble.
getArea – thisfunction should accept the rectangle’s length and width asarguments, and then
return therectangle’s area. The area is calculated by multiplying thelength by width.
displayData – thisfunction should accept the rectangle’s length, width, andarea as
arguments, and then display them in anappropriate message on the screen.r another the program should behave like a Piano. • Show less0 answers
- Anonymous askedI need help creating a Blackjack program in C++. The programis very basic, one player against the de... Show moreI need help creating a Blackjack program in C++. The programis very basic, one player against the dealer and the program shouldonly be using (if and loops) statements.
Any help would be appreciated.• Show less0 answers
- Anonymous askedWrite a program in Assembly Language to find the maximum numberand the minimum number from an array... Show more
Write a program in Assembly Language to find the maximum numberand the minimum number from an array of ten positive numbers. Storethe minimum number in AX and maximum number in DX.[Hint: Use the conditional jumps] • Show less1 answer
- Anonymous askedHere is code which takes two parameters as command linearguments and adds them. I want to write it i... Show moreHere is code which takes two parameters as command linearguments and adds them. I want to write it in Visual C++6.0.
ThanksHere is Code#include<iostream>
#include <windows.h>
using namespace std;
int main(int argc, char *argv[])
{
char array[20];
int sum=0,i;
strcpy(array,"Please pass some arguments");
if(argc <= 1)
{
cout<<"Please pass somearguments"<<endl;
}else
{
for(i=1;i<argc;i++)
sum += atoi(argv[i]);
sprintf(array,"Sum = %d",sum);}
cout<<" Total arguments Passed"<<argc-1<<endl;
MessageBox(0,array,"OK", MB_OK);
return 0;
}out put isYou can use:
1) GetCommandline() function to get the string passed to program fromcommand line.
2) “strtok” function (or your own logic) totokenize the string and extract the integer values from stringpassed as commandline.
3) MessageBox(…) function to display the result ofaddition.• Show less0 answers
- Anonymous askedWrite a for loop that computes the following sum: 5+10+15+20+...+485+490+495+500. The sum shou... More »1 answer
- Anonymous askedA metal bar is divided into 10 segments, each with its owntemperature. The ends of the bar are conne... Show moreA metal bar is divided into 10 segments, each with its owntemperature. The ends of the bar are connected to heat sourceswhich keep their temperatures constant. Hence, temp[0] and temp[9]are always the same values. Assume initial temperature of the restof the segments is 0 degrees.
After a short time nterval, the new temperaute of each middlesegment becomes the average of the old temperatures of the twoneighboring segments.
temp[] is initialized as
100.00 0.00 0.00 0.00 0.00 0.000.00 0.00 0.00 80.00
After one time step, temperatures will be
100.00 50.00 0.00 0.00 0.00 0.00 0.00 0.00 40.00 80.00
And again
100.00 50.00 25.00 0.00 0.00 0.00 0.00 20.00 40.00 80.00
etc. etc.
have user input temps for segment 0 and segment 9.
I have no idea how to keep some elements of the array at thesame value while averaging some of them . any hints??? thanks! willrate highest
• Show less1 answer
- Anonymous askedan umbrella organization for a numbe... Show moreIn this assignment you will write a program for Charities,Inc., an umbrella organization for a number of charitableinstitutions, which from time to time sell raffle tickets and holdprize drawings to raise funds.
This program willtake user input in the following order:
Number of ticketssold.
Percentage ofticket revenue which goes to administrative costs. This input willbe entered in percent format (see sample runs below); your programmust convert this to a decimal fraction. For example, the userenters 25% as 25, not .25; you convert the 25 to .25 in yourcode.
Total amount ofprize money distributed.
Name of charity.The name may consist of more than one word.
The program thenwill output the following information in the followingorder:
Name ofcharity.
Total revenuegenerated from the ticket sales. The price of each ticket iscurrently fixed at $5.00.
Total amount ofadministrative overhead.
Total amount ofprize money overhead.
Balance remainingfor the charitable fund.
SampleRun
Another sample run withsample input data would be:
How many tickets were sold?25237• Show less
What percentage of the ticket revenue goes to administrative costs?60.6
How much total money is distributed in prizes?20000
What is the name of the charity? Goniffs ofAmerica
Charity: "Goniffs of America"
Revenue generated from ticketsales: $126185.00
Amount deducted for administrative overhead: $ 76468.11
Amount deducted for prizemoney: $ 20000.00
Balance raised for charitablefund: $ 29716.890 answers
- Anonymous asked1. In main(), define an integerarray with 20 elements, assign random numbers using rand(); findthe l1 answer
- Anonymous asked2 answers
- Anonymous asked(HMS). Following ar... Show moreThe domain of this assignment is related to the FPA of HospitalManagement System
(HMS). Following are the requirements of three modules of HMSapplication. You have
to calculate the size of this application (only consider thefollowing three modules for this
assignment) using Functional Point Analysis.
Requirement 01: Online Feedback submission module
Functional Requirement:
FR01-01 The system shall allow the Patient to fill onlineregistration form.
FR01-02 System shall generate a unique tracking id for a Patientagainst his/ her
registration submission.
FR01-03 The system shall allow the Patient to add feedbackform.
FR01-04 The system shall allow the Patient to edit the feedbackform.
FR01-05 The system shall allow the Patient to delete the feedbackform.
FR01-06 The system shall allow the Patient to apply for multiplefeedback form for
multiple visits.
FR01-07 The system shall allow the Patient to track the feedbackform through unique
tracking id and password.
Requirement 02: Employee Personal Information module
Functional Requirement:
FR02-01 The system shall allow the employee to create his profileafter login to the
system. The employee will be asked to provide the information abouthis age,
qualification, experience and family.
FR02-02 The system shall allow the employee to view hisprofile.
FR02-03 The system shall allow the employee to add information inthe profile form.
FR02-04 The system shall allow the employee to edit his/herprofile
FR02-05 System shall allow the HR Officer to delete the profile ofany employee.
FR02-06 The system shall verify the NIC number of the employee fromNADRA
database. With some limited rights to view the data from NADRAdatabase is
built-in into the HRMS system
Requirement 03: Patient Previous Pathology record Module
Functional Requirement:
FR03-01 The system shall allow the doctor to access the perviousPathology record
from Islamabad Pathology Lab.
FR03-03 The system shall allow the doctor to access the patientprofile through access
code.
FR03-03 The system shall allow the doctor to add the current healthcondition of
patient.
FR03-04 The system shall allow the doctor to edit the currenthealth condition of
patient.
FR03-06 The system shall allow the doctor to add the prescriptionfor the current
disease.
Keeping in mind the above stated requirements of the above statedmodules, you have to
answer the following questions.
(a) Identify the number of ILF and EIF in the system.
(b) Determine the complexity of ILFs and EIFs ?
(c) Identify all the transaction operations (EI, EO, EQ) in thesystem.
(d) Find the complexity of EI, EO, and EQ?
(e) Determine the un-adjusted function point count of the givensystem.
• Show less0 answers
- Anonymous askeduse goto field for condi... Show moreuse goto field for conditional jumps as there is noexplicit loop statement in SNOBOL).• Show less0 answers
- Anonymous asked(((a... Show more
Q No.1... Show more
Q No.1 20
An automobile Company XYZ has dealerships in differentcities. These dealers provide products and services to theircustomers. Automobile company assesses their dealers with thefeed back of their customers through e-mail. On the basis of thisevaluation by the customers, Company XYZ makes a decision, whetherdealers are providing proper services to their customers ornot.
You are required to findthe total attributes of all the relations used in this scenario,find the Facts for the fact table and also draw the star schema ofthe given scenario.• Show less1 answer
- Anonymous askedWrite aprogram in Assembly Language to find the maximum number and theminimum number from... Show moreAssignment Write aprogram in Assembly Language to find the maximum number and theminimum number from an array of ten positive numbers. Store theminimum number in AX and maximum number in DX.
[Hint: Use the conditional jumps]What to Submit:Submit Microsoft Word document containing the assemblylanguage code for the above mentioned program.• Show lessI need both progrm and code0 answers
- Anonymous askedFor this problem I need help with the code... Show moreThis is a verilog program assignment used with Xilinx9.1.For this problem I need help with the code.Implement and Test via Behavioral Simulation the followinglogic equation using the assign statement. The inputs are singlebit variables (in1, in2,in3, and in4). There is a single output(out1). In the labeling below (* - AND, + - OR, ~ - NOT). In yourVerilog code remember to use the bitwise operators & , | , ~for AND, OR and NOT respectively.• Show less
out1 = ~in1 * (in2 + ~in3 + in4) + ~in2 * ( in1 + in3 + ~in4) +~in2 * ~in30 answers
- Anonymous askedI am confused and at a loss on how to modify my existing progra... Show morex.HmI am confused and at a loss on how to modify my existing program to accomplish the following Instructions; anykind of assistance would be appreciated.
Implement the resident list as a dynamically allocated LINKED LIST, instead of an ARRAY of records.
#include<iostream>
#include<fstream>
#include<string>
#include<iomanip>
using namespace std;
enum typephone{w,h,c};
struct recordType
{ string ss;
char first;
string last;
string phone;
typephone phoneType;
};
recordType resident[500];
ifstream input;
void directions(void);
char firstmenu(void);
char secondmenu(void);
int add(void);
int existing(void);
bool check(string,int, int,int);
bool checklast(string);
void show(int, int);
void find(int);
void deleteit(int&);
int findssn(int);
int main()
{int count,i;
char nore;
//mode is a string representing how you want to open the file. Most often you'll open a file for reading (ios::in) or writing (ios::out or ios::app).
directions();
nore=firstmenu();
if(nore=='N')
count=add();
else
count=existing();
for(i=0;;)
{nore=secondmenu();
switch(nore)
{case 'S': if(count<0)
{cout<<"no existing data - add data\n";
count=add();
}
else
show(count,0);
break;
case 'A': count=add();
break;
case 'F': if(count<0)
cout<<"no existing data\n";
else
find(count);
break;
case 'D': if(count<0)
cout<<"no existing data\n";
else
deleteit(count);
break;
case 'E':return 0;
}
}
}
int add()
{int i=-1;
bool valid=false;
char in;
do{i++;
do{
cout<<"\nEnter Social Security Number: ";
cin>>resident[i].ss;
valid=check(resident[i].ss,10,3,6);
if(!valid)
cout<<"invalid data\n";
}while(!valid);
do{
cout<<"Enter first initial ";
cin>>resident[i].first;
if(!isalpha(resident[i].first))
cout<<"invalid data\n";
}while(!isalpha(resident[i].first));
resident[i].first=toupper(resident[i].first);
cin.ignore(10, '\n'); //ignore 26 characters or to a newline, whichever comes first
do{
cout<<"Enter last name ";
getline(cin,resident[i].last);
valid=checklast(resident[i].last);
if(!valid)
cout<<"invalid data\n";
}while(!valid);
do{
cout<<"Enter Phone Number: ";
cin>>resident[i].phone;
valid=check(resident[i].phone,10,3,7);
if(!valid)
cout<<"invalid data\n";
}while(!valid);
do{valid=true;
cout<<"Enter Phone Type\n";
cout<<"W - work\n";
cout<<"H - home\n";
cout<<"C - cell\n";
cin>>in;
switch(toupper(in))
{case 'W': resident[i].phoneType=w;
break;
case 'H': resident[i].phoneType=h;
break;
case 'C': resident[i].phoneType=c;
break;
default: valid=false;
cout<<"invalid data\n";
}
}while(!valid);
cout<<"More residents to add(Y/N)?";
cin>>in;
}while(toupper(in)!='N');
return i;
}
bool checklast(string l)
{int i;
if(l.length()>15)
return false;
for(i=0;i<l.length();i++)
{if(!(isalpha(l[i])||l[i]=='\''||l[i]=='-'))
return false;
if(i==0)
l[i]=toupper(l[i]);
else
if(isalpha(l[i]))
l[i]=tolower(l[i]);
}
return true;
}
bool check(string val,int max,int a,int b)
{int i;
for(i=0;i<=max;i++)
{if(i==a||i==b)
{if(val[i]!='-')
return false;
}
else
if(!isdigit(val[i]))
õs;x.Hmsp; return false;
}
return true;
}
void directions()• Show less
{cout<<"The local police department keeps a file of data on city residents who have marked their belongings with their Social Security Numbers (SSNs)\n";
return;
}
char firstmenu()
{char answer;
cout<<"Which data would you like to use?\n";
cout<<" N - New resident data\n";
cout<<" E - Existing resident data\n";
do
{cin>>answer;
answer=toupper(answer);
if(answer!='E'&&answer!='N')
cout<<"invalid choice: re-enter\n";
}while(answer!='E'&&answer!='N');
return answer;
}
int existing()
{int i=-1;
char type;
input.open("residents.txt"); //open file
if(input.fail()) //is it ok?
{ cout<<"file did not open please add data\n";
i=add();
return i;
}
while (input.peek()!=EOF)
{i++;
if(i==500)
{cout<<">500 records. extra records to be ignored\n";
i--;
return i;
}
input>>resident[i].ss;
input>>resident[i].first;
input>>resident[i].last;
input>>resident[i].phone;
input>>type;
switch(toupper(type))
{case 'W': resident[i].phoneType=w;
break;
case 'H': resident[i].phoneType=h;
break;
case 'C': resident[i].phoneType=c;
break;
}
}
input.close();
return i;
}
void show(int max,int k)
{int i;
cout<<" Name SSN Phone Type\n";
cout<<"-------------------------------------------------\n";
for(i=0;i<=max;i++)
{cout<<resident[i].first<<" "<<setw(15)<<left<<resident[i].last<<" "<<resident[i].ss;
if(k==0)
{cout<<" "<<resident[i].phone<<" ";
if(resident[i].phoneType==w)
cout<<"work";
else
if(resident[i].phoneType==h)
cout<<"home";
else
cout<<"cell";
}
cout<<endl;
}
}
char secondmenu()
{char answer;
cout<<"\n\nWhat would you like to do?\n";
cout<<" A - Add a resident\n";
cout<<" S - Show the existing residents\n";
cout<<" F - Find a resident\n";
cout<<" D - Delete a resident\n";
cout<<" E - Exit\n";
do
{cin>>answer;
answer=toupper(answer);
if(answer!='A'&&answer!='S'&&answer!='F'&&answer!='D'&&answer!='E')
cout<<"invalid choice: re-enter\n";
}while(answer!='A'&&answer!='S'&&answer!='F'&&answer!='D'&&answer!='E');
return answer;
}
void find(int count)
{int i;
i=findssn(count);
if(i>count)
cout<<"Resident not found\n";
else
{cout<<resident[i].first<<" "<<setw(15)<<left<<resident[i].last<<" "<<resident[i].ss;
cout<<" "<<resident[i].phone<<" ";
if(resident[i].phoneType==w)
cout<<"work";
else
if(resident[i].phoneType==h)
cout<<"home";
else
cout<<"cell";
cout<<endl;
}
return;
}
void deleteit(int& count)
{int i,j;
i=findssn(count);
cout<<"Resident with SSN "<<resident[i].ss<<" deleted\n";
count--;
if(i==count+1)
return;
else
for(j=i;j<count+1;j++)
resident[j]=resident[j+1];
return;
}
int findssn(int count)
{string ssn;
bool valid;
show(count,1);
do{
cout<<"\nEnter Social Security Number: ";
cin>>ssn;
valid=check(ssn,10,3,6);
if(!valid)
cout<<"inval[¹aax.Hm> }while(!valid);
int i;
for(i=0;i<=count;i++)
&0 answers
- Anonymous askedHello users I am having a little trouble getting my PHP codes torun correctly. I have a PHP file lin... Show moreHello users I am having a little trouble getting my PHP codes torun correctly. I have a PHP file linked to an HTML file sortof like a Login Page, however once i click the submit buttoninstead of it executing the PHP code it just pulls up the PHP filein textpad. If you have any tips or suggestions on how i canfix this please let me kno. THank yu.
• Show less0 answers
- Anonymous askedCan anybody see why my function is not working? I want the firstand last element of the array to rem... Show moreCan anybody see why my function is not working? I want the firstand last element of the array to remain unchanged and the middle ofthe array to update x number of times.
#include <stdio.h>
# define SIZE 10
void updateTemp( float data[], int size);
int main (void)
{
float temp[SIZE];
int x, i;
printf("Enter temperature of segment 0: ");
scanf("%f", &temp[0]);
printf("\nEnter temperature of segment 9: ");
scanf("%f", &temp[9]);
printf("\nEnter number of time steps to display: ");
scanf("%d", &x);
for (i = 0; i < x; i++)
{
printf("Time step %d: \n", i);
updateTemp( temp, SIZE );
}
return 0;
}
void updateTemp(float data[], int size)
{
int k, j, p;
printf("%.2f ", data[0]);
for ( p = 1; p <= size-2; p++)
{
data[p] = 0.00;
}
for (k = 1; k < size/2; k++)
{
data[k] = (data[k-1] + data[k]) /2;
printf("%.2f ", data[k]);
}
for(j = size/2; j < size; k++)
{
data[j] = (data[j+1] + data[j]) /2;
printf("%.2f ", data[j]);
}
printf("%.2f ", data[size-1]);
return;
}
• Show less1 answer
- Anonymous askedWrite a program called population.c that determines howlong it will take a town's population to reac... Show moreWrite a program called population.c that determines howlong it will take a town's population to reach a certain size. Yourprogram will ask the user for two values: a starting population andan ending population. Assuming that the population increases by 10percent each year, your program should use a loop to determine howmany years it will take for the population to surpass the specifiedending population. Output this result to the user. Your programshould have a function that prompts the user for input and afunction that computes the number of years. • Show less1 answer
- Anonymous askedx to access the first memberof the a structure. Which of the follo... Show more
The scalar() function uses po1→x to access the first memberof the a structure. Which of the following constructs can beequally→x*po2→x +po1→y*po2→y + po1→z*po2→z;
return(s);
}
B)
C)
D)
0 answers
- foreverdeployed askedGiven the structure and pointer declarations shown below, choosethe assignment statement which set... Show more
Given the structure and pointer declarations shown below, choosethe assignment statement which sets the Price member of thestructure pointed to by PC to 1000.
struct Computer
{
char Manufacturer[30];
float Price;
int Memory;
} *PC;
B)
C)
D)
Assuming the following declarations:
int A=1, B=2, C=3, D=4;
What is the value of the following (Boolean) expression?
C == D || B > A && C
B)
C)
D)1 answer
- foreverdeployed askedIt is generally a good rule for applications programmers to u... Show more1 answer
- Anonymous asked3 answers
- sailingbreez askedt... Show moreObjectiveThe objective of this assignment is to make you able tocalculate the size of system withthe help of Function Point Analysis technique.QuestionThe domain of this assignment is related to the FPA ofHospital Management System(HMS). Following are the requirements of three modules of HMSapplication. You haveto calculate the size of this application (only consider thefollowing three modules for thisassignment) using Functional Point Analysis.Requirement 01: Online Feedback submissionmoduleFunctional Requirement:FR01-01 The system shall allow the Patient to fill onlineregistration form.FR01-02 System shall generate a unique tracking id for aPatient against his/ her registration submission.FR01-03 The system shall allow the Patient to add feedbackform.FR01-04 The system shall allow the Patient to edit thefeedback form.FR01-05 The system shall allow the Patient to delete thefeedback form.FR01-06 The system shall allow the Patient to apply formultiple feedback form for multiple visits.FR01-07 The system shall allow the Patient to track thefeedback form through unique tracking id and password.Requirement 02: Employee Personal InformationmoduleFunctional Requirement:FR02-01 The system shall allow the employee to create hisprofile after login to the system. The employee will be askedto provide the information about his age, qualification,experience and family.FR02-02 The system shall allow the employee to view hisprofile.FR02-03 The system shall allow the employee to add informationin the profile form.FR02-04 The system shall allow the employee to edit his/herprofileFR02-05 System shall allow the HR Officer to delete theprofile of any employee.FR02-06 The system shall verify the NIC number of the employeefrom NADRA database. With some limited rights to view the datafrom NADRA database is built-in into the HRMS systemRequirement 03: Patient Previous Pathology recordModuleFunctional Requirement:FR03-01 The system shall allow the doctor to access thepervious Pathology record from Islamabad Pathology Lab.FR03-03 The system shall allow the doctor to access thepatient profile through access code.FR03-03 The system shall allow the doctor to add the currenthealth condition of patient.FR03-04 The system shall allow the doctor to edit the currenthealth condition of patient.FR03-06 The system shall allow the doctor to add theprescription for the current disease.Keeping in mind the above stated requirements of theabove stated modules, you have toanswer the followingquestions.(a) Identify the number of ILF and EIF in the system.(b) Determine the complexity of ILFs and EIFs ?(c) Identify all the transaction operations (EI, EO, EQ) inthe system.(d) Find the complexity of EI, EO, and EQ?(e) Determine the un-adjusted function point count of thegiven system.Note: The necessaryComplexity Matrix for calculating FP is given at the belowlink answers
- Anonymous askedI need to do program exercise #4 in chapter 10 in C++ programming:from problem analysis to program d... Show moreI need to do program exercise #4 in chapter 10 in C++ programming:from problem analysis to program design (4th ed) but i must use thefunction prototype below:
int list[12] = { 4, 23, 65, 34, 82, 37, 12, 17, 24, 36, 82, 51};
and must remove at index = 7, then move elements to indexpositions: 7, 8, 9.
output must show:
final array elements
the array size
the array element removed
• Show less1 answer
- Anonymous asked... Show moreI must use following parallel vectors:
vector<int> hours;
vector<int> rate;
and function prototype:
void printResult (vectory<int> vec 2, vector<int> vec3,int num);
step 1:
Must use push_back member function to insert following values:
hours: 40 35 40 30 40
rate: 15 20 18 17 20
after loading vectors using push_back function, must callprintResult to output the product "hours * rate" for each parallelmember.
step 2:
in the vector hours, change the values: 35 to 40 and 30 to 20 andrepeat the call to function printResult
• Show less0 answers
- Anonymous askedGiven a string of characters, write it in reverse order. Forexample, write the string “cat”
as “tac”... Show moreGiven a string of characters, write it in reverse order. Forexample, write the string “cat”
as “tac”. define a method writeBackward to doso.
you must use recursion in your algorithm. • Show less1 answer
- CollegeMath asked,... Show moreThere are two arrays a and b, each with 15 numbers , and each in sorted order, create anew array c, equal to the mergeof a and b. I want to use amerge algorithm. • Show less1 answer
- SamSan asked0 answers
- Anonymous asked... Show moreExplain what is testing the method guessWhatIDo from thefollowing program:
public class Test63{
public staticvoid main(String[] args) {
int[] x1 = { 2, 8, -34, 16, 4, 91, -6, 21};
int[] x2 = { -34, -6, 2, 4, 8, 16, 21,91};
// first call to method guessWhatIDo
boolean bv1 = guessWhatIDo(x1);
// second call to method guessWhatIDo
boolean bv2 = guessWhatIDo(x2);
// display the result
System.out.println("CMSC 130 - Homework 6- What is doing the method guessWhatIDo?\n");
System.out.println("The result of calling guessWhatIDo method onarray x1 is: " + bv1);
System.out.println("The result of callingguessWhatIDo method on array x2 is: " + bv2);
}
public staticboolean guessWhatIDo(int[] a) {
boolean bRet = true;
for (int i = 0; i<a.length-1; i++){
if(a[i] >a[i+1]) {
bRet = false;
break;
}
}
return bRet;
}
}1 answer
- Anonymous askedCompare the following Linear Congruential code to theSystem RND(1) function by writing a function t... Show moreCompare the following Linear Congruential code to theSystem RND(1) function by writing a function that compares the meanand variances of each for any arbitrary (user-specified) number (N)of uniform deviates.5 REM Knuth's Linear Congruential Random NumberGenerator10 INPUT "N = "; N20 jran = 120030 For I=1 to N40 div = (jran*84589+45989)/21772850 jran = int ( (div - int(div))*217728 )60 ran = jran/21772870 Print I, ran80 Next I90 Goto 10• Show less0 answers
- Anonymous askedThe ancient Greek mathematician Euclid developed a method forfinding the greatest common divisor of... Show moreThe ancient Greek mathematician Euclid developed a method forfinding the greatest common divisor of two integers, a andb. His method is as follows:
1 answer
- If the remainder of a/b is 0 then b is thegreatest common divisor.
- If it is not 0, then find the remainder r ofa/b and assign b to a and the remainderr to b.
- Return to step (A) and repeat the process.
- Anonymous askedFor this assignment, add a couple of functions to go along withthe ones that were coded for... Show more
Overview
For this assignment, add a couple of functions to go along withthe ones that were coded for Program 7. The program will continueto process a data set that represents the players that were withthe Chicago Blackhawks during the 2008 - 2009 regular season. Theinformation in the file will still be stored in a set of arrays.The arrays will be sorted, displayed, and then processed.
The new code for the assignment will involve:
writing a function to search for a specific player
writing a function that will find the most number of goalsscored, assists, and number of shots attempted over the season. Itwill usethe call-by-reference techniques thatwere discussed in lecture.
Suggested Logic for main():
NOTE: all of the functions mentioned inthis logic are described below.
Fill the three integer arrays by callingthe buildArrays() function.
Sort the four arrays by callingthe sortArrays() function.
Display the sorted arrays by callingthe printArrays() function.
If the player is found, display the number of goals and assistsfor that player. If the player is not found, display a message,including the player's name, indicating that the player was notfound.
If the player (you) is found, display the number of goals andassists for that player. If the player is not found, display amessage, including the player's name, indicating that the playerwas not found.
Call the findMost() function todetermine the most goals, assists, and number of shots.
Display the name of the player that scored the most goals,include the number of goals in parenthesis. Display the name of theplayer that had the most assists, include the number of assists inparenthesis. Display the name of the player that attempted the mostshots, include the number of shots in parenthesis.
Functions to write and use
bool playerSearch( string names[], int numPlayers, stringnameToFind, int &nameLoc )
This function will sequentially search the array of strings fora specific name. If the name is found, the "location" (subscript)will be "passed back" using the fourth argument and true will bereturned. If the name is not found, return false.This function takes four arguments: an array of strings to besearched, the number of players in the array, the name to searchfor, and an integer reference to pass back where the name wasfound.
void findMost( int goals[], int assists[], int shots[], intnumPlayers, int &mostGoalsLoc, int &mostAssistsLoc, int&mostShotsLoc )
This function will search the appropriate array to find the mostgoals scored, assists, and attempted shots. It should pass back the"location" (subscript) of each value using the last threearguments.
This function takes as its arguments the three integer arrays,the number players in the array, and three integer references topass back the results.
Output:
Chicago Blackhawks 2008-2009 Player StatsPlayer Goals Assists Points Shots Shooting %------------------------------------------------------------------Aaron Johnson 3 5 8 27 11.1Adam Burish 6 3 9 83 7.2Andrew Ladd 15 34 49 195 7.7Ben Eager 11 4 15 80 13.8Brent Seabrook 8 18 26 132 6.1Brent Sopel 1 1 2 15 6.7Brian Campbell 7 45 52 108 6.5Cam Barker 6 34 40 101 5.9Colin Fraser 6 11 17 67 9.0Dave Bolland 19 28 47 111 17.1Duncan Keith 8 36 44 173 4.6Dustin Byfuglien 15 16 31 202 7.4Jack Skille 1 0 1 14 7.1Jacob Dowell 0 0 0 0 0.0Jonathan Toews 34 35 69 195 17.4Jordan Hendry 0 0 0 1 0.0Kris Versteeg 22 31 53 139 15.8Martin Havlat 29 48 77 249 11.6Matt Walker 1 13 14 83 1.2Niklas Hjalmarsson 1 2 3 15 6.7Pascal Pelletier 0 0 0 7 0.0Patrick Kane 25 45 70 254 9.8Patrick Sharp 26 18 44 184 14.1Sammy Pahlsson 7 11 18 88 8.0Tim Brent 0 0 0 0 0.0Troy Brouwer 10 16 26 126 7.9Dustin Byfuglien scored 15 goals and had 16 assists.Amy Byrnes was not foundPlayer with the most GOALS: Jonathan Toews (34)ASSISTS: Martin Havlat (48)SHOTS: Patrick Kane (254)
• Show less0 answers
- ShaggyZebra6672 askedCreate a linked list structure to implement a stack and alsocreate a linked... Show moreWill ratelifesaver!!!!!Create a linked list structure to implement a stack and alsocreate a linked list structure to implement a queue.• Show less
To demonstrate that the stack is working correctly, write a smallfunction using a stack that will determine if a given input stringis a valid tag.
A valid tag is defined as the character < followed by a group ofalphabetic characters followed by a >. Recall that casting acharacter to an int will give you the ASCII value of thatcharacter. The lowercase characters have ASCII values between 97and 122. The upperclase characters have ASCII values between 65 and90. You may assume that the input to the method is a C string, thatis an array of characters.
To test the queue, ask the user for input until they enter a -1.For each integer they give you, if it is odd, enqueue it in onequeue, if it is even, enqueue it in another queue. After a -1 hasbeen entered, display first the even numbers entered, and then theodd numbers.1 answer
- Anonymous asked0 answers
- Anonymous asked0 answers
- Anonymous askedint x =1-,... Show morepredict the output
#include <stdio.h>
int kirk(int, int, int *, int *);
void main ( )
{
int x =1-, y =20, z;
z = kirk(x,y,&x,&y);
printf("*1* %d %d %d \n" , x, y,z);
}
int kirk(int a, int b, int*p, int*q)
{
printf("*2* %d %d %d %d %d %d\n,a,b,p,q,*p,*q);
a=50
*q=60;
printf("*3* %d %d %d %d %d %d\n,a,b,p,q,*p,*q);
return b;
}
• Show less1 answer
- Anonymous asked1 answer
- Anonymous asked2 answers
- Anonymous askedThis is suppose... Show moreI've looked over the finite difference method, but I'm stillstuck. Where do I start??
This is supposed to be a program written in C.
Set up the equations for solving the differential equation
with boundary conditions x = 0, y=1.0 and x = 1, y = 0.0 usingfinite difference method we have discussed in the class.
The set up should result in simultaneous equations where the numberof equations depends on the number of points that ‘x’is divided into.
Solve for ‘y’ as a function of ‘x’ usingthe equations set up above using successive substitution method.Check the results for 5 divisions and 10 divisions for‘x’.
• Show less0 answers
- Anonymous askedprivate String author... Show more
Consider the following (partially defined) Java classBook.
public class Book {
private String author;
private String title;
private int year;
private String publisher;
public Book (String a, String t, int y, String p) {
// ... code
} public Book() {
// ... code
} public String toString() {
// ... code
} public void displayBook() {
// ... code }
}
a. List the data fields (also known asproperties or instance variables) of the classBook.
b. How many constructors define the classBook.
c. Identify an overloaded entity defined by theclass Book. Explain.
d. List the methods defined by the classBook.• Show less1 answer
- Anonymous askedNote: the fu... Show morewrite a function which will return the value of the largest threeintegers passed to it.
Note: the functions should not do any input or output (noscanf or printf).
The prototype of the function is:
int findbig(int, int, int);
• Show less3 answers
- Anonymous askedN mushrooms, g... Show moreI have a homework which I do not know where i canstart... Could someone help me out?
N mushrooms, growing along a circle, are ready to bepicked. Walking in one direction around the
circle, you pick the rst mushroom, skip a givennumber skip, pick the next one,skip skip again,
pick the next, and continue doing so until all mushroomsare o
the ground.
Write a program whose inputs are Nand skip. Print the mushrooms in theorder they are
picked. You may assume that Nis at most100.
Sample run:
()$ a.out
# mushrooms and skip size: 101
1 3 5 7 9 2 6 10 8 4
()$ a.out
# mushrooms and skip size: 104
1 6 2 8 5 4 7 10 3 9
()$ a.out
# mushrooms and skip size: 1010
1 3 6 10 8 9 5 2 4 71 answer
- Anonymous asked0 answers | http://www.chegg.com/homework-help/questions-and-answers/computer-science-archive-2009-november-04 | CC-MAIN-2014-35 | refinedweb | 8,115 | 57.16 |
?..
:) Loved your rant. Feel better now?
The first big flaw in your article is “Automattic in this post refers to statements by Matt Mullenweg” which implies that Automattic (or myself) control WordPress.org unilaterally.. It’s also an opinion shared by every major developer of WordPress, the majority of whom do not work for Automattic. Thus, it is unfair to refer to the opinions above as mine or Automattic’s, probably the most accurate way to update your article would be to say “the WordPress core team.”
The GPL is about user freedom, not developer freedom. It says the users have certain rights with regards the the software and no one, not even the developer, can take them away. When someone claims their plugin or theme is not GPL, they take away user freedom. If this wasn’t a concern to us, we would have chosen something like a MIT or BSD license.
If you’re curious about the SFLC:
.”
@kelltic
Not really. You know, best kind of rant is after you are done and you look at situation and think “screw this, it is over”.
Looking at this one I only feel “this is so not over…”
@Matt
Thank you for dropping by and spending your time to reply. This post is not really intended to make another fuss with multiply people involved (we have WPTavern for that, heh), but to express my thoughts on subject in single and appropriate place.
which implies that Automattic (or myself) control WordPress.org unilaterally.
I am sorry, but this is impression I get. More like I was never able to distinguish who does control it. And I also get an impression that it is common, see for example WPTavern threads when people had their plugins kicked and were completely lost about who is responsible for what on wp.org..
I am perfectly aware of that one and it is linked to in post (somehere).
But decision? That is opinion and there are opinions that differ. I disagree (small me, but again – my opinion which I call what it is).
It’s also an opinion shared by every major developer of WordPress, the majority of whom do not work for Automattic.
I am sorry, did I miss a poll?
WPBlogger did a number of interviews with some of those major developers. Somehow they all say almost same thing – they only went GPL so community would shut up about them. To be “in line with WordPress” and “in line with Automattic” is not strong opinion on GPL, it is weak action to follow the herder.
When someone claims their plugin or theme is not GPL, they take away user freedom.
Oh yes, those evil ones who dare to license their work how they see fit and not agreeing to GPL linking opinion. How dare they. :) I mean I use theme licensed under Creative Commons, clearly my freedom is being smashed here.
If this wasn’t a concern to us, we would have chosen something like a MIT or BSD license.
Does this void my understanding (stated in post) that WordPress has GPL inherited as b2 fork and is stuck with it (unless some major code changes happen)?
If this is major concern – why wasn’t license with clear terms on linking extensions used? I believe it’s not that hard and allowed to make derivative of GPL with additional clauses.
If you’re curious about the SFLC:
Yep, very scary. I believe I read somewhere that there is no intention from WP to bring any of people who do not agree to lisence their extensions under non-GPL terms to court.
“We would have totally won this one” is another opinion, not a fact.
Any of those cases dealt with CMS themes by the way? :)
I say let’s fork the shit out of it, and build a multi-license plugin directory where people can make compatible plugins that can be sold.
People are selling themes left and right, why can’t awesome PHP developers come and make wordpress better.
There’s plenty of plugins out there that need to be developed, some people like myself probably have the skills to do it but lack the motivation and time for it.
Why can’t we have the equivalent of an App Store?
I’m all for GPL, but you can’t force people to write extensions and license them the way you want to. I’ve heard lots of bad stories also on how the wordpress plugin directory is run, and if you have to time to read some of the code of the most popular plugins in there, it seems like the curation process right out sucks, it all seems like a mafia they got going on there.
Fork, Fork, Fork, Fork.
@Matt
“The GPL is about user freedom…..If this wasn’t a concern to us, we would have chosen something like a MIT or BSD license.”
This is a null argument since the original b2/cafelog is GPL, you can’t change it.
If you care so much about the GPL and freedom, maybe you should encourage Brett Smith to write another letter to Apple and remove the WordPress for iPhone from the Apple Store ().
“I also discussed it with Richard Stallman…” and you think it’s a good thing? He was a great programmer but today he is very close to very polemical political affiliations (supportive of Hugo Chavez, Advisory Council of TeleSUR).
At the end, serious innovations and changes does not care about the GPL issue, because they are made in software as services and they are never released for free. How much do you think the Automattic’s profit come from GPL stuff?
@Gubatron
I believe there are some stores already, PluginBuddy comes to mind. But WP experience is very wp.org-centric in starts. Most users won’t know/care about alternatives anyway.
By the wa technical side is very wp.org-centric as well. Plugin update system is not flexible and suffers with backwards compatibility issues.
There’s plenty of plugins out there that need to be developed, some people like myself probably have the skills to do it but lack the motivation and time for it.
It would be interesting to see service that offers fixing up and bringing up to date plugins from official repository.
Why can’t we have the equivalent of an App Store?
Vendor-controlled environment with tight obscure rules and shaky practices? :) I believe we have one. At least we don’t have to root WordPress to install plugins from elsewhere. :)
I’m all for GPL, but you can’t force people to write extensions and license them the way you want to.
Craziest thing I hear occasionally is that if WP extensions are mandatory GPL and you can take and do whatever you want with any of them. This is crazy. You can’t assume GPL! Unless developer explicitly made his code GPL it isn’t. He may be or may not be breaking GPL in process, but short of court you can’t just put GPL label on it.
@Alden Torres
At the end, serious innovations and changes does not care about the GPL issue, because they are made in software as services and they are never released for free.
Like wpmu.org if I understand you right. And this is exactly model Automattic( /Matt /core team? :) showed to have problem with. Desirable functionality behind paywall detriments from WordPress “free and happy” image.
WordPress extensions cannot run without WordPress, link core WordPress functions and data structures, and are executed as a single stream at runtime. The GPL was created to cover exactly that sort of linking. Just because someone says the opposite, the most comprehensive arguments coming from a Florida real estate attorney, doesn’t mean there is any real dispute. Regardless, the polite thing to do in an ambiguous situation is to respect the intent and opinion of the authors.
The GPL enables businesses to thrive in a stable environment, as the numerous 100% GPL theme and plugin businesses show. (Which collectively generate tens of millions in revenue a year, and growing fast.) Who knows whether they or their customers care about the GPL or not (is that even relevant?) but they are building their businesses on a strong legal foundation and with the respect and support of the core WP team.
(By “core team” I mean the several dozen people currently busting their butts to make a powerful, flexible, and stable 3.0 for you, all the while WP is being downloaded over 40k times a day.)
Automattic, my business, has shown the same, becoming one of the top 10 properties on the web, profitable the whole time, while contributing countless hours to GPL software and releasing all of our improvements from WordPress.com even though we’re not required to under the letter of the GPL, which did not anticipate web services. It’s just the right thing to do.
I’m probably not going to change your mind if you’ve decided you don’t like the GPL, or that it’s an ambiguous license despite standing strong for 15+ years, but at least recognize that 99% of the businesses out there are 100% in line with the license and doing fantastic. At every WordCamp I meet hundreds of people whose lives and livelihoods have been positively transformed by WordPress, a group we know numbers in the tens of thousands in the United States alone.
In a market growing this fast, isn’t it common sense to want to be aligned with the platform you’re building on? If not, better to build on something else. If you want a non-GPL platform, I would suggest Habari (Apache), Serendipity (BSD), Movable Type (proprietary license option), or Expression Engine (proprietary). Avoid Drupal or Joomla as they share WordPress’ “opinion” of how extensions should be licensed.
WordPress extensions cannot run without WordPress, link core WordPress functions and data structures
Not necessarily. All or part of extension code can be completely WordPress-unspecific, except for meta information needed to recognize it as extension.
Even if it is completely WordPress-specific it is still ambiguous if such linking establishes derivative work. I understand you consider that it is. Some people don’t.
And Wikipedia still has page of text dedicated to how screwed up situation with GPL and linking is. And that text isn’t going away for some reason.
The GPL was created to cover exactly that sort of linking.
GPL was created to cover compiled software binaries. It was not created to cover loosely linked interpreted code with CSS, JS, docs and images on top. By the way I have trouble with concept of images under GPL at all.
(By “core team” I mean the several dozen people currently busting their butts to make a powerful, flexible, and stable 3.0 for you, all the while WP is being downloaded over 40k times a day.)
I have no gripe with WordPress as product and its development. I am reasonably happy with it, otherwise I’d use something else.
And I rarely see most WP developers going around telling people how they should run their blogs and businesses. You tend to. :)
I’m probably not going to change your mind if you’ve decided you don’t like the GPL
And where did I ever said such thing? I have no issue with GPL. I have issue when people start to play loose with it. I have issue when people in total compliance with GPL are considered some kind of impure. I have issue when GPL is bent to fit opinions instead of being legal document it is. I have issue with GPL used to justify “open source spirit” demands that go well beyond GPL letter.
In a market growing this fast, isn’t it common sense to want to be aligned with the platform you’re building on?
When platform tries to police what you say, link to and advertise online at your blog and puts additional restrictions on top of GPL… this decision moves from “common sense” into “may be, may be not” area.
As I summed up in post I’d like to drop pretense that this stuff is about GPL and GPL only. This is political. You have a vision of how WordPress ecosystem should work (one I believe formed by your business obligations as well as your personal beliefs) and you use leverage you have to implement and uphold this vision.
I would very much prefer that your vision was in form of clearly defined code of conduct or whatever, as what Chip Bennet suggested on WPTavern.
Rather than FUD. Because developers being hit with “you are evil and will be banished from WP.org” out of nowhere for no reason except not fitting your vision is FUD. When developers adopt GPL out of fear to not fit your vision alone it is FUD.
GPL was not made to be scared into.
“I have no issue with GPL. I have issue when people start to play loose with it.”
100% agreed. :) I’ve discussed this very issue with the guy who wrote it, the lawyers who defend it, and my fellow developers who choose to license their work under the GPL. The rights and responsibilities of WordPress developers under the GPL are exactly the same as what they are under other projects with similar structures. Nearly every developer I’ve talked to with an invalid license on their theme or plugin did so because they didn’t know any better. (An honest mistake, one we could probably lessen by more resources on WordPress.org, as you recommend.)
They switch out their invalid license with the GPL, and their business continues on just as before. The only difference is they’re building their prosperity on a solid foundation of decades and billions of dollars of GPL-based open source development, not some fringe interpretation that seems to occur only along the edges of the WP world. (I can name two, out of well over a hundred substantial businesses and products, so let’s call it 2-3%.) They can focus on things that really matter, like creating solutions that work for their customers and users.
I have lots of opinions about everything, including how to run a business. (Though that is informed by my relatively short experience.) However one of the freedoms of the GPL is that people can run the code, and their business, in any way they like. That freedom could be taken away, however, by proprietary extensions.
What if your theme had a license that said you couldn’t criticize the author? (Don’t laugh, there was a CMS that had such a clause in their license.) Now it’s not just your theoretical software freedom, but your actual freedom of speech being taken away, and there’s nothing you can do about it except abandon the theme.
WordPress protects its users from this by its own license, the GNU Public License (GPL), that says extension developers can’t spoil WordPress with restrictions for their own personal gain at the expense of the community and user freedom. It would be a horrible tragedy of the commons we’ve created together over the past seven years, if such protection wasn’t in place.
It’s a Bill of Rights for WordPress users.
By the way, PluginBuddy, along with the rest of iThemes endeavours, is completely awesome and in line with the GPL. They’re a great example of one of the many businesses that doesn’t think they need to break a license to make a buck. iThemes is listed on the commercial theme directory on WordPress.org, and has been from day one.
@Matt
100% agreed. :)
Except that I include putting more restrictions on top of GPL as “playing loose” as well. As I repeat it goes well beyond actual license.
What advertisement you run on blog came up as factor more than once. It has what exactly to do with GPL? It comes back to that “non-GPL-compliant people” which is probably craziest definition I heard this year.
Every single GPL fallout on WPTavern comes down to letter of GPL versus open source spirit of GPL. And message from “WordPress core team” seems to favor spirit more often than letter.
Again – it’s you leverage and up to you how to use it. Just don’t be surprised when it irks people who disagree. Leverage works that way – when you swing you hit something.
They’re a great example of one of the many businesses that doesn’t think they need to break a license to make a buck.
And yet just as GPL compatible wpmu.org got much less stellar words from you.
The difference? They dared to sell valuable functionality (as opposed to generic and abundant market of themes). Again – out of GPL realm and into specific vision of WP ecosystem.
To sum up a little there are different opinions and there always will be. However delivering your opinions with a stick of repository purges and occasional blog comments only blazes stuff more.
Clear project structure, code of conduct and personal responsibilities. Is it such an irrelevant information to have?
Also could use real documentation. Codex kinda fails. :)
I hope I made it clear that I am neither WP or GPL hater. I am not much into hating things overall. But a lot of things with WP really make me react with wtf. And almost two years into it that is a lot of wtf moments.
I’ve been talking about the GPL, I think you’re talking about the website policies on WordPress.org-the-website. For the record, WP places *no* additional restrictions on top of the GPL. The license is the license. There’s no spirit. There was confusion around extensions, but that’s been cleared up by us and the SFLC.
There are a small, small handful of products left that violate WordPress’ license, which is found morally reprehensible by the core team in the same way any intellectual property abuse is. Let’s say what you found morally reprehensible was taking ice cream from kids. Let’s say you were sending significant amounts of traffic to websites that were sponsored by child-ice-cream-stealing, or contained prominent ads on “how to steal ice cream.” You would reconsider sending your audience to such an odious place.
The third issue you raise, around wpmu.org, has nothing to do with the GPL or valuable functionality but with significant marketplace confusion being created by borrowed designs and predatory trademark infringing domain-name acquisition, use, and SE optimization aimed toward sites like wordpressmu.org. If you put yourself in the shoes of a novice user, it’s very confusing, and one of the reasons we retired the MU moniker.
If you want fewer WTF moments, change the places you hang out. If you judged by a few Twitter accounts, or particularly drama-filled blogs or forums, you’d think the entire project was on the verge of collapse. Once you get outside of the inside baseball stuff and into the real world, like at a WordCamp, it’s amazing and refreshing to see what the real WP community is like. You’ll never meet a more supportive or generous group anywhere.
@Matt
I’ve been talking about the GPL, I think you’re talking about the website policies on WordPress.org-the-website.
I am talking how blurred is line between GPL and GPL+open source spirit. What is essentially a technical issue is repeatedly brought into emotional and moral context.
I’ve seen perfectly fine businesses as Theme Forest with dual-licensed themes referred to as suspicious because of “everything should be GPL” ecosystem you insist on for WP.org
I talk about GPL and WP.org because believe me they are mixed into complete mess in many heads. Current blend of GPL with semi-official policies on top of it creates environment where you can’t be sure what is license and what are vague unwritten guidelines.
On traffic – I understand where you come from, but not methods. I find it questionable that it is more important to banish person with some banner on his blog than to have and benefit from fine GPL code he submitted to repository. Again – GPL and moral get mixed up.
That is not kids and ice-cream, that is more like firing person for what he is doing in his backyard.
On wpmu – didn’t look like that from the sideline. I revisited those comments when writing this post and it clearly started with functionality and moved into branding later (seemed like afterthought to me).
Quoting you:
Therein lies the problem. [...] When that development is instead channeled behind a paywall, regardless of license, the community suffers, as MU has.
Thus distinct impression that being GPL in WP ecosystem is not enough if you do something “WordPress core team” finds not to their taste.
If you want fewer WTF moments, change the places you hang out.
At moment I have little opportunity to travel and I don’t think there are any WordCamps planned around here.
So here is backwards perspective – people whom you meet at WordCamps are only tiny percentage of WP community. Probably quite active percentage but that doesn’t make numerous people like me that primarily hang out around WP online any less real and any less community.
Awesome read.
@Rush
I think that is shortest comment I ever had from you. :) Glad this ended up with some entertaining value after all.
So I guess it’s just a matter of the likes of PluginBuddy to streamline the plugin installation and purchase process by creating a GPL Plugin :)
Basically, you go to a PluginBuddy like site, get their plugin, and then you can browse all the non-free plugins inside your wordpress.
If only I had the time.
@Matt:
And I’m all for GPL, but share the cake baby. Automattic is profitable, super top hot 10 property in great part because of that community that supports you. Why not make it 1000 times more profitable by opening up to the idea of allowing also paid-for plugins?
Don’t get too cocky on your success, and look to the future, Google will be doing the same on Chrome with their Web App Store, you are in an amazing position to become hugely profitable, if you don’t take that chance you’re not as bright as you think.
I find this line of thinking a little bit weird:
“WordPress extensions cannot run without WordPress, link core WordPress functions and data structures, and are executed as a single stream at runtime. The GPL was created to cover exactly that sort of linking.”
It this was true, then every piece of code that runs on the Linux kernel should be GPLd.
Say you needed to use a socket struct in your C code…
#include // <– GPL 2 code from kernel
struct sock* mySockPtr;
eventually your program will link down to sock.h, it won't be able to open a socket, hell, it won't run without the linux kernel, therefore it must be GPL :)
@Gubatron
Automattic is profitable, super top hot 10 property in great part because of that community that supports you. Why not make it 1000 times more profitable by opening up to the idea of allowing also paid-for plugins?
Because it’s not their business model. Ideal environment for Automattic seems to be lots of free stuff (big part of WordPress promotional value, it doesn’t want to be known as platform where you have to pay all the time) and GPLed to death so it is as straightforward as possible to use it in WP.com (and then WP.org).
So ideal stuff – free and completely GPL (not that it even makes much sense for images and such).
Less than ideal, but bearable – free or paid generic stuff, GPL+something (doesn’t matter that theme is paid, thousands free around).
Unfavorable – GPL paid killer functionality (no free version), yes I am still not buying that wpmu stuff was about branding alone.
Mortal sin – paid non-GPL stuff, even worse if it is market success.
Notice how line is blurred in the middle. You can be ok with license, but so-called “community” (people labeled as such by “WordPress core team”) won’t be happy with you.
Yesterday I had seen post on WPTavern straightly saying that dual-licensing is against WordPress philosophy. Crazy, but that is what “community” being formed into. GPL or else!
Gubatron, with regards to the kernel, fortunately they’ve thought of that. Kernel modules (like WP extensions) are considered to fall under the GPL, but the COPYING file includes a specific note on userspace programs: “NOTE! This copyright does *not* cover user programs that use kernel services by normal system calls – this is merely considered normal use of the kernel, and does *not* fall under the heading of “derived work”.”
In a similar way WordPress doesn’t consider programs using the XML-RPC, Atom, RSS, or other HTTP-based APIs to fall under the GPL. Someone could write a theme that didn’t use any WordPress functions, just parsed public RSS feeds, and I wouldn’t consider that to be under the GPL. There are some other technicalities, such as the include direction, but that’s the gist.
I’m not sure what you mean by share the cake — I can’t think of any cake more delicious than the right to use all of the GPL code we release or contribute to for any purpose, including commercial. The WordPress ecosystem collectively makes 25-50x Automattic’s revenue. (Just because we contribute the most back, doesn’t mean we make the most.) That’s a direct result of how open the commercial community, of which Automattic is a part, has remained.
Rarst, I know that in day-to-day life it’s unusual for a commercial entity to have a mission besides just profit, but it does happen! Spend some time talking to any Automattician and you’ll see that. Also, your theory only works if this was a grand conspiracy promoted by Automattic people to dupe everyone into releasing things for free and taking advantage of that. It breaks down because that hasn’t happened, we’ve produced and contributed back enormous amounts of code and time, and the reading of the GPL you disagree with is the consensus amoung many independent organizations, including dozens of individual contributors and the SFLC.
@Matt
This copyright does *not* cover user programs that use kernel services by normal system calls – this is merely considered normal use of the kernel, and does *not* fall under the heading of “derived work”
So… Aren’t WordPress extensions “normal use of WordPress core” then? :)
I don’t know details on Linux, so if you might clear up this… Whose choice it was to define userspace apps as normal use on Linux? Whose choice it is to determine WordPress extensions as derivatives? Wait, you said there is no choice…
Also, your theory only works if this was a grand conspiracy promoted by Automattic people to dupe everyone into releasing things for free and taking advantage of that.
Oh, I don’t believe in conspiracy. I don’t think you click “chatroom for discussing evil plots” in the morning and decide whom you are going to go screw up today. :)
But scenario works just fine without conspiracy. See reference to interviews with major developers above. They did not comply with GPL because they had strong opinion and clear idea how would that benefit their business (judgin by interviews it hardly does). The complied merely to be “in line”.
And that is line you are drawing.
Ask a payment for killer functionality and you are hostile. Put a banner to Thesis on your blog and you are immoral. Dual-license your code and you are suspicious.
No need for conspiracy theory for these thoughts blooming. Just occasional WP.org purge and comment here and there.
Interesting read, but man, this is way over my head!
@JeeMan
This issue is one of WP land mines. :) You start to use WordPress thinking “hey – this is cool, easy and overall awesome” and year later it is “wtf, I wish I knew this, this and that”.
Well, techie perspective. Luckily most of WP users won’t have to ever bother bother knowing issues with GPL and many more.
I’ve tried my best in this conversation, but I feel like you’ve already made up your mind and you don’t accept anything I say at face value without imagining a bad intention behind it. i hope that you continue to enjoy the benefits of using WordPress, even if you disagree with the people who built it.
@Matt
I feel like you’ve already made up your mind
I have no problem changing my mind. But I don’t see much new data here. I am aware of both views on linking, repeatedly stressing that your opinion is right doesn’t really make me less sure about mine.
you don’t accept anything I say at face value without imagining a bad intention
I am not imagining bad intention, more like biased towards certain things.
i hope that you continue to enjoy the benefits of using WordPress, even if you disagree with the people who built it.
Will do. :)
Thank you for your time!
@Matt,
I personally appreciate your time writing in this post. It doesn’t matter if the result is nothing more than good comments. It’s always good to see you inside the community.
@Matt
(It’s awesome that you’re actually reading this btw, thanks for the time spent)
What do I mean by “Sharing the Cake”? I think you could do a hell of a lot better than Steve Jobs himself on running a Plugin Store for wordpress. You have the Open vision, and you have demonstrated to truly know the technicalities and gray areas of the GPL, I will in no way win an argument on those areas with you.
I think that there are some interesting ideas that can work ON TOP of WordPress via a GPL plugin. Let’s say I built an RPG platform to engage users into participating, rating, the content of a WordPress based website. I could build my entire RPG platform completely independent of wordpress and have it talk to WordPress using a GPL plugin, I’d like to sell my RPG platform to 10s of thousands of blogs out there, wouldn’t it be cool if we shared the cake?
By me having a WordPress Centric experience to sell my RPG Platform + WordPress RPG Plugin THROUGH the Official Plugin Directory I get plenty of exposure, Automattic gets a % of each sale. If it’s a service, Automattic gets a % on every recurrying payment.
As of now, Automattic is doing fine, you managed to create a great business model around it but you’re eating all the cake. Sure, we get GPL code, but why not consider the opportunity. Themes are making a killer, there’s tons of Web entrepreneurs who would jump on a WordPress Market in an instant, there’s so much fabric to cut on this idea, think micropayments, virtual goods that could be shared across wordpress instances.
I think WP can be a lot more while still keeping it’s GPL flavor, I think there should work arounds and you’ll be flooded with business.
“WordPress extensions does not include or bundle WordPress code, the only thing from WP they include are function names.”
I think it is pointless to discuss a GPL or license if you fail to recognize the validity of the license or the spirit of the thing or even know that a function is more than a name.
Developers who are against the GPL simply want to have their cake and eat it to, you build on code that was made free to you and use it to make money ignore the license and then want others to respect yours!!!!.
@shawn sandy
First and last warning – I will not allow trolling here. You want to talk, keep it polite and civil and less assuming everyone is dumb but you.
I think it is pointless to discuss a GPL or license if you fail to recognize the validity of the license or the spirit of the thing
I never challenged validity of GPL. Spirit of GPL is something so vague that some people twist in the opposite of GPL really promotes. So don’t give me spirit, most of the time that is only tool for people to justify their personal agendas and cover ass with authority of GPL.
function is more than a name
Calling functions and incorporating them in your code are different things. Disagree?
Developers who are against the GPL
And what gives you idea that developers are against GPL? That they dare to disagree on linking? And that is exactly the problem with attitude – you either shut up and what WordPress core team says or you are evil all around. Yay for WordPress freedom.
want others to respect yours
I think all work deserves respect. And work of third party developers no less than work of WordPress core team. Not being hired by Automattic doesn’t make someone inferior human being..
Can’t make sense of this passage. Why find ways around GPL if you may just stick with your opinion on linking and release your extension in line with that? Why bend your code to fit opinion that is neither yours or something you agree with?
I am sure where I was impolite, but I will apologize for sharing my view and having a strong difference of opinion, after all it is your blog and I have respect your wishes!!!
***I am sure I was not impolite, but I will apologize for sharing my view and having a strong difference of opinion, after all it is your blog and I have respect your wishes!
@shawn sandy
I have no issue with you sharing your views, different or not. I only ask that you don’t treat those with different opinion as morally or intellectually inferior.
In that one comment you claimed other side of debate is unable to understand terms of GPL, sucks at programming and is out to maliciously rip off WordPress project.
If that is polite I’d hate to see your version of rude.
As for me THIS is the issue with WordPress community. And this is exactly what original post is about – having different opinion on GPL and linking (or whatever else) should not be an excuse to vilify people.
“In that one comment you claimed other side of debate is unable to understand terms of GPL, sucks at programming and is out to maliciously rip off WordPress project…..”
Your interpretation I cannot change that…
As it is the web today is filled with way too much noise and clutter, so when I say anything I try to be as direct and factual as possible not politically correct.
This is not the first time I have engaged you in this conversation and the like I said the GPL is clear on this matter and that is a fact!
Another fact is that when you add a function to a theme it executes pieces WP code and what you get is the results of the code… Without the WP code and the php compiler all I would be seeing is “”. It is the GPL that allows you to do this if it did not you would not be able to reuse a single line of that code for anything. It is the way code works, suggesting otherwise seems either irresponsible or uninformed.
“freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs….”
All of the themes I write for WP use a simple MVC structure and I do this for two reasons 1. Is the WordPress theme structure of including files is archaic, and does not allow you to reuse code.
2. I can truly separate my design and code from the WordPress core and in fact reuse it anywhere. It does not take much to do this.
I have looked at a lot of these themes they contain a lot of sloppy code that is not fit for redistribution or resale for that matter.
As for frameworks most of them contain WP function wrapped in more functions creating more bloat than innovation IMHO.
My biggest issue with the GPL is that it seems to promote free as beer more than it does Freedom to share but that is a whole other issue.
That said you can choose to delete this post if you wish, I would expect and have no problem with it.
@shawn sandy
Another fact is that when you add a function to a theme it executes pieces WP code and what you get is the results of the code… Without the WP code and the php compiler all I would be seeing is “”.
Is WP derivative of PHP? It does execute PHP functions and get results. WP won’t work without PHP.
It is the GPL that allows you to do this if it did not you would not be able to reuse a single line of that code for anything. It is the way code works, suggesting otherwise seems either irresponsible or uninformed.
So you think Linux is wrong in considering function calls as “normal use of kernel” and not establishing derivative work?
GPL establishes license inheritance for derivative works. Unfortunately what IS derivative work can be vague. GPL contains no definitions of such on top of weakly formulated that is to say, a work containing the Program or a portion of it.
I have looked at a lot of these themes they contain a lot of sloppy code that is not fit for redistribution or resale for that matter.
I must note that WP code is hardly marvel itself… :)
This is why I have to sound like I talk down, I get my facts before I make a statement so I am confident when I say something or I say I do not Know…
It does not matter if WP is a derivative of PHP under the php licence it does not make a difference.
” GPL enforces many restrictions on what can and cannot be done with the licensed code. The PHP developers decided to release PHP under a much more loose license (Apache-style), to help PHP become as popular as possible.”
I am not familiar with the linux licence so I cannot answer that questions sorry.
Actually the GPL is quite clear on what it considers a derivative!
The WP code is simple for most part, I am not sure what you mean by hardly a marvel???
It does not matter if WP is a derivative of PHP under the php licence it does not make a difference.
I missed the answer… So do you or do you not consider WP derivative of PHP? :)
Actually the GPL is quite clear on what it considers a derivative!
Quote please.
The WP code is simple for most part, I am not sure what you mean by hardly a marvel???
Simple?? I mean that it is messy, complicated, plagued by multiple layers of backwards compatibility and deprecated functions.
In the end it works, but I suspect that a lot of sloppy third party code is that way because it is pain to get it right with WordPress. Every little thing with WP can waste ton of time on how to do it in right way with poorly documented APIs.
“A derivative is something which has been developed or obtained from something else” so technically it is!
Now thats out of the way read the GPL to understand how derivatives should be handled.
Have you ever really explored WP code-base, do you understand why backwards compatibility is an issue, or it exists!
I can assure that sloppy codes by theme and plugin devs have nothing to do with WordPress!
“A derivative is something which has been developed or obtained from something else”
When I open blank text file and write code for WordPress theme I neither “develop from” or “obtain from” WordPress. I can code without even seeing any of WP code, merely using API documentation.
How can I derive from code I don’t see?
I am still waiting for your answer is WP derivative of PHP? Is PHP in turn derivative of OS?
Have you ever really explored WP code-base, do you understand why backwards compatibility is an issue, or it exists!
I am not particularly interested why, I am interested how to deal with it. And it is rarely a pleasant process.
I can assure that sloppy codes by theme and plugin devs have nothing to do with WordPress!
Yeah, how kind of you to decide for all of WordPress developers. Wait, you don’t.
When official WP documentation contains wonderful instructions like Meh, I’m not going to tell you now. there is no wonder developers screw up.
Are you still trying to present a valid argument against the GPL here… cause it is getting weaker with every response.
A blank text file… You can code without seeing any WordPress code??? I am not particularly interested why???
Devs are the ones that start with “blank txt files” and fill it with lousy code poor structure and redundant “functions” AKA frameworks…
I am sorry but how do you expect me to take your argument seriously!
@shawn sandy
There is not a single argument against GPL on this page. If you don’t understand that – read damn post and 29 comments after it.
I expected you to participate in logical discussion, but apparently repeatedly saying that you are right (and everyone else must be dumb to not understand that) works for you better.
I am taking you seriously (or at least try to). If you are not willing to spend even this much effort I will just stop replying to your comments, even if that is against how I run my blog.
This is quite an interesting series of comments. 2 sides having monologue; without giving credence to any facts presented by other side. I am not on either side, and have no take on the issue, but this is neither a discussion nor a debate; just 2 sides shouting out loud with their ears closed :)
@Ishan
Well… As I said above Matt didn’t really present any facts I wasn’t aware of. And speaking frankly ignored most of really interesting questions. I made my take on arguments of both sides very clear in the post, but that got largely ignored.
As usual.
It is so much more convenient and usual to try and twist me into stupid-person-who-hates-GPL-open-source-and-even-kittens rather than stick to what I really wrote in post.
It wasn’t my intention to have discussion under this post with Matt or at all. I merely had these thoughts boiling for some time and is there any more fitting place to put them in writing than my blog? :) Shouting is just collateral damage.
I find myself on the fence. I love WordPress, I use WordPress and I profit from WordPress. But, I have absolutely felt vilified with a bit of “elitist behavior towards me where opinion was shined on as fact” subtlety from mods, theme reviewers and WP programmers/developers that share a certain view.
It doesn’t anger me to the point of the same passion you have about it, but I get it and it’s frustrating, convoluted and certainly not ideal. I see both sides. I’ve contributed one theme and one plugin officially to WordPress totally for free, for fun, interest, experience and perhaps a little recognition/backlink love in return (for anyone to deny that would be a lie).
However, I recently ventured into premium theme territory that of course pushed me to do my research into GPL. When all I was doing was contributing for free it was easy going, but now that I’ve gone to premium there is definitely this weight of how dare I try and make money, the commercial evil has consumed me.
I don’t get this from the top, but from the people in the middle that perhaps haven’t been given a clear enough handbook into how they should treat WordPress’ users, designers, developers or people in general. When programmers wouldn’t work with me because my project was premium or my ideas of the project didn’t fit this WordPress’ unwritten ethical codes guideline I definitely felt this “I’m a bad guy.” attitude. Until I read this article, I thought I was the only one asking myself “What the hell, I’m a professional. I give a lot of stuff away for free, but I can’t work hard on something and then make a profit on it too?”
And then I read this and it really put things into perspective:
That’s the official gnu.org stance on the issue and seemingly the way WordPress also feels considering they have a commercial showcase of theme on their site itself.
So, I don’t think Matt is to blame or any other conglomerate of higher ups. I get the feeling that all the unpaid people that help out the WordPress project (the people who really run things) have sort of created their own idealism on how things should be. Here’s an analogy for you…
WordPress is like an island. Matt and the core team are sort of like guards that keep just enough pressure and explain just enough to appease the king (the law) and keep the people in order. And all the mods, theme reviewers, developers, designers, users, customers etc (“the community”) are all the people dropped onto this island.
They’re told just enough to stay in compliance and be allowed to stay on the island. But, for all pertinent info, nuances and in-between stuff they have to figure out for themselves. And without enough clarity from the guards they form all sorts of varying opinions and break off into groups. They know enough to appease the guards and the king, but they never learned how to all get along.
The bottom line is that wherever there are people, there’s trouble. Whether that be an island, a city or even an online community it is political, I can’t see how that could be argued. You make a very valid point.
Ironically, though I’m made to feel like a bad guy for earning a living, my ideals of how to give away for free or sale digital goods is way less restricting than even that of the GPL. All the code I write on my blog or software, website templates etc that I create, I don’t even want to restrict how people can or can’t use it at all, adding no license most of the time. But, because we live in such a litigious society people are scared. So I have to say that it’s public domain and they can safely use whatever it is, however they want.
My ideal would be no licenses at all. But, to play with WordPress is not a mutual friendship. WordPress is that one kid you played with growing up (you know the one). You benefit from one another’s company enough to still be their friend, but it’s not mutual. WordPress is the dominant friend. If you don’t agree with them or do the things they want to do they won’t play with you anymore, period.
So, although it’s interesting to discuss these issues and our opinions, they’re just that and no one cares and nothing is going to change.
Like I said, I’m on the fence, neither left or right. So my opinions are probably less popular than any.
Thanks, Bryan
@Bryan Hadaway
Note the post is from couple years ago, it was about peak of GPL wars. I think the interesting takeaway is that “every WP extension is derivative under GPL” was de facto (and silently) dropped since and official plugin repository demands merely GPL compatibility, not inheritance.
I disagree that the top folks had little to do with it. It were and remain their ideals that crowds adopted… and often blew out of proportion. It was their witch hunts and policies that educated people to go around and mess with people to “uphold” those ideals.
In the end my standing opinion on the licensing perception by WP higher circles – it’s a stick. Handy when you need to smack someone, boring and irrelevant rest of the time.
@Rarst – All the same, as a newcomer to premium theming, doing my GPL research lead me to your article. While being two years old, still holds true on many points as I experience them for the first time.
Many of those points being of non-GPL origin and more of this fear of breaking compliance undertone that is ever present in the “company”.
Right now I’m pondering GPLv2 vs GPLv3.
Thanks, Bryan
3 pingbacks
[...] data structures, and are executed as a single stream at runtime. " (see Rarst post comments) Additionally, I personally care about the issue because I want to release my code with a more [...]
[...] The WordPress community is pretty divided on the subject and really all over the might. I read an interesting article that shares some of my same views on the issue.My thoughts on what was said and GPL are as [...]
[...] Or we could be watching political drama for dramas sake, that has been going on for a long time, here’s an old blog post on the subject from the venerable Rarst: [...] | http://www.rarst.net/thoughts/wordpress-gpl/ | CC-MAIN-2014-35 | refinedweb | 8,415 | 70.43 |
I have a problem with reducing two rational numbers in the form a/b and need to recude them to form where a and b do not have any common integer dividers.
I tried something, but it didn't work. Here is the code:
It always gives me result 1/1. Where is the problem ? I really can't figure it out.It always gives me result 1/1. Where is the problem ? I really can't figure it out.Code:
#include <stdio.h>
int main()
{
int i, j, k;
int a, b;
scanf("%d/%d", &a, &b);
if(a > b) j = b;
else j = a;
for(i = j;i > 1; i--)
{
if(((a % j) == 0) && ((b % j) == 0)) { k = j; break; }
}
a = a / j;
b = b / j;
printf("%d/%d\n", a, b);
return 0;
}
Thanks in advance. | http://cboard.cprogramming.com/c-programming/114927-reducing-rational-numbers-code-not-working-properly-printable-thread.html | CC-MAIN-2014-15 | refinedweb | 139 | 93.03 |
Find the XOR of all the subarray XORs for an array of integers, where subarray XOR is achieved by XORing all of its members in the subarray.
Example 1:
With an input of
arr = [54, 3, 2, 1], we want to receive an output of
0
Example 2:
With an input of
arr = [3, 2, 1], we want to receive an output of
2
A simple solution is to find all the subarrays for the given array, find the XOR for each subarray, and finally, find the XOR of all subarray XORs.
The time complexity of this would be O(N3) and its space complexity would be O(1).
public class Main{ static int xorOfSubarrayXors(int[] arr){ int res = 0; for (int i = 0; i < arr.length; i++) for (int j = i; j < arr.length; j++) for (int k = i; k <= j; k++) res = res ^ arr[k]; return res; } public static void main(String[] args) { int[] arr = {3, 2, 1}; System.out.println("The XOR of all subarray xors is " + xorOfSubarrayXors(arr)); } }
Lines 3–12: We define the
xorOfSubarrayXors() method to find the XOR of all the subarray XORS. There are three nested loops in the method.
forloop,
for (int i = 0; i < arr.length; i++), is used as a starting point of the subarrays.
forloop,
for (int j = i; j < arr.length; j++), is used as the ending point of the subarrays.
forloop,
for (int k = i; k <= j; k++), is used to find the XOR of the subarray.
Line 15: We define an array
arr.
Line 16: We call the
xorOfSubarrayXors() method with
arr as the parameter.
RELATED TAGS
CONTRIBUTOR
View all Courses | https://www.educative.io/answers/how-to-find-the-xor-of-all-subarray-xors | CC-MAIN-2022-33 | refinedweb | 275 | 71.85 |
Though we have the fancy new ALIASEDVAR opcodes, they don't reach across function boundaries yet. Name ICs will let us optimize these accesses (and others) until the front-end is changed. When that happens (bug 753158), most of the really hot NAME ops will become ALIASEDVAR, but the name ICs will still be useful for eval-poisoned scopes.
This bug will should get us most of the way there for JSOP_NAME; bug 753158 will be an additional win since the steps emitted by the ICs will instead be inlined as MIR.
Created attachment 631246 [details] [diff] [review]
WIP v0
Benchmark:
var f = function (x, y) {
return (function () {
var t;
for (var i = 0; i < 10000000; i++)
t = y;
return t;
})();
}
Goes from 1054ms to 27ms. Yay!
Otherwise untested, test tomorrow.
Created attachment 632090 [details] [diff] [review]
a patch
Comment on attachment 632090 [details] [diff] [review]
a patch
Review of attachment 632090 [details] [diff] [review]:
-----------------------------------------------------------------
Looks good, r=me with comments addressed.
::: js/src/ion/IonCaches.cpp
@@ +1107,5 @@
> + if (!IsCacheableNonGlobalScope(obj2))
> + return false;
> +
> + // Stop once we hit the global or target obj.
> + if (obj2->isGlobal() || obj2 == obj)
IsCacheableNonGlobalScope will return |false| if obj2->isGlobal(). Do we need something like "&& !obj2->isGlobal()" there to allow global properties?
It would be good if we could somehow call IsCacheableScopeChain here if possible.
@@ +1138,5 @@
> +
> + if (cache.stubCount() < MAX_STUBS &&
> + IsCachableName(cx, scopeChain, obj, holder, prop))
> + {
> + if (!cache.attach(cx, scopeChain, obj, (Shape *)prop))
A cache.incrementStubCount(); here to avoid adding too many stubs. | https://bugzilla.mozilla.org/show_bug.cgi?id=762421 | CC-MAIN-2016-30 | refinedweb | 250 | 66.13 |
Hi Tom, > So is the general strategy with observable sharing to use > unsafePerformIO with Data.Unique to label expressions at > construction? something like that, yes. Basically, you just need: {-# NOINLINE ref #-} ref x = unsafePerformIO (newIORef x) and you can write expressions like ref False == ref False and let x = ref False in x == x However, while referential equality is enough for sharing detection, I *suspect* it's simpler to use the fact that refs are IORefs and you can read and write them (in the IO monad). So a very simple Lava might look like module Lava (Bit,Netlist,low,high,nand2,netlist) where import Data.IORef import System.IO.Unsafe {-# NOINLINE ref #-} ref x = unsafePerformIO (newIORef x) type Ref = IORef (Maybe Int) data Bit = Gate String Ref [Bit] type Netlist = [(String, Int, [Int])] -- gate, output, inputs low = Gate "low" (ref Nothing) [] high = Gate "high" (ref Nothing) [] nand2 (a, b) = Gate "nand2" (ref Nothing) [a, b] netlist :: Bit -> IO Netlist netlist x = do i <- newIORef (0 :: Int) ; f i x where f i (Gate str r xs) = do val <- readIORef r num <- readIORef i case val of Nothing -> do writeIORef r (Just num) writeIORef i (num+1) rest <- mapM (f i) xs let is = map ((\(g,o,is) -> o) . head) rest return ((str,num,is):concat rest) Just j -> return [("indirection",j,[])] -- explicit sharing! Indirections can be filtered out at the end, they don't actually give the netlist any information. > Of course, now that you have me reading up on Yhc.Core, option #5 is > looking considerably more fun. Yeah, I think Yhc.Core is pretty nifty too. Thank Neil! Matt. | http://www.haskell.org/pipermail/haskell-cafe/2008-February/039449.html | crawl-002 | refinedweb | 272 | 68.7 |
* Peter Zijlstra <a.p.zijlstra@chello.nl> wrote:> On Sat, 2008-09-27 at 20:10 +0200, Ingo Molnar wrote:> > * Chris Friesen <cfriesen@nortel.com> wrote:> > > > > --- a/kernel/sched.c> > > +++ b/kernel/sched.c> > > @@ -298,9 +298,9 @@ static DEFINE_PER_CPU(struct cfs_rq, init_cfs_rq) ____cacheline_aligned_in_smp;> > > static DEFINE_PER_CPU(struct sched_rt_entity, init_sched_rt_entity);> > > static DEFINE_PER_CPU(struct rt_rq, init_rt_rq) ____cacheline_aligned_in_smp;> > > #endif /* CONFIG_RT_GROUP_SCHED */> > > -#else /* !CONFIG_FAIR_GROUP_SCHED */> > > +#else /* !CONFIG_USER_SCHED */> > > #define root_task_group init_task_group> > > -#endif /* CONFIG_FAIR_GROUP_SCHED */> > > +#endif /* CONFIG_USER_SCHED */> > > > hm, these seem to be fixed already, via:> > > > | commit 9a7e0b180da21885988d47558671cf580279f9d6> > | Author: Peter Zijlstra <a.p.zijlstra@chello.nl>> > | Date: Tue Aug 19 12:33:06 2008 +0200> > |> > | sched: rt-bandwidth fixes> > > > is all in tip/master.> > > > (or is perhaps the direction of your patch wrong?)> > No I think he got it right, as I vaguely remember fixing it too - now > I know where I left it ;-)> > I often leave such trivial comment fixes in whatever patch I'm working > on at that moment.that's OK. The risk is of course that if the other bits of this commit break something, and we drop or revert the commit, we drop the cleanup as well. But the patch was perfect in this case so all is fine :-) Ingo | http://lkml.org/lkml/2008/9/27/167 | CC-MAIN-2013-20 | refinedweb | 195 | 54.83 |
A short demonstration of how to use OpenCV to capture and display video frames from an avi file. The code demonstrates how to capture video from an example video (avi) file, get information in the form of frames per sec. and display the video.
1. Some pre-requisites
i. Make sure OpenCV has been successfully installed on your machine. Here’s how.
ii. Before attempting any of this you will probably need to download and compile ffmpeg, a command line tool used for converting multimedia files between formats, most notably libavcodec. Here’s how.
2. Implementation
All that is needed to initiate the video capture is the
cvCaptureFromAVI:
CvCapture* capture = cvCaptureFromAVI("infile.avi");
And to grab individual frames we simply use
cvQueryFrame:
IplImage* frame = cvQueryFrame( capture );
cvGetCaptureProperty is used to return the frames per second so that we may control the speed at which individual frames get displayed.
Sample video output:
3. Code Listing
Here is the code listing used to display the sample video file, “SAMPLE.AVI“:
#include <cv.h> #include <cxcore.h> #include <highgui.h> int main() { int key = 0; // Initialize camera or OpenCV image //CvCapture* capture = cvCaptureFromCAM( 0 ); CvCapture* capture = cvCaptureFromAVI( "sample.avi" ); IplImage* frame = cvQueryFrame( capture ); // Check if ( !capture ) { fprintf( stderr, "Cannot open AVI!\n" ); return 1; } // Get the fps, needed to set the delay int fps = ( int )cvGetCaptureProperty( capture, CV_CAP_PROP_FPS ); // Create a window to display the video cvNamedWindow( "video", CV_WINDOW_AUTOSIZE ); while( key != 'x' ) { // get the image frame frame = cvQueryFrame( capture ); // exit if unsuccessful if( !frame ) break; // display current frame cvShowImage( "video", frame ); // exit if user presses 'x' key = cvWaitKey( 1000 / fps ); } // Tidy up cvDestroyWindow( "video" ); cvReleaseCapture( &capture ); return 0; }
4. Some caveats
Just to re-iterate, you may need to ensure that ffmpeg has been successfully installed in order to allow video encoding and video decoding in different formats. Not having the ffmpeg functionality may cause problems when trying to run this simple example and produce a compilation error like this:.
Also, please be advised that it is not possible to compile the sourcecode from ffmpeg in visual studio 2010.
5. If you still get problems
Try the various Windows builds for FFMPEG over at this website. For example, for a 64-bit PC running Windows 7 you may wish to try these builds. Download and extract the file, and insert a copy of the ffmpeg.exe file contained in the /bin subfolder inside the C++ project folder you are working on. This worked for me when I encountered simuilar difficulties.
Sample avi is downloadable from here.
Other posts related to image detection
Tracking Coloured Objects in Video using OpenCV
Analyzing FlyCapture2 Images obtained from Flea2 Cameras
Integrating the FlyCapture SDK for use with OpenCV
OpenCV Detection of Dark Objects Against Light Backgrounds
Getting Started with OpenCV in Visual Studio
Object Detection Using the OpenCV / cvBlobsLib Libraries
Hi!
excellent article and very usefull. I am working on a project displaying also avi files with opencv and I have two problems : I have no sound in the videos I display, and I am doing a certain image processing for each frame of the video and the video is being displaying very slowly. Do you now how can I improve any of those questions?
Sorry for my english :p | http://www.technical-recipes.com/2011/displaying-avi-video-using-opencv/?replytocom=964 | CC-MAIN-2017-30 | refinedweb | 542 | 55.24 |
About the Sensor
The BNO055 uses three triple-axis sensors to simultaneously measure tangential acceleration (via an accelerometer), rotational acceleration (via a gyroscope), and the strength of the local magnetic field (via a magnetometer). Data can then be either sent to an external microprocessor or analyzed inside the sensor with an M0+ microprocessor running a proprietary fusion algorithm. Users then have the option of requesting data from the sensor in a variety of formats.
The chip also has an interrupt that can notify the host microcontroller when certain motion has occurred (change in orientation, sudden acceleration, etc.).
Re-created block diagram from datasheet
The sensor must be calibrated prior to use and a read register holds the current calibration status. Once calibrated, the calibration offsets can be written to the sensor and then the sensor is immediately ready to use the next time it is powered on.
See the video below to learn how to calibrate your sensor.
UART Interface Handling Soldering Specifications Datasheet
A host microcontroller can request any or all of the data from the sensors (accelerometer, gyroscope, and/or magnetometer) in non-fusion mode and can request absolute and relative orientation (angles or quaternions) in fusion mode.
The sensor can return acceleration in m/s² or mg ($$1 mg=9.81\frac{m}{s^2}\times 10^{-3}$$); magnetic field strength in mT; gyroscope data in degrees or radians per second (DPS and RPS, respectively), Euler angles in degrees or radians, or quaternions; and temperature in °C or °F. All options are set in the unit_selection register (table 3-11 in the datasheet, PDF page 30).
Euler Angles vs. Quaternions
If you are designing a sensor solution for a system that has a limited range of motion, you can use Euler angles. But if you are designing a sensor that can be oriented anywhere in space, you should use quaternions.
Euler Angles
Euler angles allow for simple visualization of objects rotated three times around perpendicular axes (x-y-x, x-z-x, y-x-y, y-z-y, z-x-z, z-y-z, x-y-z, x-z-y, y-x-z, y-z-x, z-x-y, z-y-x).
x-y-z rotations from Wolfram.com
As long as the axes stay at least partially perpendicular, they are sufficient. However, as the axes rotate, an angle exists where two axes can describe the same rotation—creating a condition known as gimbal lock. When gimbal lock occurs, it is impossible to reorient without an external reference. See my article, Don't Get Lost in Deep Space: Understanding Quaternions, to learn more about gimbal lock.
This animation has three gimbals (shown as red, green, and blue solid cylinder segments) along with the available rotations (shown as red, green, and blue transparent spherical lunes). When the plane of the internal green gimbal aligns with the plane of the red gimbal, the axes of rotation of the red and blue gimbals overlap and gimbal lock occurs (indicated by a light-yellow background).
The problem of gimbal lock does not exist when using quaternions.
Quaternions
Quaternions were invented by William Hamilton in 1843 as a way to multiply and divide three numbers. They slowly fell out of favor over the course of many decades and saw a revitalization in the nuclear era and again with modern computer graphics programming. A quaternion consists of four numbers: a scalar and a three-component vector.
.
where w, x, y, and z are all real numbers and i, j, and k are quaternion units.
Typically, w, x, y, and z are kept in the range between -1 and 1, and $$\sqrt{w^2+x^2+y^2+z^2}=1$$.
These four numbers succinctly reorient vectors in a single rotation with or without changes in length.
The blue and red vectors are of unit length. The orange is the rotation required to rotate the blue vector into the red.
Normal transformation matrices consist of nine numbers and involve the application of trigonometric functions. Quaternions consist of four numbers, all less than or equal to one. It is possible to convert a quaternion to an orthogonal transformation matrix but, due to the mathematical properties associated with gimbal lock (again, see my quaternion article for more information), it is slightly more difficult to convert from rotation matrix to a quaternion.
Method of converting a quaternion to a 3x3 orthogonal rotation matrix.
The code snippets below demonstrate how to create a 3×3 transformation matrix and roll, pitch, and yaw angles from a quaternion.
/* Create Rotation Matrix rm from Quaternion */ double rm[3][3]; rm[1][1] = quat.w()*quat.w() + quat.x()*quat.x() - quat.y()*quat.y() - quat.z()*quat.z(); rm[1][2] = 2*quat.x()*quat.y() - 2*quat.w()*quat.z(); rm[1][3] = 2*quat.x()*quat.z() + 2*quat.w()*quat.y(); rm[2][1] = 2*quat.x()*quat.y() + 2*quat.w()*quat.z(); rm[2][2] = quat.w()*quat.w() - quat.x()*quat.x() + quat.y()*quat.y() - quat.z()*quat.z(); rm[2][3] = 2*quat.y()*quat.z() - 2*quat.w()*quat.x(); rm[3][1] = 2*quat.x()*quat.z() - 2*quat.w()*quat.y(); rm[3][2] = 2*quat.y()*quat.z() + 2*quat.w()*quat.x(); rm[3][3] = quat.w()*quat.w() - quat.x()*quat.x() - quat.y()*quat.y() + quat.z()*quat.z(); /* Display Rotation Matrix */ Serial.print(rm[1][1],5);Serial.print(" \t"); Serial.print(rm[1][2],5);Serial.print(" \t"); Serial.println(rm[1][3],5); Serial.print(rm[2][1],5);Serial.print(" \t"); Serial.print(rm[2][2],5);Serial.print(" \t"); Serial.println(rm[2][3],5); Serial.print(rm[3][1],5);Serial.print(" \t"); Serial.print(rm[3][2],5);Serial.print(" \t"); Serial.println(rm[3][3],5); /* Create Roll Pitch Yaw Angles from Quaternions */ double yy = quat.y() * quat.y(); // 2 Uses below double roll = atan2(2 * (quat.w() * quat.x() + quat.y() * quat.z()), 1 - 2*(quat.x() * quat.x() + yy)); double pitch = asin(2 * quat.w() * quat.y() - quat.x() * quat.z()); double yaw = atan2(2 * (quat.w() * quat.z() + quat.x() * quat.y()), 1 - 2*(yy+quat.z() * quat.z())); /* Convert Radians to Degrees */ float rollDeg = 57.2958 * roll; float pitchDeg = 57.2958 * pitch; float yawDeg = 57.2958 * yaw; /* Display Roll, Pitch, and Yaw in Radians and Degrees*/ Serial.print("Roll:"); Serial.print(roll,5); Serial.print(" Radians \t"); Serial.print(rollDeg,2); Serial.println(" Degrees"); Serial.print("Pitch:"); Serial.print(pitch,5); Serial.print(" Radians \t"); Serial.print(pitchDeg,2); Serial.println(" Degrees"); Serial.print("Yaw:"); Serial.print(yaw,5); Serial.print(" Radians \t"); Serial.print(yawDeg,2); Serial.println(" Degrees");
Interfacing the Sensor with Arduino
I purchased the BNO055 sensor affixed to a development board with support components from Adafruit. It is possible to save a bit of money by purchasing the BNO055 from Digi-Key or Mouser and soldering it to a 7.5×4.4mm 28-pin LGA to DIP converter for prototyping on a solderless breadboard. But for the marginal cost savings after shipping, I wouldn't recommend it.
To get started interfacing your BNO055 with an Arduino, follow these steps:
- Connect power, ground, SDA, and SCL
- Open the Arduino IDE and click on Sketch→Include Library→Manage Libraries
- Open and edit File→Examples→Adafruit BNO055→Raw Data to comment out the Euler angle section and uncomment the Quaternion section, or copy and paste the abridged code below.
#include <Wire.h> #include <Adafruit_Sensor.h> #include <Adafruit_BNO055.h> #include <utility/imumaths.h> /* This program is an abridged version of Adafruit BNO055 rawdata.ino available after installing the Adafruit BNO055 library File→Examples→Adafruit BNO055→Raw Data Connections on Arduino Uno ========================================================================= SCL to analog 5 | SDA to analog 4 | VDD to 3.3V DC | GND to common ground */ #define BNO055_SAMPLERATE_DELAY_MS (100) // Delay between data requests Adafruit_BNO055 bno = Adafruit_BNO055(); // Create sensor object bno based on Adafruit_BNO055 library void setup(void) { Serial.begin(115200); // Begin serial port communication if(!bno.begin()) // Initialize sensor communication { Serial.print("Ooops, no BNO055 detected ... Check your wiring or I2C ADDR!"); } delay(1000); bno.setExtCrystalUse(true); // Use the crystal on the development board } void loop(void) { imu::Quaternion quat = bno.getQuat(); // Request quaternion data from BNO055 Serial.print(quat.w(), 4); Serial.print("\t"); // Print quaternion w Serial.print(quat.x(), 4); Serial.print("\t"); // Print quaternion x Serial.print(quat.y(), 4); Serial.print("\t"); // Print quaternion y Serial.print(quat.z(), 4); Serial.println(); // Print quaternion z delay(BNO055_SAMPLERATE_DELAY_MS); // Pause before capturing new data }
The program simply communicates with the BNO055 over I²C and streams the data back to the computer over a UART port. Quaternion data is sent back as tab-separated data with newlines after each quaternion.
Keep in mind that until your sensor is calibrated, your data is not valid.
Sample Quaternion Data
For the following example, I requested quaternion data from the BNO055 as I placed it in a random orientation near my desk. You can interpret the data manually at WolframAlpha.com by entering it as comma separated values enclosed in parenthesis after the word quaternion (e.g., "Quaternion(0.403, 0.414, 0.085, 0.812)")
The numbers above are a quaternion that describes the current orientation of the sensor with respect to the reference orientation.
Image from WolframAlpha.com shows default and actual orientation of object
Image from WolframAlpha.com shows rotation axis and amount of rotation needed to reach the current position from the default position.
While it's certainly not necessary to look to the Internet to process your quaternion data, it is nice to have the option to double-check your work.
Capturing Data with Mathematica
Mathematica is a versatile computer program that can process almost any data you can imagine. For those interested, I put together a few lines of code that demonstrate how to receive data from a device and how to use Mathematica to evaluate the data with a few quaternion-based functions. The code below was written for Windows, so Linux and Mac users might have to change the input device line (the line that begins bConnect).
Screenshot of the Mathematica Notebook available via the download button below
Mathematica allows data to be collected and processed in real-time and after the fact. For this demonstration, I opted for a program that collects the data from the serial buffer, converts it to a rotation matrix, and uses the rotation matrix to reorient an arrow in a reference sphere.
Begin by clicking "Connect Arduino" and then "Data from Buffer." I didn't incorporate any data validation or error checking, so if the data area is blank or misformatted, the only option is to recollect the data.
Mathematica is capable of reading and working with data as it arrives over the serial port, but for this demonstration, the 30 or so measurements stored in the buffer should be sufficient to see how the program works.
Data sent from the BNO055 is analyzed in Mathematica and used to reorient an arrow in a reference sphere
Quaternion with Mathematica
Controlling a Two-Axis Gimbal
The BNO055 is well-suited for robotics use. As an example application, I'll use the BNO055 to control a laser mounted on a servo-based two-axis gimbal. The code should allow the seamless introduction of a third axis-of-rotation for any reader fortunate enough to have one.
Connect the BNO055 as before and add servos, connected to digital pins 9-11. If you're using the gimbals to hold a camera, consider upgrading to the Alorium XLR8 board. Servos rely on precise timing, and if the Arduino is processing competing tasks, it can lead to jitter. The XLR8 is a drop-in replacement of the Arduino made from an FPGA. It has a library that can control the servos from a separate "XLR8tor" (accelerator) block for steady and fluid servo movement.
Wiring overview of the circuit
Arduino Uno R3 replacements: XLR8 vs Sparkfun "Redboard" Arduino Uno R3
//---- Included Libraries ----// #include <Wire.h> // I²C library #include <math.h> // trig functions #include <Adafruit_Sensor.h> // Base library for sensors #include <Adafruit_BNO055.h> // BNO055 specific library #include <utility/imumaths.h> // Vector, Matrix, and IMUMath library //#include <servo.h> // Standard Servo library #include <XLR8Servo.h> // XLR8 servo library #include <XLR8Float.h> // XLR8 accelerated floating point math #define BNO055_SAMPLERATE_DELAY_MS (50) // Set pause between samples //---- Variable Declaration ----// boolean debug = true; // true/false = extra/no information over serial int rollPin = 9; // Digital pin for roll int yawPin = 10; // Digital pin for yaw int pitchPin = 11; // Digital pin for pitch float roll, pitch, yaw; // Variable to hold roll, pitch, yaw information Adafruit_BNO055 bno = Adafruit_BNO055(); // Use object bno to hold information Servo rollServo; // Create servo rollServo Servo pitchServo; // Create servo pitchServo Servo yawServo; // Create servo yawServo void setup(void) { rollServo.attach(rollPin); // The rollServo is connected at rollPin pitchServo.attach(pitchPin); // The pitchServo is connected at pitchPin yawServo.attach(yawPin); // The yawServo is connected at yawPin Serial.begin(115200); // Create serial connection at 115,000 Baud if (!bno.begin()) // Attempt communication with sensor { Serial.print("Ooops, no BNO055 detected ... Check your wiring or I2C ADDR!"); } delay(100); // Wait 0.1 seconds to allow it to initialize bno.setExtCrystalUse(true); // Tell sensor to use external crystal } //---- Main Program Loop ----// void loop() { //---- Request Euler Angles from Sensor ----// imu::Vector<3> euler = bno.getVector(Adafruit_BNO055::VECTOR_EULER); if (debug) { // If debug is true, send information over serial Serial.print("Measured Euler Roll-Pitch-Yaw"); Serial.print("\t yaw: "); Serial.print(euler.x()); Serial.print("\t"); Serial.print("\t pitch: "); Serial.print(euler.z()); Serial.print("\t"); Serial.print("\t roll: "); Serial.print(euler.y()); Serial.println(); } /* Remap information from the sensor over the 0° - 180° range of the servo The Yaw values are between 0° to +360° The Roll values are between -90° and +90° The Pitch values are between -180° and +180° */ int servoYaw = map(euler.x(), 0, 360, 0, 180); int servoRoll = map(euler.y(), -90, 90, 0, 180); int servoPitch = map(euler.z(), -180, 180, 0, 180); if (debug) { // If debug is true, send information over serial Serial.print("Measured Euler Roll-Pitch-Yaw"); Serial.print("\t Yaw Servo: "); Serial.print(servoYaw); Serial.print("\t"); Serial.print("\t Pitch Servo: "); Serial.print(servoPitch); Serial.print("\t"); Serial.print("\t Roll Servo: "); Serial.print(servoRoll); Serial.println(); } // If debug is true, send information over serial if (debug) { Serial.println("Calculated Servo Roll-Pitch-Yaw"); Serial.print("\t roll:"); Serial.print(servoRoll, DEC); Serial.print("\t"); Serial.print("\t pitch:"); Serial.print(servoPitch, DEC); Serial.print("\t"); Serial.print("\t yaw:"); Serial.print(servoYaw, DEC); Serial.println(); } rollServo.write(servoRoll); // Send mapped value to rollServo pitchServo.write(servoPitch); // Send mapped value to rollServo yawServo.write(servoYaw); // Send mapped value to rollServo delay(BNO055_SAMPLERATE_DELAY_MS); // Wait before rerunning loop }
Arduino Sketches for BNO055
Conclusion
The BNO055 is an easy-to-use inertial measurement unit that could be incorporated into a wide variety of applications, from robot stabilization (quadcopter, inverted pendulum, etc.) to camera stabilization and navigation (including dead reckoning).
Unlike other 9-DOF systems that output raw measurement data, the BNO055 filters and synthesizes data for a host microcontroller, thereby freeing up processor bandwidth and taking the guesswork out of programming.
Readers—if you would like to see a project or article that uses quaternions in greater depth, please let us know in the comment section below.
Featured image courtesy of Adafruit.
Give this project a try for yourself! Get the BOM.
14 CommentsLogin
Funny how this article show how good is this device but doesn’t show the complaint of people having drift over time and unstable calibration.
@Christian Bianchini 1,
Thanks for joining the site today, it’s always nice to get new members. From the tone of your comment, I assume you have the sensor and have difficulty in your application. What problem are you experiencing and in what application? (I assume that you wrote the calibration values to the registers rather than leaving it in a state of continuous calibration?).
Mark
Yes, please, I would like to see more examples of quaternion usage.
Hi @Neil Benson,
Thanks for joining AllAboutCircuits! Nice to have you aboard. Did you have a specific usage case in mind? And are you more interested in the theory (e.g. math), usage (code), or project? Finally, just in case you missed it last week—I wrote this behemoth of an article—
Anyhow, there’s certainly more to be said on the subject, let me know what you’re looking for and I’ll ask the editors for permission to do it.
Thanks,
Mark
Please tell me about the theory (math) of calculate the angle? I am doing a project using BNo055 to detect the angle, but confused about how to do it.
Hi @tanming,
First, take steps to calibrate the sensor according to the datasheet or the video in the article and write the calibration values to tot he sensor—working with an uncalibrated sensor will produce unreliable and sometimes contradictory results. Second—are you using quaternions or Euler Angles? Euler angles have some drawbacks, and quaternions can be difficult to understand—I did write an article about the two that provides an introduction to the subject:
Are you using pitch (-180,180), roll (-90,90), and yaw (0,360) to keep track of things, quaternions, or quaternions converted to pitch, roll, yaw? If you can explain a little more of what’s troubling you, I’ll do my best to help—although we might need to move this conversation to the forums where there is more room to type.
Thanks,
Mark
Hi
I have been using this sensor a lot lately. There are several problems that I want to get an idea from you.
1). When the sensor is fully calibrated, at its original position there is a reading (Yaw Pitch Roll), associated with the original position. After a long time of movement, I placed the sensor back to its original position, the Yaw could be off by some constant degree, 20 - 50 degree depending on the environment. Why this is happening? The sensor is always auto calibrate itself, but still I am expecting the reading at original position was more or less the same. Can you explain this and how to solve this.
2. Calibrate could be very painful and not stable, i.e. gyro, acc, and mag status are all 3, but sys indicates 0. Why is that?
Thanks
Hi @Mingming Zhang,
Glad you like the sensor—sorry you are having troubles.
The BNO055 doesn’t have an internal EEPROM to store calibration data—so every time that the sensor loses power, the calibration data disappears with it. Ideally, you would enter calibration mode just once (default at power-on), carefully go through the steps to calibrate the sensor (Datasheet page 47), and read the calibration data to store externally to non-volatile memory (EEPROM.) Then the next time the BNO055 is powered on, read the calibration profile from the EEPROM memory and send it to the BNO055. From the datasheet: “Once the sensor enters the internal calibration routine, the calibration profile is overwritten with the newly obtained sensor offsets and sensor radius.”
I suspect that your sensor is in a continuous state of calibration. How did that happen? Well provided that you are using the sample code I have posted above, the code that controls the mode of the device is hidden in the header files of the BNO055 library (Adafruit_BNO055.h, Adafruit_BNO055.cpp, Adafruit_Sensors.h, etc…)
Look for lines like this:
OPERATION_MODE_CONFIG = 0x00, ..., OPERATION_MODE_IMUPLUS - 0x08, etc…
and like this:
void Adafruit_BNO055::setMode(adafruit_bno055_opmode_t mode)
{
_mode = mode;
write8(BNO055_OPR_MODE_ADDR, _mode);
delay(30);
}
Also, there might be some stray magnetic fields near your work surface that are messing with things (ferrous-metal bolts, screws, worksurface, etc…)
So—to summarize—you should only have to calibrate once—once calibrated—get out of the config mode—otherwise the calibration data that you worked so hard to get will be continuously overwritten—resulting in a sensor that gives wildly inaccurate readings.
Does that make sense? Do you need additional assistance? If so, please create a post in the forum and ping me and I’ll try to assist you more.
Thanks,
Mark
Hey Mark, I just started playing with the Adafruit BNO055 and your article is clearing up a lot on how to get started.
In your code you haven’t used the setMode method that you mention in this comment. Why is that? If I am understanding correctly, I should calibrate my sensor, save the offsets to the EEPROM, and then each time the sensor boots up, the sensor is in config mode by default. While it is here, I should read the offset values from EEPROM, set them to the sensor and then change the mode using the setMode method. Is that right?
Hi @Oscar Salgado,
Hi Oscar—you don’t see any setMode in my functions because I am not switching into and out of a calibration state. When I wrote this article, I only used the BNO055 once and only carefully calibrated the sensor once, and since I kept the sensor powered on while I made the other sketches, I didn’t worry about it again or frankly even think about it again. In retrospect, I wish I had written the article to include more about the calibration offsets and radius and included a software routine and schematics that included an integrated external EEPROM, as this article has attracted quite a few confused makers—so sorry about that.
You have to calibrate the device—the sketches in the adafruit example library provide a calibration status (0 is not calibrated, 3 is calibrated, 1 and 2 are somewhere in between). Once you get to level 3, the device is calibrated. You can read the data from the registers while the operation mode is CONFIG_MODE.
Perhaps include a switch/button on your board that you press (or do it automatically with code at startup) that does the following steps listed on page 48 of the datasheet (once calibrated).
1) Change operation mode to CONFIG_MODE
2) Write the sensor offsets and radius data
3) Change to fusion mode.
If you go to you’ll see a sketch that does this.
I hope this helps—if you need further assistance, please create a post in the forums and ping me and I will try to assist you. This is the maximum comment depth and you will not be able to reply to my post, however, you should still be able to reply to the original article.
Hi all,
I am also playing with the BNO055 since a few days. And despite of all data sheet reading and reading of the comments above I am still confused about the auto calibration of the device. In the last comment Mark recommends the steps listed on page 48 in the datasheet. After loading the previousely stored cal data we change from CONFIG to FUSION mode. But what happens? The autocal in the background starts to run…. and the problems come up. There is footnote (5) on page 48 saying that the permanent background calibration can not be disabled.
So what is my problem?
I run the BNO55 in car to measure the horizontal acceleration, preferably without the influence of the gravity vector. I switch on IMU mode, do the cal steps as recommended, wait for the cal status bits to report 03 for the gyroscope and 03 for the acc sensor. The sensor is now mounted in a perpendicular manner on the dashboard and I compare the raw accel data in driving direction and the linear accel that the fusion algorithm reports. I expect the linear accel to be free of influence of road inclination and vehicle pitching. But what happens when I moderately accelerate and brake the vehicle? The raw accel is what I expect from the speed increase/decrease. The fusion accel follows the expected output for 1 or 2 seconds but approaches zero after a few seconds although the vehicle is still accelerating or braking constantly. The vehicle acceleration/deceleration is nearly constant. I can easily derive this from a straight speed trace going up up or down. I guess that the permanent recalibration cancels my moderate acceleration to zero. For one or two seconds the linear accel looks realistic, thereafter it is definitely wrong, while the raw accel data is realistic.
Isn’t there a chance to disable the internal recal for a while?
I havn’t found any details about the autocal procedure that Bosch implemented. There is a nice video showing how simple one can calibrate the sensor. The video is like a hocus-pocus… but no in-depth information. The user is left alone in the end.
Mark, can you tell me what I need to know?
@Freddy4711,
When I wrote this article, my interest with the BNO055 lied primarily with the quaternion information, so I did not do a full implementation with custom code. I used a library that was already available. Had I known at the time how vexing this little device was for so many users, I would have gone in a completely different direction and focused on the sensor implementation rather than dealing with the data.
Here’s are my recommendations:
1) If all you’re doing is looking at acceleration data, don’t recalibrate at all. See this quick-start guide.
The accelerometer should be factory calibrated. Calibration is necessary for the magnetometer and the gyroscope (the gyro will drift relentlessly and requires the magnetometer data to be useful)
2) Get an I2C EEPROM and use it to store your calibration data. Park your car and turn off the engine, go through all of the calibration “hocus-pocus” with the BNO055 where it will be mounted in your car. Then read the BNO055 calibration registers and write them to the I2C EEPROM. Anytime you power-on the BNO055 from that point forward, you should be able to simply read the data from the EEPROM and write it to the BNO055.
3) Don’t use Fusion mode if all you’re trying to do is get acceleration data. If I remember correctly, the fusion modes force the continuous calibration. You just need acceleration—so get a non-fusion mode running that provides acceleration.
4) You cannot ignore vehicle and road pitch. The acceleration due to your car and the acceleration due to gravity are identical to an accelerometer. While I wouldn’t expect this to be too significant, it will affect your results. You should be able to deal with this in programming though (For example, if the sensor is perfectly level and the acceleration of the car is only in the x direction, any readings in the z directions would indicate a pitching sensor, and a reading in the y direction would indicate a yaw)
If you could, please create a forum post for further questions and ping me so I can help out there. It’s very difficult to deal with questions inside the limitations of a comment box.
Best,
Mark
Does calibration depends on tthe envirement? Do I need to calibrate it when I cahnge the envirement? Do I need to cailbrate the device every time I use, or once at the first usage of the devide?
The magnetometer calibration will depend on the environment and the proximity to ferromagnetic materials. But there is no eeprom in the BNO055 to store the calibration offsets. So you need to either recalibrate each time it’s turned on, or you need to store the calibration data in non-volatile memory and load it up each time it is powered on. | https://www.allaboutcircuits.com/projects/bosch-absolute-orientation-sensor-bno055/ | CC-MAIN-2019-13 | refinedweb | 4,641 | 56.35 |
span8
span4
span8
span4
I really don't know if this is something that FME can do, but it has done a lot of things so far so just seeing if this might be possible!
I have a directory of 'D:\data' which has many folders containing data from map layers (D:\data\parks, D:\data\buildings, D:\data\rivers etc).
What I am trying to do is automate the deletion of the contents of these sub-folders (which include both files and more folders), except any folders within 'data' that start with the name 'raster' (for instance I don't want to delete D:\data\raster_aerial2016 and all of its contents).
Is this something that FME Desktop can do? I don't have experience in python / batch files and FME has solved many problems so just wondering if there are any transformers that can help me out?
Nice question. Of course - and I know I'm stating the obvious - you'll be sure to test your chosen technique (including mine) before letting it loose on your real data. I'd hate to be the cause of your entire filesystem going up in smoke!
My thought is that you could use the "Directory and File Pathnames" reader to read a list of files, use a Tester to drop all those that contain the word 'raster' and then use the "File/Copy" writer to move the remaining files to the /dev/null equivalent for your operating system.
Attached is a workspace that shows the technique. It searches for txt files in C:\FMEOutput and moves it to "nul" in another folder. Windows doesn't allow a file called "nul", so it is deleted.
Hope this helps.
Awesome thanks Mark!
I find the SystemCaller transformer referenced above by jeroenstiers to be great for file system operations: if you can do it in a CMD window, you can do it in FME!
Hi,
Yes, copying the required files to another folder like E:\Data to E:\Data1 with filecopy writer and delete the folder E:\Data in normal windows is the best option.
Pratap
Hi @cartochris,
I created a small example of workspace you can use for this functionality. It does make use of a small python-script that lists all folders in the parent DATA-folder. It loops through this list and to check the name of every folder. If the folder doesn't start with 'raster', a feature is created (with the url of the folder) and send to a SystemCaller that will use the path and the RMDIR "PATH_TO_FOLDER" \S \Q command to remove it and all files / folders inside it automatically.
You might want to remove the \Q in the statement above so you will have to confirm before removing a folder.
I don't think I have to specify how dangerous this code can be if the parent-folder is pointing to a drive... So take watch out with the use!
The PythonCode:
import fme import fmeobjects import glob class RemoveData(object): def __init__(self): self.parentUrl = 'D:/DATA/' def input(self,feature): # Don't do anything for every feature entering pass def close(self): # List all folders in the parentfolder (self.parentUrl) folders = glob.glob('{}{}'.format(self.parentUrl, '*') ) # Loop throught all returned folders for cFolder in folders: # Check if the name starts with 'raster' if cFolder.split('\\')[1][0:6] == 'raster': # Skip this folder continue # Create feature, add attribute, and send it to workspace newFeature = fmeobjects.FMEFeature() # Convert the slashes to windows-notation newFeature.setAttribute('url', '"{}"'.format(cFolder.replace('\\\\', '\\').replace('/', '\\'))) self.pyoutput(newFeature)
example-removingallsubfolders.fmw
Hopefully this helps you!
Jeroen
Hi @cartochris, as far as I know, there is no way to remove files unless you write a script. However, I think you can copy or move only files which are saved under the "D:\data\raster_*" folder to a backup folder in the disk system using the Directory and File Pathnames Reader and File Copy Writer. Once you created the backup, it's easy to remove remnant files manually.
I don't think moving files in the same disk drive takes so long time, since it is equivalent to renaming. However, I didn't know that moving a file to 'null' works to delete it. It would be a good tip as @Mark2AtSafe suggested.
Anyway, be careful not to delete necessary files. I always create a backup for safe before cleaning up a folder, even if it could take a long time.
Answers Answers and Comments
10 People are following this question.
How to write a file for each distinct value? 3 Answers
Send messages to terminal when batch processing from command line 1 Answer
Batch deploy disabled 1 Answer
Batch deploy issue 3 Answers
Creating new sub folders when outputting data ? 1 Answer | https://knowledge.safe.com/questions/28084/delete-files-and-sub-folders-from-folders-not-star.html | CC-MAIN-2019-51 | refinedweb | 799 | 69.62 |
Future versions of Scala will be equipped with a new language feature called literal types. Originally only available in Dotty, Miles Sabin went at great lengths to implement this feature in Typelevel Scala and in mainline Scala. His pull request was recently merged, whereby literal types will officially become part of Scala 2.13, expected to be released in spring 2018.
This article is a case study of literal types, inspired from our experience with Pine which is a functional library for HTML/XML. To aid adoption, we decided to migrate our code base to it and were pleasantly surprised by the results. Although IDE support for literal types is still spotty, I figured it is a feature many users can already benefit from. This article explains how literal types can help improve the expressiveness of your code and reduce boilerplate.
Literal Types
I will start with a couple of basic examples to get some intuition of what a singleton type is. To run those examples, I recommend Typelevel Scala's REPL which itself is based on Ammonite:
% curl -s | bash @ repl.compiler.settings.YliteralTypes.value = true
Alternatively, follow the sbt instructions here. Note that it is possible to use Typelevel Scala with support for multiple platforms (JVM, JavaScript and LLVM) and versions (2.11, 2.12).
With literal types enabled, any literal like a string, integer, boolean etc. now becomes a valid type:
@ 42: 42 res1: Int = 42 @ 42: 41 cmd2.sc:1: type mismatch; found : Int(42) required: 41 val res2 = 42: 41 ^ Compilation Failed
As the result shows,
42 continues to be an integer, but it also has a more concrete type which is
42.
A concrete example where this could be a useful property is a function that should only take a particular string:
def f(value: "a"): Unit = {} f("a") // Works f("b") // Fails
If you would like to create an immutable variable (
val) from a literal value, you will find that the literal type is not retained:
val str = "hello" str: "hello" // Fails
The solution is to use the
final modifier:
final val str = "hello" str: "hello" // Works
Another useful property is that literal values inherit from
Singleton:
"hello": Singleton // Works "hello": Singleton with String // Works
We can use this property to constrain a type parameter. For example, we may want to create a list of literal values where every list item is equivalent:
class SingletonList[T <: Singleton](values: List[T]) new SingletonList(List(1, 1)) // Works new SingletonList(List(1, 2)) // Fails
We can further narrow down the type of the singleton values. In the following example, we only allow string literals:
class StringSingletonList[T <: Singleton](values: List[T with String]) new StringSingletonList(List("a", "a")) // Works new StringSingletonList(List(1, 1)) // Fails
Note that the following will not work due to this issue:
class StringSingletonList[T <: Singleton with String](values: List[T])
Another useful feature is the
ValueOf implicit. It allows us to retrieve the value of a literal:
def text[T <: Singleton with String](implicit vo: ValueOf[T]): String = vo.value text["test"] // "test"
Strongly-typed ASTs
Now, we will look at a common example: defining a strongly-typed Abstract Syntax Tree (AST). As an example, we will consider HTML. As it is a constantly evolving standard with many extensions, any modeling effort is prone to fail. Let us look at a solution that strives for maximum type safety:
sealed trait Node object Node { case class Text(text: String) extends Node abstract class Tag(val name : String, val children : List[Node], val attributes: Map[String, String]) extends Node { type Self <: Tag def update(children : List[Node], attributes: Map[String, String]): Self def attr(name: String): Option[String] = attributes.get(name) def attr(name: String, value: String): Self = update(children, attributes + (name -> value)) } } object Html { case class A(children : List[Node] = List.empty, attributes: Map[String, String] = Map.empty ) extends Node.Tag("a", children, attributes) { override type Self = A override def update(children : List[Node], attributes: Map[String, String]): Self = copy(children, attributes) def href: Option[String] = attr("href") def href(value: String): Self = attr("href", value) } }
As you can see, there is a fair amount of boilerplate in defining a new tag type. We always need to define the
case class parameters, override
Self and define
update.
On the upside, you can now conveniently instantiate an
<a> node:
val node = Html.A().href("") // : Html.A
Since we used call site type polymorphism,
href returns back an
Html.A object instead of
Tag. If we define more attributes and call them in a chain, we will retain the original type in the end.
By design, there is no other way to instantiate the same node given that
Tag is
abstract: A function taking a
Tag.Script cannot be called with a
Tag.A argument. This gives us additional type safety, but if you wanted to construct a tag dynamically, you would need a
match that is aware of all the available classes and then performs a dynamic dispatch:
def create(name : String, children : List[Node], attributes: Map[String, String]): Node.Tag = name match { case "a" => Html.A(children, attributes) ... }
Unfortunately, such a solution is far from extensible. Adding custom tags will require to either change
create() or to define a custom function.
To summarise, there are two issues with this approach:
- Boilerplate: For better type safety, we need to repeat a few definitions for each tag that we want to define.
- Extensibility: For each unsupported tag, we need to create a separate class and define a function that performs dynamic dispatch.
A possible solution using literal types
Instead of introducing separate classes for tags, we will restrict ourselves to only one with the key difference that the tag name becomes a literal type. This allows us to greatly simplify our earlier solution:
sealed trait Node object Node { case class Text(text: String) extends Node case class Tag[T <: Singleton]( name : T with String, children : List[Node] = List.empty, attributes: Map[String, String] = Map.empty ) extends Node { def attr(name: String): Option[String] = attributes.get(name) def attr(name: String, value: String) = copy(attributes = attributes + (name -> value)) def as[U <: Singleton with String]( implicit vo: ValueOf[U] ): Tag[U] = { assert(name == vo.value) this.asInstanceOf[Tag[U]] } } } object Html { type A = Node.Tag["a"] val A = Node.Tag("a") type B = Node.Tag["b"] val B = Node.Tag("b") }
Now we can write:
Html.A.attr("href", "") // : Node.Tag["a"] = Tag("a", List(), Map("href" -> ""))
Since the tag name is encoded in every
Tag instance as a type parameter, we retain the type safety from our earlier example that used sub-typing:
def renderNode(n: Html.A): String = "" renderNode(Html.A) // Works renderNode(Html.B) // Fails
Since
Html.A is just an alias for
Node.Tag("a"), we do not need the dynamic dispatch anymore and can instantiate nodes without any overhead. A side-effect is that our literal-based solution is more extensible:
val customTag = Node.Tag("custom-tag")
In the definition of
Tag, we used the
ValueOf type class for implementing a safe runtime cast. It can be used as follows:
val dynamicTagName: String = "a" val tag = Node.Tag(dynamicTagName) // : Node.Tag[dynamicTagName.type] tag.as["a"] // : Node.Tag["a"] tag.as["b"] // Fails
One last thing which the solution above left out were attributes. Earlier, we defined two
href functions on the
A object. This is obviously not possible anymore, but Scala offers a convenient alternative: implicits. Those can be used in conjunction with singleton types.
implicit class AttributesA(node: Html.A) { def href: Option[String] = node.attr("href") def href(value: String): Html.A = node.attr("href", value) } val node = Html.A.href("")
Let us revisit the two problems we identified with the inheritance-based approach and see how literal types compare:
- Boilerplate: Defining a new tag merely consists of creating a
typeand a
def, as well as an
implicit classfor the attributes. The boilerplate code has been reduced to a minimum.
- Extensibility: We do not have to define a separate class for each tag. Tags can now be instantiated directly without the need for dynamic dispatch.
IDE support
In the beginning, I mentioned IDE support as problematic. One reason we defined the type alias
A is better IDE support:
"a" is not recognised as a valid type yet by IntelliJ. Another issue currently is that implicits are not resolved properly.
Summary
We have seen how literal types clearly outperform an approach based on sub-typing. I hope I piqued your interest in trying out literal types yourself. If you would like to learn more about literal types, please refer to the official documentation.
How do you plan to use literal types in your projects? Let me know below in the comments.
Originally published on sparse.tech | https://functional.works-hub.com/learn/literal-types-a-case-study-586ae | CC-MAIN-2019-51 | refinedweb | 1,468 | 54.83 |
WebSockets in Django 3.1
Together.
Introduction into WebSockets ASGI interface
ASGI is a replacement protocol to good-old WSGI protocol that served us for years and it will become a de-facto standard in Python web frameworks in the next 2–3 years.
So, how does WebSocket work in this context? Let us find it!
The communication between WebSocket clients and your application is event-based. The ASGI specification defines two types of events: send and receive.
Receive events. These are events that clients send to your application. Let's look at them:
websocket.connectis sent when the client tries to establish a connection with our application
websocket.receiveis sent when the client sends data to our app
websocket.disconnecttells us that the client has disconnected.
Send events are emitted by our application to a client (e.g. a browser). Here is a list of them:
websocket.accept— we send this event back to the client if we want to allow the connection
websocket.send— with this event, we push data to the client
websocket.closeis emitted by the application when we want to abort the connection.
Now, as we know all participants of that party, it is the time to speak about their order.
When a browser opens a connection, the ASGI protocol server (we will talk about this later) sends us
websocket.connect event. Our application must respond to it with either
websocket.accept or
websocket.close according to our logic. It is simple: emit
websocket.accept if you allow the connection or emit
websocket.close to cancel the connection. You may want to cancel the connection, for example, if the user has no permissions to connect or is not logged in. I will assume that you allow the connection in the next steps.
After you accepted the connection, the application is ready to send and receive data via that socket using
websocket.send and
websocket.receive events.
Finally, when the browser leaves your page or refreshes it, a
websocket.disconnect is sent to the application. As a developer, you still have control over the connection and can abort the connection by sending
websocket.close event at any time you wish.
This was a brief description of how ASGI processes WebSockets. It is not scoped to Django, it works for any other ASGI compatible web framework like Starlette or FastAPI.
Setting up Django apps
In this tutorial, I am not going to cover Django installation and setup topics. Also, I assume that you have Django installed and operating.
First, we have to create a new Django application. This app will keep the custom URL pattern function, ASGI middleware, and WebSocket connection class.
Let's make a new app using this command:
django-admin startapp websocket
Okay, now let's make a new little helper function for developer convenience. This function will be a simple alias for
path function at the moment.
Add
urls.py to the
websocket app with this content:
from django.urls import pathwebsocket = path
Now you can configure WebSocket URLs in a distinct way. Time to create your first WebSocket view! To keep things simple and reusable we will make another Django app named, say, `users`. Don’t forget to enable both applications in the
INSTALLED_APPS setting!
django-admin startapp users
Implementing ASGI middleware
The middleware will be our glue code between WebSockets and asynchronous views provided by Django. The middleware will intercept WebSocket requests and will dispatch them separately from the Django default request handler. When you created a new Django project, the installed has added a new file named
asgi.py to the project installation directory. You will find the ASGI application in it. This is the application we are going to use instead of one defined in
wsgi.py.
Create a new
websocket/middleware.py file and put the code in it:
Every ASGI middleware is a callable that accepts another callable. In the middleware, we test if the request type is
websocket , and if so, we call Django’s URL resolver for a dispatchable view function. By the way, a 404 error will be raised if the resolver fails to find a view matching the URL.
Now, open
project_name/asgi.py file and wrap default application with this middleware:
from django.core.asgi import get_asgi_application
from websocket.middleware import websocketsos.environ.setdefault("DJANGO_SETTINGS_MODULE", "project_name.settings")django.setup()
application = get_asgi_application()
application = websockets(application)
Since that moment, every request made will be caught by our middleware and tested for its type. If the type is
websocket then the middleware will try to resolve and call a view function.
Don’t mind at the moment about missing import from the
.connection module. We are about to make it in a minute.
Add WebSocket connection
The role of the WebSocket connection is similar to the request object you use in your views. The connection will encapsulate request information along with methods that assist you in receiving and sending the data. This connection will be passed as the first argument of our WebSocket view functions.
Create
websocket/connection.py with the contents from the gist below. To make life easier we will also enumerate all possible WebSocket events in classes, add
Headers class to access request headers, and
QueryParams to get variables from a query string.
Add your first WebSocket view
Our project is set up to handle WebSocket connections. The only thing left is a WebSocket view function. We would also need a template view to serve an HTML page.
# users/views.pyfrom django.views.generic.base import TemplateViewclass IndexView(TemplateView):
template_name = "index.html"
async def websocket_view(socket):
await socket.accept()
await socket.send_text('hello')
await socket.close()
Mount both views in the root
urls.py
# project_name/urls.pyfrom django.urls import path
from websocket.urls import websocket
from users import viewsurlpatterns = [
path("", views.IndexView.as_view()),
websocket("ws/", views.websocket_view),
]
users/templates/index.html should contain this script:
<script>
new WebSocket('ws://localhost:8000/ws/');
</script>
This is a bare minimum to establish a WebSocket connection.
Start the development server
The Django’s
runserver command does not use application defined in
asgi.py at the time of writing this post. We need to use a 3rd-party application server. I will use Uvicorn.
pip install uvicorn
Once installed start the server passing ASGI application as the first positional argument:
uvicorn project_name.asgi:application --reload --debug
Navigate to, open browser’s console, switch to Network tab and observe the WebSockets working.
Echo server
The WebSocket view we created is useless. It sends one message and then closes the connection. We will refactor it in a simple echo server that replies to a client using the incoming message text.
Replace
websocket_view in
users/views.py with this code:
async def websocket_view(socket: WebSocket):
await socket.accept() while True:
message = await socket.receive_text()
await socket.send_text(message)
and replace contents of
users/templates/index.html with this:
<script>
let socket = new WebSocket('ws://localhost:8000/ws/');
let timer = null;socket.onopen = () => {
timer = setInterval(() => {
socket.send('hello');
}, 1000);
};socket.onclose = socket.onerror = () => {
clearInterval(timer);
};
</script>
The updated code will send
hello text to our application every one second and our application will respond to it with the same message.
Conclusion
In this post, I demonstrated how to add WebSocket support to your Django project using only Django 3.1 and the standard python library. Yes, I know that Uvicorn still needs to be installed but this is a limitation of the Django dev server at the moment. | https://alex-oleshkevich.medium.com/websockets-in-django-3-1-73de70c5c1ba?readmore=1&source=---------0---------------------------- | CC-MAIN-2021-17 | refinedweb | 1,249 | 51.55 |
Hey, im using an MSGEQ7 IC to receive audio inputs and display the 63Hz frequency on an WS2812B addressable LED strip. Though i am receiving my inputs fine and my circuits work, i just wanted to know if i could have some help when it comes to timing for receiving the values from my IC. My main goal is to have the LED strip react to music and it works but it is not quite as responsive as i would like it to be. That and some LEDs stay on when the LEDs need to turn off from top to bottom when there are no frequencies being received in the 63Hz range or no music is playing. I know this happens because of the delays in my audioRead() function, and i know to avoid this I would need to use millis() or micros() for timing, but im struggling with actually implementing it. I struggle with understanding how to keep the timing tight and accurate. In my code you can see my attempt at trying to use micros() to make an equivalent piece of code in the audioRead() function. I’m using the FastLED library for this project too. Thanks in advance!
My code below:
#include <FastLED.h> #define NUM_LEDS 144 #define DATA_PIN 9 #define RESET 6 #define STROBE 5 #define AUDIOPIN A0 int i = 0; int col = 0; int inputArray[7]; int led63hz = 0; int downMillis(); unsigned long currentMicros = 0; unsigned long previousMicros = 0; unsigned long holdMicros = 0; int downcount = 15; //for IC data int p1 = LOW; int p2 = LOW; int p3 = LOW; int p4 = LOW; int start = HIGH; //Code for LED strip functionality CRGB leds[NUM_LEDS]; void setup() { // put your setup code here, to run once: //IC related pin setup pinMode(RESET, OUTPUT); pinMode(STROBE, OUTPUT); pinMode(AUDIOPIN, INPUT); //LED related pin setup pinMode(DATA_PIN, OUTPUT); FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS); FastLED.setMaxPowerInVoltsAndMilliamps(5, 700); FastLED.setBrightness(50); //Serial Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: currentMicros = micros(); //Function to read analog values from IC MSQEQ7 audioRead(); //Function(s) to control LEDs based on Frequency band mapFunction(); lightUp(); //63HzLightDown(); if ((currentMicros - previousMicros) > 500) { leds[downcount].setRGB(0, 0, 0); if (downcount < 0) { downcount = 15; } downcount--; } } //Function to Read Analog Values void audioRead() { digitalWrite(RESET, HIGH); digitalWrite(RESET, LOW); delayMicroseconds(75); for (int i = 0; i < 7; i++) { digitalWrite(STROBE, LOW); delayMicroseconds(40); inputArray[i] = analogRead(AUDIOPIN); //Serial.print("\nThis is box "); //Serial.print(i); //Serial.print(":"); //Serial.print(inputArray[i]); // Serial.print("\n"); digitalWrite(STROBE, HIGH); delayMicroseconds(40); } //My attempt at re-implementing the code above: /* if(start == HIGH) { digitalWrite(RESET, HIGH); digitalWrite(RESET, LOW); start == LOW; p1 = HIGH; } //make p1 low at start else if( ( (micros() - currentMicros >= 0.075) && p1 == HIGH) || ( (micros() - holdMicros >= 0.04) && (micros() - holdMicros <= 0.075) ) ) { digitalWrite(STROBE, LOW); p2 = HIGH; p1 = LOW; } else if( (micros() - currentMicros >= 0.04) && p2 == HIGH) { inputArray[i] = analogRead(AUDIOPIN); digitalWrite(STROBE, HIGH); p2 = LOW; p3 = HIGH; } else if( (micros() - currentMicros >= 0.04) && p3 == HIGH) { if (i >= 6) { i = 0; p1 = LOW; p2 = LOW; p3 = LOW; p4 = LOW; start = HIGH; } i++; holdMicros = micros(); } */ } //Dont really need this down here, just for my understanding's sake; void mapFunction() { //Or we could use a map led63hz = map(inputArray[0], 0, 1023, 0, 14); //downcount = led63hz; } void lightUp() { fill_solid(leds, led63hz, CRGB(0, 210, 100)); FastLED.show(); } //END OF PRGRAM | https://forum.arduino.cc/t/msgeq7-ic-input-timing/660917 | CC-MAIN-2022-33 | refinedweb | 564 | 50.16 |
Updated May 18, 2018
You’ve got a React app, and an API server written in Express or something else. Now – how do you deploy them both to a server?
There are a few ways to do this:
- Keep them together – Express and React files sit on the same machine, and Express does double duty: it serves the React files, and it also serves
This article will cover how to keep them together. We’ll build the Express server to serve React’s static files in addition to providing an API, and then deploy it to Heroku. Heroku is easy to deploy to and free to get started with.
Make a Heroku Account
If you don’t have one already, go here and sign up. It’s free.
Install Heroku Toolbelt
Heroku comes with a commandline command they call a “toolbelt.” Follow the instructions here to install it. (On a Mac with Homebrew, just
brew install heroku).
The App
We’ll build a password generator. Every time you load the app or click Get More you’ll get 5 random paswords.
Just a quick disclaimer: this is just meant as a demo! I don’t recommend using some random internet thing that generates passwords on the server to generate your own real passwords ;)
Create the Express App
Make a parent directory to contain everything. Call it
rando or whatever you want.
$ mkdir rando; cd rando
Initialize the project with Yarn or NPM:
$ yarn init -y # or npm init -y
We need 2 packages: Express itself, and a password generator. Install those now:
$ yarn add express password-generator
Create a file called
index.js, which will be the Express app, and type this in:
const express = require('express'); const path = require('path'); const generatePassword = require('password-generator'); const app = express(); // Serve static files from the React app app.use(express.static(path.join(__dirname, 'client/build'))); // Put all API endpoints under '/api' app.get('/api/passwords', (req, res) => { const count = 5; // Generate some passwords const passwords = Array.from(Array(count).keys()).map(i => generatePassword(12, false) ) // Return them as json res.json(passwords); console.log(`Sent ${count} passwords`); }); // The "catchall" handler: for any request that doesn't // match one above, send back React's index.html file. app.get('*', (req, res) => { res.sendFile(path.join(__dirname+'/client/build/index.html')); }); const port = process.env.PORT || 5000; app.listen(port); console.log(`Password generator listening on ${port}`);
We’re also going to need a “start” script in package.json, so that Heroku knows how to start the app. Open
package.json and add a scripts section at the bottom. The full file should look something like this:
{ "name": "rando", "version": "1.0.0", "main": "index.js", "license": "MIT", "dependencies": { "express": "^4.15.3", "password-generator": "^2.1.0" }, "scripts": { "start": "node index.js" } }
Test It
It’s always good to make sure things are working as you go along. Much better than getting to the end and realizing nothing works. So, let’s try it out.
Start up the Express app by running:
$ yarn start
Open up your browser and go to. You should see something like this:
Set Up Heroku
Now we’ll deploy the app to Heroku, make sure it works, and then we’ll add React to the mix.
Git Init
Heroku needs your project to have a Git repository, so we’ll create one along with a
.gitignore file to ignore node_modules, and then commit the code:
$ git init $ echo node_modules > .gitignore $ git add . $ git commit -m "Initial commit"
Now we’re ready for Heroku. Run its ‘create’ command:
$ heroku create
And you’ll see something like this:
To make it work, we just need to push up our code by running:
$ git push heroku master
It will print out a bunch of stuff, and then the app will be live. One of the last lines will tell you the URL of the app:
Now you can go to
<your url>/api/passwords and make sure it works.
Woohoo! You’ve got an app live on the real internet! Except it’s not very nice to use, yet. Let’s add a React frontend now.
Create the React App
We’re going to use Create React App to generate a project. Remember that we decided the React app would live in the “client” folder? (we did, back when we set up Express to point to “client/build” for static assets).
If you don’t have Create React App installed yet, do that first:
$ yarn global add create-react-app # or npm install -g create-react-app
Generate the React app inside the Express app directory:
$ create-react-app client
Create React App will proxy API requests from the React app to the Express app if we add a “proxy” key in package.json like this:
"proxy": ""
This goes in
client/package.json, not in the Express app’s package.json, and it will be ignored by Heroku after deploying.
Open up
src/App.js and replace it with this:
import React, { Component } from 'react'; import './App.css'; class App extends Component { // Initialize state state = { passwords: [] } // Fetch passwords after first mount componentDidMount() { this.getPasswords(); } getPasswords = () => { // Get the passwords and store them in state fetch('/api/passwords') .then(res => res.json()) .then(passwords => this.setState({ passwords })); } render() { const { passwords } = this.state; return ( <div className="App"> {/* Render the passwords if we have them */} {passwords.length ? ( <div> <h1>5 Passwords.</h1> <ul className="passwords"> {/* Generally it's bad to use "index" as a key. It's ok for this example because there will always be the same number of passwords, and they never change positions in the array. */} {passwords.map((password, index) => <li key={index}> {password} </li> )} </ul> <button className="more" onClick={this.getPasswords}> Get More </button> </div> ) : ( // Render a helpful message otherwise <div> <h1>No passwords :(</h1> <button className="more" onClick={this.getPasswords}> Try Again? </button> </div> )} </div> ); } } export default App;
You can update the CSS too, if you like (in
src/App.css):
.App { text-align: center; font-family: "Courier New", monospace; width: 100%; } h1 { font-weight: normal; font-size: 42px; } .passwords { list-style: none; padding: 0; font-size: 32px; margin-bottom: 2em; } .more { font-size: 32px; font-family: "Courier New", monospace; border: 2px solid #000; background-color: #fff; padding: 10px 25px; } .more:hover { background-color: #FDD836; } .more:active { background-color: #FFEFA9; }
I also recommend opening up
src/index.js and removing the call to
registerServiceWorker() at the bottom, since it can cause some confusing caching issues (like preventing you from accessing the API endpoints in a browser after you load the React app once).
Now start up the React app by running
yarn start inside the
client folder.
Make sure the Express app is running too: run
yarn start from its folder as well.
Go to and the app should be working! Now we can deploy the whole thing to Heroku.
Deploying to Heroku
When you deploy the app with the
git push heroku master command, git copies all the checked-in files up to Heroku. There are two complications now:
- We need to check in the new
clientcode
- Express depends on the built client code in
client/build, which we don’t have yet, and which we’d rather not check in to git.
What we’ll do is tell Heroku to build the React app after we push up the code, and we can do that by adding a “heroku-postbuild” script in the top-level (Express app’s) package.json.
Using Yarn
If you’re using Yarn, the script looks like this:
"scripts": { "start": "node index.js", "heroku-postbuild": "cd client && yarn && yarn run build" }
This tells Heroku “hey, after you’re done doing what you do, go into the client folder and build my React app.” The
yarn run build script will kick off Create React App’s production build, which will put its output files in the
client/build folder so Express can find them.
Using NPM
If you’re using NPM, the script will look like this:
"scripts": { "start": "node index.js", "heroku-postbuild": "cd client && npm install && npm run build" }
This tells Heroku “hey, after you’re done doing what you do, go into the client folder and build my React app.” The
npm run build script will kick off Create React App’s production build, which will put its output files in the
client/build folder so Express can find them.
Thanks to Matthew Locke and Babajide Ibiayo in the comments for how to get this working with NPM.
Time to Deploy
Once you have configured the
heroku-postbuild step for Yarn (or NPM), add everything to git and commit it. Make sure to run this from the top-level
rando directory, not inside
client:
$ git add . $ git commit -m "Ready for awesome"
If you run
git status now, you should see no red items.
Then you can deploy the app by running:
$ git push heroku master
It again prints out your app’s hostname. Mine is. Go there and try it out!
Congrats, you’ve got a React + Express app in production ;)
Get the Code
The complete app can be found on Github, and the README there explains how to deploy it.
npm branch with
git checkout npm if you want to use NPM. From there, the deploy will differ slightly – run
git push heroku npm:master to deploy the npm branch insead of master.
Learning React can be a struggle — so many libraries and tools!
My advice? Ignore all of them :)
For a step-by-step approach, check out my Pure React workshop.
>>IMAGE. | https://daveceddia.com/deploy-react-express-app-heroku/ | CC-MAIN-2019-51 | refinedweb | 1,605 | 73.17 |
>> ..."
In English, every word can be verbed. Would that it were so in our programming languages.
What do they teach in undergrad now? (Score:5, Insightful)
Pascal was good in... (Score:3, Insightful)
ouch! (Score:2, Insightful)
Hey, it legitimized the PC (Score:2, Insightful)
Seems like a limited (and rather verbose) language now, but it was UCSD Pascal for the Apple II and shortly thereafter Turbo Pascal for DOS that made it possible to create sophisticated and transportable programs on personal computers without spending a fortune on development tools. Prior to that point it was either assembly-level hacking (which produced some amazing work, but didn't generalize well) or BASIC (no more need be said...)
end;
Re: What do they teach in undergrad now? (Score:4, Insightful)
> But that was a long time ago and I pose the question. What language is the "teaching language" now? Do they have Pascal?
Pascal, C, C++, Java,
Memories of Pascal (Score:5, Insightful)
Now there are other languages to learn with (and a few of those aren't just for educational purposes). Java, PHP, and C for example. Even Delphi has kept Pascal alive and relevant.
Back then, I had to find...um...creative ways to be able to program and compile Pascal code. With all the freely available IDEs, compilers, debuggers, etc. around now for all these various languages (especially through OSS), things have become more accessible.
Pascal was the language that brought me out of my BASIC habits...for that I'm definitely grateful.
Re:What do they teach in undergrad now? (Score:5, Insightful)
It's like teaching people to drive with semi-tractor trailers.
Re:ouch! (Score:5, Insightful)
A teaching language (Score:3, Insightful)
Re:ouch! (Score:5, Insightful)
I used Turbo Pascal for DOS to write real-mode device drivers that loaded before windows did that communicated and made callbacks to windows applications written in Delphi (using the DPMI 0.9 API)
There really was nothing that could not be done or hacked with Turbo Pascal (and assembly) and Delphi (and more assembly as needed).
Borland DID get windows, more than MS did.
None of MS widget wrappers around the raw windows API compare in any degree to Borlands excellent VCL (Visual Class Library) that encapsulated and extended windows in a most wonderful way.
I've seen people program in Delphi who only know how to program in C and it looked like it. Ugly, nasty code.
I've seen Delphi code written by people who understand object Pascal and it is a dream to behold. (I've done some good stuff too).
The reason Delphi didn't catch on enormously is partly to do with it not being a cross platorm language (object pascal I mean) butmostly for the same reasons smalltalk, scheme, EISA and so on didn't catch on. I wish I knew what that reason was.
Sam
Re:What do they teach in undergrad now? (Score:3, Insightful)
After all, the important thing to a freshman class is to understand what's happening in a loop, or a sort block or whatever. That fundamental stuff never changes so why change the language you teach it with???
Re:What do they teach in undergrad now? (Score:5, Insightful)
If a language can do that to you, it is a language worth knowing. Most modern languages (read scripting, like Perl, Python, Ruby, etc) support many functional paradigms, like map, lambda functions, etc. They are incredibly useful, if you know how.
Function Nesting (Score:3, Insightful)
There's one thing I really miss about Pascal: nested procedures and functions. Being about to write a little utility function in the scope of the function it helps is just so elegant. You don't have to pass a bunch of parameters to get them in scope. Nobody else can miscall your utility function because it's not out in the global namespace. It's immediately clear to people reading your code that it's just a subordinate helper and to which function it belongs.
Function nesting is a feature sorely lacking from languages like C. It's not to hard to work around this limitation in an OO language, but the solution is still not as elegant or efficient.
And even after 15 years of C and C++, it still makes more sense to me to use = for comparison and to have a special symbol like
:= for assignment.
Re:Let me be the first to say... (Score:4, Insightful)
program Anniversary (OUTPUT); {* define file used *}
begin
writeln ('Happy 30th Anniversary Pascal. You roxxorzz') {* semicolon not need before end *}
end.
Re:What do they teach in undergrad now? (Score:5, Insightful)
The reason they use it is because the program is based on MIT's highly-esteemed CSCI curriculum.
If Scheme fucked you up then you didn't really know anything about programming. LISP is a pretty questionable language for real world programming, but for the little tasks they make you do in Intro to CS it's perfect. It lets you learn about recursion and the fundamental sameness of code and data without a bunch of syntactical overhead.
Then later when they dump you head first into C for Machine Architecture and Operating Systems you can at least write good algorithms while you grapple with pointers and memory management.
It's a hell of a lot better then teaching kids Java's class libraries or a million magic ways to do things in Perl. A CSCI degree should not teach you things you wanted to know before, it should introduce you to all the things that make a good programmer. Study hard kid.
Re:What do they teach in undergrad now? (Score:3, Insightful)
Want Scheme to be an object-oriented language? You can make it one pretty easily, but first you have to understand the concept of closures and lexical scope. Want to learn functional programming? You can make a Y-combinator in just a few lines. Want to learn backwards-chaining declarative logic? Under 100 lines.
The beauty of Scheme is twofold. One, it's so minimalist that by itself it's almost useless; and two, in the process of making Scheme useful, you learn a lot about the way languages are designed and why they're designed that way. I didn't truly understand exceptions until I understood Scheme's call-with-current-continuation, for instance.
If you want programming, go to DeVry. If you want to learn computer science, stick with Scheme.
Re:ouch! (Score:4, Insightful)
I think the reason Delphi hasn't become mainstream is the same reason many other excellent products haven't. Microsoft cloned it with VB and kept just close enough behind that it was acceptable to choose the un-FUD'd development environment.
Re:Let me be the first to say... (Score:3, Insightful)
So encourages my teacher, but why? if you want to add a line afterwards, you'll need to add in a semicolon or face unexpected error messages - why not just put it there in the first place?
Re:More serious apps... (Score:4, Insightful)
Re:Why didn't it succeed? (Score:3, Insightful)
Not true. Pascal is generally easier to write a compiler for than C. Now you might be focusing on the optimization side of things, and in that case you'd be right. A naive compiler typically generates much better code for C-style pointer math than for arrays, and in Pascal you use the latter.
Even more serious (Score:5, Insightful)
And in certain circles, Pascal is still the language of choice. Lots of people who hack out basic native-code Windows software prefer Borland's Delphi IDE [borland.com] to any alternative. One reason is the programming language [wikipedia.org], which is actually an object-oriented extension of Pascal.
I spent 3 years at Borland, documenting their component libraries [wikipedia.org], which are mostly written in Delphi. I came to appreciate its simplicity and power. My job required me to go back and forth between Delphi and C++ (the same libraries are used in Borland's C++ products) and it was an object lesson (forgive the pun) in how painfully baroque C++ has become.
It's a pity that Pascal/Delphi has so thoroughly lost the language wars. But it has. Even if C++ hadn't thoroughly taken over native-code programming, Borland's bizarre and insular corporate culture would keep from spreading beyond a few fierce loyalists.
Re:More serious apps... (Score:4, Insightful)
You've got issues.
Are you suggesting that because Java implemented Vector in it's API library (which, by the way is now ArrayList in Java as well) that it somehow has a right to be the only language that implements Vector, and therefore call all other languages that implement vector a rip off?
Vector is a Collection, it's a concept that all people learn when studying computer science, so it makes sense to have that kind of 'dynamic array' in your API no matter what languahe it's in (python, java or c#).
What you're trying to say, that the subtle differences between languages are not enough to differentiate them. Yet in today's world of hi-level languages and managed runtimes, the only thing to differentiate between languages are the subtle differeces.
Look I don't really care which language is better (in your mind or anyone elses), the fact remains that untill C# came along with the newer language constructs and features, Java didn't even bother to implement them. So at the very least, the competition is spurring on development/innovation between the two companies.
Oh and by the way, doesn't your language also lend itself to the 'java is a rip off of C++' arguement, since they are so similar and c++ came first ?
It's apples and oranges dude, and your agument is a total troll.
Re:Why didn't it succeed? (Score:2, Insightful)
One thing that helps Pascal readability over Java and C dirivatives is that declarations of types come *after* the variable name instead of before. The variable name is usually more important than the type name, so seeing it lined-up on the left side makes it easier to spot.
Re:More serious apps... (Score:3, Insightful)
The original Java designers apparently didn't stop to think why the this was called 'vector' in the first place and just put it in the spec, this while they didn't have legacy code to contend with. Once they found their 'Vector' was too slow for its most common use they invented something weirdly called an 'ArrayList' (which looks more like the std::vector). Now wow, that's a weird name: is it an array or a list??? They probably refrained from using Array because at that point they needed to conted with legacy code
:-) Ah well, I think that nobody would argue that Java at its core is very consistent anyway (String.size, Collection.size(), T[].length?). | https://developers.slashdot.org/story/04/10/21/2017251/30th-anniversary-of-pascal/insightful-comments | CC-MAIN-2017-22 | refinedweb | 1,846 | 64.41 |
Nov 10, 2010 10:04 AM|gijigae|LINK
All,
In the List screen, I would like to insert a certain record into a table before update the list if the record does not exist in the table.
For example, in my Product List screen, Category field is a textbox and at backend DB it has FK relationsihp with Product.
When a user inserts/updates a new product, I want to first check whether a category entered exists.
If it doesn's, then the category should be inserted into the category table first to avoid FK constraint issue.
I am thinking of using "Instead Of Update" trigger if it cannot be done from DD side.
Would you please share your thoughts on this matter?
Best regards,
All-Star
17915 Points
MVP
Nov 10, 2010 10:36 AM|sjnaughton|LINK
Hi Gijigae, I did this article for this type of situation A Popup Insert control for Dynamic Data if the Category does not exist then you click the NEW button and a popup page open for you to enter the new category.
Dynamic Data Popup Insert
All-Star
35159 Points
Nov 10, 2010 10:37 AM|smirnov|LINK
Another way is to update through stored procedure where you can check if record exists and perform insert if not.
Here's how to call SP
Nov 10, 2010 03:37 PM|Roddey|LINK
Steve:
I am using your Popup Insert control to insert new items in the dropdown list on a related item.
However; I am getting an javascript error "Object not found" error when I try to add a new item with EnablePartialUpdate="true". I do not get that error when I have EnablePartialUpdates set to false. I am using EFM in my application and the page that I am calling the control from is in a Formview control. Either I did not translate your code exactly form the LNQ to sql to EFM or I have a namespace probelm when it calls the "NotAClue" web control.
Do you have any ideas as what may cause the error and have you given any more consideration to converting the code to use the Ajax modal popup extender control?
I really appreciate the work you have done and the help you have provided. I really don't understand why Microsoft has stopped making updates to the Dynamic Data controls.
Thanks
Roddey
All-Star
17915 Points
MVP
Nov 10, 2010 09:14 PM|sjnaughton|LINK
Hi Roddey, I've just tested it with partail render enabled and it's working fine for me not sure what is going on, I would try a vanila project with minimal config to get popup to work and see if you still have the issue.
Dynamic Data 4
4 replies
Last post Nov 10, 2010 09:14 PM by sjnaughton | https://forums.asp.net/t/1621956.aspx?Insert+before+update | CC-MAIN-2019-43 | refinedweb | 471 | 63.32 |
Created on 2017-03-06 21:27 by Oren Milman, last changed 2017-08-26 14:52 by steve.dower. This issue is now closed.
------------ current state ------------
import io
class IntLike():
def __init__(self, num):
self._num = num
def __index__(self):
return self._num
__int__ = __index__
io.StringIO('blah blah').read(IntLike(2))
io.StringIO('blah blah').readline(IntLike(2))
io.StringIO('blah blah').truncate(IntLike(2))
io.BytesIO(b'blah blah').read(IntLike(2))
io.BytesIO(b'blah blah').readline(IntLike(2))
io.BytesIO(b'blah blah').truncate(IntLike(2))
The three StringIO methods are called without any error, but each of the three
BytesIO methods raises a "TypeError: integer argument expected, got 'IntLike'".
This is because the functions which implement the StringIO methods (in
Modules/_io/stringio.c):
- _io_StringIO_read_impl
- _io_StringIO_readline_impl
- _io_StringIO_truncate_impl
use PyNumber_AsSsize_t, which might call nb_index.
However, the functions which implement the BytesIO methods (in
Modules/_io/bytesio.c):
- _io_BytesIO_read_impl
- _io_BytesIO_readline_impl
- _io_BytesIO_truncate_impl
use PyLong_AsSsize_t, which accepts only Python ints (or objects whose type is
a subclass of int).
------------ proposed changes ------------
- change those BytesIO methods so that they would accept integer types (i.e.
classes that define __index__), mainly by replacing PyLong_AsSsize_t with
PyNumber_AsSsize_t
- add tests to Lib/test/test_memoryio.py to verify that all six aforementioned
methods accept integer types
What is the use case? Unless changing the behaviour would be useful, I think the simplest solution would be to document that the methods should only be given instances of “int”, so that it is clear that other kinds of numbers are unsupported.
I don't have a use case for that. (I noticed this behavior by
chance, while working on some other issue.)
However, IIUC, commit 4fa88fa0ba35e25ad9be66ebbdaba9aca553dc8b,
by Benjamin Peterson, Antoine Pitrou and Amaury Forgeot d'Arc,
includes patching the aforementioned StringIO functions, so that
they would accept integer types.
So I add them to the nosy list, as I guess that the use cases for
accepting integer types in StringIO methods are also use cases
for accepting integer types in BytesIO.
And now that you mention the docs, according to them, both StringIO
and BytesIO inherit these methods from BufferedIOBase or IOBase.
Thus, the methods are already expected to behave the same, aren't
they?
Other objects in the io module use special-purposed converter _PyIO_ConvertSsize_t() which checks PyNumber_Check() and calls PyNumber_AsSsize_t().
I think StringIO implementation can be changed to reuse _PyIO_ConvertSsize_t() for simplicity.
After that BytesIO implementation can be changed to use the same converter just for uniformity.
Are there tests for accepting non-integers in other classes? If no then don't bother about tests. I suppose all this came from the implementation of the 'n' format unit in PyArg_Parse* functions.
using _PyIO_ConvertSsize_t sounds great.
with regard to tests for accepting integer types in other classes,
there aren't a lot of them, so I guess it is not always tested.
still, it is tested in (excluding tests of the actual feature of
treating integer types as ints): test_bytes, test_cmath, test_int,
test_math, test_range, test_re, test_slice, test_struct,
test_unicode and test_weakref.
also with regard to adding tests, consider the following scenario:
in the future, someone writes a patch for these functions, which
makes them not accept integer types anymore.
assuming the tests don't exist, the writer of the patch doesn't
realize the patch broke something, and so the patch is committed.
years later, when the patch is finally a part of the stable release,
it breaks a lot of code out there.
lastly, ISTM adding these tests would be quite simple anyway.
I wrote a patch, but I attach it here and not in a PR, as you haven't approved
adding tests. (I would be happy to open a PR with or without the tests.)
I ran the test module (on my Windows 10), and seems like the patch doesn't
break anything.
also, while running test_memoryio with my added tests, i noticed some places in
Lib/_pyio.py which seemed like they should be changed.
in particular, I changed 'var.__index__' to 'var = var.__index__()' in some
places.
I feel really uncomfortable about that change, as it undos a change committed
by Florent Xicluna in b14930cd93e74cae3b7370262c6dcc7c28e0e712.
Florent, what was the reason for that change?
LGTM.
should I open a PR (even though we didn't give Florent enough time to
respond)?
Open a PR. It will be not hard to make small changes after opening it.
sure.
In general, should drafts (like this one) be uploaded here?
or is it always better to open a PR?
This for your preference.
I would accept changes to Modules/_io/ because I consider them as code cleanup (with little side effect). But I'm not sure about changes to Python implementation and tests. Could you create more narrow PR for Modules/_io/ changes and left other changes for the consideration of the io module maintainers?
done
thanks :)
I would update the original PR soon.
or maybe git is smart enough to realize what happened, and I don't have
to update PR 560?
New changeset 740025478dcd0e9e4028507f32375c85f849fb07 by Serhiy Storchaka (orenmn) in branch 'master':
bpo-29741: Clean up C implementations of BytesIO and StringIO. (#606)
New changeset de50360ac2fec81dbf733f6c3c739b39a8822a39 by Steve Dower (Oren Milman) in branch 'master':
bpo-29741: Update some methods in the _pyio module to also accept integer types. Patch by Oren Milman. (#560) | https://bugs.python.org/issue29741 | CC-MAIN-2018-34 | refinedweb | 890 | 65.42 |
How to Find an Element in a List with Java
Last modified: February 12, 2020
1. Overview
Finding an element in a list is a very common task we come across as developers.
In this quick tutorial, we'll cover different ways we can do this with Java.
Further reading:
Checking If a List Is Sorted in Java
Java List Initialization in One Line
2. Setup
Let's start by defining a Customer POJO:
public class Customer { private int id; private String name; // getters/setters, custom hashcode/equals }
And an ArrayList of customers:
List<Customer> customers = new ArrayList<>(); customers.add(new Customer(1, "Jack")); customers.add(new Customer(2, "James")); customers.add(new Customer(3, "Kelly"));
Note that we've overridden hashCode and equals in our Customer class.
Based on our current implementation of equals, two Customer objects with the same id will be considered equal.
We'll use this list of customers along the way.
3. Using Java API
Java itself provides several ways of finding an item in a list:
- The contains method
- The indexOf method
- An ad-hoc for loop, and
- The Stream API
3.1. contains()
List exposes a method called contains:
boolean contains(Object element)
As the name suggests, this method returns true if the list contains the specified element, and returns false otherwise.
So when we just need to check if a specific item exists in our list, we can do:
Customer james = new Customer(2, "James"); if (customers.contains(james)) { // ... }
3.2. indexOf()
indexOf is another useful method for finding elements:
int indexOf(Object element)
This method returns the index of the first occurrence of the specified element in the given list, or -1 if the list doesn't contain the element.
So, logically, if this method returns anything other than -1, we know that the list contains the element:
if(customers.indexOf(james) != -1) { // ... }
The main advantage of using this method is that it can tell us the position of the specified element in the given list.
3.3. Basic Looping
But what if we want to do a field-based search for an element? Say we're announcing a lottery and we need to declare a Customer with a specific name as the winner.
For such field-based searches, we can turn to iteration.
A traditional way of iterating through a list is to use one of Java's looping constructs. In each iteration, we compare the current item in the list with the element we're looking for to see if it's a match:
public Customer findUsingEnhancedForLoop( String name, List<Customer> customers) { for (Customer customer : customers) { if (customer.getName().equals(name)) { return customer; } } return null; }
Here, the name refers to the name we are searching for in the given list of customers. This method returns the first Customer object in the list with a matching name, and null if no such Customer exists.
3.4. Looping With an Iterator
Iterator is another way that we can traverse a list of items.
We can simply take our previous example and tweak it a bit:
public Customer findUsingIterator( String name, List<Customer> customers) { Iterator<Customer> iterator = customers.iterator(); while (iterator.hasNext()) { Customer customer = iterator.next(); if (customer.getName().equals(name)) { return customer; } } return null; }
And the behavior is the same as before.
3.5. Java 8 Stream API
As of Java 8, we can also use the Stream API to find an element in a List.
To find an element matching specific criteria in a given list, we:
- invoke stream() on the list
- call the filter() method with a proper Predicate
- call the findAny() construct which returns the first element that matches the filter predicate wrapped in an Optional if such an element exists
Customer james = customers.stream() .filter(customer -> "James".equals(customer.getName())) .findAny() .orElse(null);
For convenience, we default to null in case an Optional is empty but this might not always be the best choice for every scenario.
4. Third-Party Libraries
Now, while the Stream API is more than sufficient, what should we do if we're stuck on an earlier version of Java?
Fortunately, there are many third-party libraries like Google Guava and Apache Commons which we can use.
4.1. Google Guava
Google Guava provides functionality that is similar to what we can do with streams:
Customer james = Iterables.tryFind(customers, new Predicate<Customer>() { public boolean apply(Customer customer) { return "James".equals(customer.getName()); } }).orNull();
As we can with Stream API, we can optionally choose to return a default value instead of null:
Customer james = Iterables.tryFind(customers, new Predicate<Customer>() { public boolean apply(Customer customer) { return "James".equals(customer.getName()); } }).or(customers.get(0));
The above code will pick the first element in the list if no match is found.
And don't forget that Guava throws a NullPointerException if either the list or the predicate is null.
4.2. Apache Commons
We can find an element in almost the exact same way using Apache Commons:
Customer james = IterableUtils.find(customers, new Predicate<Customer>() { public boolean evaluate(Customer customer) { return "James".equals(customer.getName()); } });
There are a couple of important differences, though:
- Apache Commons just returns null if we pass a null list
- It doesn't provide default value functionality like Guava's tryFind
5. Conclusion
In this article, we've learned different ways of finding an element in a List, starting with quick existence checks and finishing with field-based searches.
We also looked at the third-party libraries Google Guava and Apache Commons as alternatives to the Java 8 Streams API.
Thanks for stopping by, and remember to check out all the source for these examples over on GitHub. | https://www.baeldung.com/find-list-element-java | CC-MAIN-2020-40 | refinedweb | 948 | 52.49 |
This post is a code snippet: a short code example to demonstrate a topic.
From now on I’ll write in this blog useful code snippets that I come to write.
A question on StackOverflow motivated me to write a simple C# console application that demonstrates a way of counting how often a value appears within a given set. I used LINQ to accomplish this.
I’ve commented the code in green so that it’s easier to understand what’s going on.
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { // Creating a list of Values that serves as the data source for LINQ query. List<int> values = new List<int>() { 0, 1, 2, 3, 6, 2, 3, 1, 0, 4, 5, 7, 8, 9, 3, 7, 5 }; // For each Value in the data source, let's group by Value into g. g stores all Values grouped. // Using the select new constructor we create an Anonymous Type that has each distinct Value and its Count (how often it appears). var query = from v in values group v by v into g select new { Value = g.Key, Count = g.Count() }; // A simple foreach that prints in the screen each Value and its frequency. foreach (var v in query) { Console.WriteLine("Value = {0}, Count = {1}", v.Value, v.Count); } } }
This is the output:
Value = 0, Count = 2 Value = 1, Count = 2 Value = 2, Count = 2 Value = 3, Count = 3 Value = 6, Count = 1 Value = 4, Count = 1 Value = 5, Count = 2 Value = 7, Count = 2 Value = 8, Count = 1 Value = 9, Count = 1
Hope you enjoy and make good use of this code.
Feel free to comment and add any other way of doing this in a more efficient or elegant fashion. | http://www.leniel.net/2010/09/counting-value-frequency-using-linq.html | CC-MAIN-2017-43 | refinedweb | 298 | 72.56 |
MOUNT_PROCFS(8) BSD System Manager's Manual MOUNT_PROCFS(8)
mount_procfs - mount the process file system
mount_procfs [-o options] /proc mount_point
The mount_procfs command attaches an instance of the process namespace to the global filesystem namespace. The conventional mount point is /proc. This command is normally executed by mount(8) at boot time. The options are as follows: -o options Options are specified with a -o flag followed by a comma separat- ed string of options. See the mount(8) man page for possible op- tions and their meanings. The following procfs specific option is also available: linux Add Linux compatibility links and nodes to procfs. The root of the process filesystem contains an entry for each active pro- cess. These processes are visible as a directory whose name is the process's PID. In addition, the special entry curproc references the current process. Each directory contains several files. cmdline Process command line parameters, separated by NULs. ctl A write-only file which supports a variety of control operations. Control commands are written as strings to the ctl file. The con- trol commands are: attach Stops the target process and arranges for the sending process to become the debug control process. detach Continues execution of the target process and removes it from control by the debug process (which need not be the sending process). run Continues running the target process until a signal is delivered, a breakpoint is hit, or the target process ex- its. step Single steps the target process, with no signal delivery. wait Waits for the target process to come to a steady state ready for debugging. The target process must be in this state before any of the other commands are allowed. The string can also be the name of a signal, lower case and without the SIG prefix, in which case that signal is delivered to the process (see sigaction(2)). file A reference to the vnode from which the process text was read. This can be used to gain access to the process's symbol table, or to start another copy of the process. fpregs The floating point registers as defined by struct fpregs in <machine/reg.h>. fpregs is only implemented on machines which have distinct general purpose and floating point register sets. mem The complete virtual memory image of the process. Only those ad- dress which exist in the process can be accessed. Reads and writes to this file modify the process. Writes to the text seg- ment remain private to the process. note Not implemented. notepg Not implemented. regs Allows read and write access to the process's register set. This file contains a binary data structure struct regs defined in <machine/reg.h>. regs can only be written when the process is stopped. status The process status. This file is read-only and returns a single line containing multiple space-separated fields as follows: • Command name. • Process ID. • Parent process ID. • Process group ID. • Session ID. • major,minor of the controlling terminal, or -1,-1 if there is no controlling terminal. • List of process flags: ctty if there is a controlling termi- nal, sldr if the process is a session leader, or noflags if neither of the other two flags are set. • Process start time in seconds and microseconds, comma separated. • User time in seconds and microseconds, comma separated. • System time in seconds and microseconds, comma separated. • Wait channel message. •)). Statistics reported by df(1) on a procfs filesystem will indicate virtual memory used/available instead of 'disk space', and the number of process slots used/allocated instead of 'inodes'. The block size of the filesys- tem is the system page size.
/proc/# /proc/curproc /proc/curproc/cmdline /proc/curproc/ctl /proc/curproc/file /proc/curproc/fpregs /proc/curproc/mem /proc/curproc/note /proc/curproc/notepg /proc/curproc/regs /proc/curproc/status
mount(2), sigaction(2), sysctl(3), fstab(5), mount(8), umount(8)
The mount_procfs utility first appeared in 4.4BSD.
This filesystem may not be NFS-exported since most of the functionality of procfs requires that state be maintained. When changing the kern.allowpsa and/or kern.allowpse sysctl, this filesystem must be unmounted and remounted for the new permission bits to become active. MirOS BSD #10-current May 20, 2012. | http://www.mirbsd.org/htman/sparc/man8/mount_procfs.htm | CC-MAIN-2014-52 | refinedweb | 712 | 58.38 |
I am building up a nested model that iterates through N feature classes (point shapefiles) in order to calculate statistics for field X and get the minimum value for each feature class. So far so good.
The iteration includes the model tool Get Field Value to extract the minimum value from the summary statistics and the Collect Values Tool to collect the values (Zmin, see figure below). It works properly.
Next step would be to extract the minimum out of the N collected values (Zmin) and use it as a parameter in the main model:
The output of the nested model (Zmin) is returned as multiple values:
I have tried to use the Calculate Value Tool applying the following function:
Expression:
lowest("%Zmin%")
Code Block:
def lowest(Zmin):
Zmin.replace(";",",")
Zmin.split(',')
LowestLine = min(Zmin)
return LowestLine
Data Type: Double
It only returns '-', thus something is obviously wrong in the code but I cannot figure out what, due to my limited Python skills. Any help would be very much appreciated! Thanks in advance.
You were almost correct! Your function should be:
This will return -118.9. If you wanted to return -157.3 then you use the max() function. | https://community.esri.com/thread/227212-calculate-value-from-collected-values-not-working | CC-MAIN-2019-18 | refinedweb | 199 | 63.7 |
![endif]-->
The boot-cloner is a program compiled and burnt with the Arduino IDE, that copies part of it's flash memory onto another microcontroller. The bootloader can be written to a new microcontroller by the Arduino, instead of burning the bootloader onto new ATmega8's with a separate device.
If you're like me, then you need more than one microcontroller, so you can put the IC into a circuit and leave it there permanently. Unfortunately, burning multiple bootloaders can be a very involved, time consuming process. The cloner will help you get dozens of new ATmega8's ready to use, in seconds. The program gives you access to an implementation of the ISP protocol and declaring and using tables stored in program flash, which don't occupy ram.
Notes:
In-System Programming (ISP) is a protocol developed by Atmel to be used as the primary means of programming their microcontrollers. The three wire serial protocol can be used to write the fuse bits, program memory and eeprom. It's a bit of a language by itself, and varys slightly from one microcontroller to another - mostly by chip architecture differences. (i.e. flash/eeprom size and fuse bit features) While holding the RESET pin of the microcontroller at a low level, the first command issued through ISP is called program enable. After those special 32 bits are sent, the microcontroller begins communicating. There's several commands that can be issued after program enable, which are sent serially at any rate: reading the flash memory, writing the flash memory page-by-page, erasing the flash memory, reading/writing the fuse bits or eeprom, reading device codes and more.
In the Boot-Cloner sketch is an implementation of the ISP protocol for an ATmega8, complete with functions that encapsulate the protocol's commands - making them easier to use. These functions are compatible with many of the other atmel microcontrollers as-is, but haven't been tested yet.
The bootloader written to the new ATmega8 is stored in a large array - because default fuse bits of your Arduino prevent reading the boot section. This was a problem I ran into, but the table that had to be added also provides new possibilities.
To sum it all up, this means the Boot-Cloner could write any program to any atmel microcontroller. But, because the target's program must be stored in the source's memory (which limits the maximum size of the program) it's only possible to write small programs like bootloaders.
The ISP protocol is detailed in the Atmel ATmega8 datasheet, towards the end. Additional comments in the sketch's source code describe command parameters and the flash write process.
1) Download and expand the zip archive containing the source code and schematic
2) In the Arduino IDE, open the Boot-Cloner sketch
3) Verify the sketch compiles without error
4) The +5V and GND of your Arduino should be used to power the target ATmega8
5) Upon wiring the circuit, according to the schematic, your Arduino should be connected by 10 wires to a breadboard
5V, GND, RESET, SCK, MISO, MOSI, LED1, LED2, LED3, START BTN
6) Ensure you have the chip oriented correctly, and oscillator and power connected to the pins as shown in the schematic
7) Burn the BootCloner sketch to the Arduino and wait for the program to start - you'll see an LED light up according to the program's state
8) At this point, you can push the start button.
The LEDs will change from Idle/Green to Run/Yellow for a moment (less than 4 seconds) and then switch back to Idle/Green.
9) Remove the target ATmega8, insert the next.
10) Test the first one you burn, the first time you do this, by putting it in an Arduino and writing the Blinking LED program.
11) If step 10 worked you can repeat steps 8 and 9 until all your ICs are prepared.
The bootloader table in the BootCloner sketch holds the raw data which is written to the boot section of the microcontroller. However, a hex file contains memory address and checksums in addition to the raw data. To save space the extra information was discarded and the string hexadecimal numbers were converted to decimal or hexadecimal constants recognizable by the Arduino IDE. (0-255 or 0x00-0xFF)
At the beginning of the BootCloner source code is a reference to a website described as "iHex flash file format information". If you want to understand the format better, that's a great place to start.
The program below, "Hex Data Extractor" can be built into an application that'll extract it for you.
There are also some things in the sketch that need to be changed. How many defined constants need to be modified depends on how different your target microcontroller is than an ATmega8. Ideally you should only have to change the constants, and not the program itself.
Alternate bootloader for an ATmega8:
Alternate bootloader for an ATmega168:
Diecimila bootloader for ATmega168 (arduino-010 version)
Alternate bootloaders for other atmel microcontrollers:
Notes:
/* Data Extractor for Intel Hex Formatted Files * ------------------ * Created 2007 by jims * <mailto:jim@federated.com> * * Compile this with your preferred C environment, as a standard console app. * From the console (Command Prompt), launch the app with the hex file pathname. * The console output will be the extracted hex data. * * 05/25/2008: Bug fix by froyer * . The last important byte of each line was getting truncated. * . replaced buf[len-4] = 0; with buf[len-3] = 0; and zeroed out 2 more bytes to the end of the line * . removed space between bytes in output */ #include <stdio.h> #include <string.h> void main() { char buf[4096]; int ByteCount = 0; while(fgets(buf, sizeof(buf)-1, stdin)) { int len = strlen(buf); char *b; if (len<9) { continue; } buf[len-3] = 0; buf[len-2] = 0; buf[len-1] = 0; for (b = buf+9; *b; b += 2) { printf("0x%c%c,", b[0], b[1]); ByteCount++; } printf("\n"); } printf("/*%d Bytes*/", ByteCount); }
I couldn't get the above code to work on Windows. This modified code does:
#include "stdafx.h" #include "stdio.h" #include "string.h" int main(int argc, char* argv[]) { FILE * pFile; pFile = fopen (argv[1], "r"); if (pFile == NULL) { perror ("Error opening file"); return 1; } else { char buf[4096]; int ByteCount = 0; while(fgets(buf, sizeof(buf)-1, pFile)) { int len = strlen(buf); char *b; if (len<9) { continue; } buf[len-3] = 0; //write null 2nd char //last char - strips out the //last two chars ie checksum for (b = buf+9; *b; b += 2) //strip out //first 9 chars - ie non-data chars { printf("0x%c%c,", *b, *(b + 1)); // changed b[1]; - array format to *(b + 1); -pointer //format for consistency ByteCount++; } printf("\n"); } printf("/*%d Bytes*/", ByteCount); fclose (pFile); return 0; } }
(It's probably not terribly useful at the moment since there don't appear to be any alternative bootloaders for the Atmega8 but it does work.)
NOTE by Fabien Royer, May 26 2008 I had not luck with this Boot Cloner. However, I was able to use [] successfully.
Note by Ae7flux, 02/06/08 Doesn't work with the Atmega168 but it's fine for the Atmega8 (programs in about two seconds).
Note by Celso Fraga, July 18 2008
Worked like a charm! Even bringing back to life some Mega8's that was lying around... I've built an shield for the Boot-Clonner, I can upload some pics if somebody told me how to... | http://playground.arduino.cc/BootCloner/BootCloner | CC-MAIN-2017-09 | refinedweb | 1,258 | 58.11 |
Introduction
In this Wagtail tutorial, I will talk about how to implement search function in Wagtail blog so the user can search the posts through keywords.
Basic search function
Wagtail search can work with many backend systems such as Database, ElasticSearch and Whoosh, considering what we build is a blog application, I will use database backend here because Elasticsearch is too heavy for us.
First, we continue to add a new route to our
BlogPage, to make it can handle
search path in URL.
class BlogPage(RoutablePageMixin, Page): @route(r'^search/$') def post_search(self, request, *args, **kwargs): search_query = request.GET.get('q', None) self.posts = self.get_posts() if search_query: self.posts = self.posts.filter(body__contains=search_query) self.search_term = search_query self.search_type = 'search' return Page.serve(self, request, *args, **kwargs)
The method above is a view function handle the search request, we use
filter method in Django ORM to filter the posts by search keywords.
body__contains means to find posts, body of which contains the keywords, the query would be translated to SQL like this
SELECT ... WHERE body LIKE '%search_query%';.
If you read above code carefully, you will notice that there is
search_term and
search_type here, which I will talk about in a bit.
Add search form to template
Now we need to add search form in our sidebar.html so use can enter the keyword in this form.
<form role="search" method="get" class="form-search" action="{% routablepageurl blog_page "post_search" %}" method="get"> <div class="input-group"> <input type="text" class="form-control search-query" name="q" placeholder="Search…" title="Search for:" /> <span class="input-group-btn"> <button type="submit" class="btn btn-default" name="submit" id="searchsubmit" value="Search"> <span class="glyphicon glyphicon-search"></span> </button> </span> </div> </form>
We use
routablepageurl to resolve the search url for us, which has been explained in the previous tutorial, keyword will be sent through HTTP GET method, which can be found in http parameters with key
q.
To make users can see what they are searching, we need to show the keywords in the template, that is why
search_query and
search_type has been used to tell us the search type (
search,
tag,
category) and search keyword (
keyword,
category name,
tag name).
We can add this to the top of the
blog_page.html
{% if search_term %} <header class="page-header"> <h1 class="page-title">Search Results for <span>{{ search_type }}: {{ search_term }}</span></h1> </header> {% endif %} ......
Here is the screenshot of our Wagtail Blog.
How to search multiple fields at one time?
You can set
search_fields to make user search multiple fields at once.
search_fields = Page.search_fields + [ index.SearchField('title'), index.SearchField('body'), ]
Then please use
self.posts.search(search_query) to do full-text search.
Some notes about search backend in Wagtail
Some people have no idea what backend they should use in wagtail project to support search I must say that depends on the data you want to index, if the data is big and you want the results to be more accurate, you should use big and heavy framework such as ElasticSearch, but based on my experience, most users have no need to import this tool. Remember to check the hardware before choosing ElasticSearch.
For most CMS projects, Postgres backend is a very good option for the following reasons.
- Postgres is a relation DB and Django can work with it very well.
- Postgres has full-text search support, and Wagtail has Postgres backend which supports full-text search feature very well.
If you are using SQLite db and you care about the performance of SQL
Like. You can take a look at wagtail-whoosh.
If you are also using Haystack
If you have used
Haystack in your project to support other custom search function, then I am sure you have met strange problem which told you
All documents removed. Updating backend: default: Backend doesn't require rebuild. Skipping after importing Wagtail to your project.
The reason why this happens is the command name conflict,
update_index exists in both frameworks, so Django can not determine which command should be called each time. So how to make both framework coexist in one project, you can find the solution and discussion here.
Updated in Jan, 4, 2019:
Haystack support Whoosh, Solr and Elascicsearch. Since Wagtail support Whoosh and Elasticsearch now, you can stop using haystack in your project.
As for Solr, you can let Postgres db to handle similar jobs, if you need more detail or tips about this, just contact me.
Conclusion
In this Wagtail tutorial, I showed you how to implement search function in wagtail blog so user can find the posts through the keywords, and give you some tips about search function in Wagtail. | https://www.accordbox.com/blog/wagtail-tutorials-7-add-search-function-wagtail-blog/ | CC-MAIN-2021-31 | refinedweb | 780 | 69.82 |
Java is not type-safe.
12c4bf87d1f0d650f32084ea8398bbab
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<HTML>
<HEAD>
<TITLE>Java is not type-safe</TITLE>
<META NAME="GENERATOR" CONTENT="Mozilla/3.01Gold (WinNT; I) [Netscape]">
<META NAME="Author" CONTENT="Vijay A. Saraswat">
<META NAME="Description" CONTENT="Technical report describing a major security bug in the type-system for Java.">
<META NAME="KeyWords" CONTENT="Java,security,bug,classloader,type-spoofing">
</HEAD>
<BODY TEXT="#000000" BGCOLOR="#FFFFFF" LINK="#0000EE" VLINK="#551A8B" ALINK="#FF0000">
<H1 ALIGN=CENTER><FONT COLOR="#CC0000">Java is not type-safe </FONT></H1>
<CENTER><ADDRESS><A HREF="mailto:vj@research.att.com">Vijay Saraswat </A></ADDRESS></CENTER>
<CENTER><ADDRESS><FONT SIZE=-1>AT&T Research,180 Park Avenue, Florham
Park NJ 07932 </FONT></ADDRESS></CENTER>
<P><FONT COLOR="#CC0000">Table of Contents </FONT></P>
<UL>
<LI><A HREF="#Abstract">Abstract</A></LI>
<LI><FONT COLOR="#CC0000"><A HREF="#Section 1. The">Section 1. The problem</A></FONT></LI>
<LI><FONT COLOR="#CC0000"><A HREF="#A concrete example.">A concrete example.</A></FONT></LI>
<LI><FONT COLOR="#CC0000"><A HREF="#Consequences.">Consequences</A></FONT></LI>
<LI><FONT COLOR="#CC0000"><A HREF="#Can an applet exploit">Can an applet
exploit type-spoofing?</A></FONT></LI>
<LI><FONT COLOR="#CC0000"><A HREF="#Section2">Section 2. How does this happen?</A></FONT></LI>
<LI><FONT COLOR="#CC0000"><A HREF="#Section 3">Section
3. How can it be fixed?</A></FONT></LI>
<LI><FONT COLOR="#CC0000"><A HREF="#Allow only one class per FQN to be loaded in.">One
class per FQN</A></FONT></LI>
<LI><FONT COLOR="#CC0000"><A HREF="#Check for type-spoofing at run-time.">Run-time
check</A></FONT></LI>
<LI><FONT COLOR="#CC0000"><A HREF="#Check types.">
Check for type-equivalence not name-equivalence
</A></FONT></LI>
<LI><FONT COLOR="#CC0000"><A HREF="#Section 4.">Section 4. Conclusion
</A></FONT></LI>
<LI><FONT COLOR="#CC0000"><A HREF="#Bibliography">Bibliography</A></FONT></LI>
<LI><FONT COLOR="#CC0000"><A HREF="#Appendix: Code">Remaining
code</A></FONT></LI>
</UL>
<FONT COLOR="#CC0000"><Font size=-1>Last modified
date:</A></FONT></font><code> Fri Aug 15 19:05:33 1997</code>
<ul>
<li><FONT COLOR="#CC0000"><A HREF="#Mtable">Added
comment on method-table generation.
</A></FONT></LI>
<li><FONT COLOR="#CC0000"><A HREF="#MTComp">Added
commentary on consequences of fix for method-table generation.
</A></FONT></LI>
</ul>
<H3><A NAME="Abstract"></A><FONT COLOR="#CC0000">Abstract </FONT></H3>
<P>A language is type-safe if the only operations that can be performed
on data in the language are those sanctioned by the type of the data. </P>
<P>Java is not type-safe, though it was intended to be. </P>
.</P>
<P>Java is not type-safe because it allows a very powerful way of
organizing the type-space at run-time (through user-extensible
<I>class loaders </I>).. </P>
<P <I>particular</I> Java program may not
exhibit this kind of type-spoofing, and one may design Java
programs in the future to satisfy this condition. A reading of
the informal description of class loaders given in <A
HREF="">HotJava</A>
indicate that it may satisfy this condition. </P>
<P>For the <I>language</I>. </p>
<P>Further study is needed to determine if there are any other
ways in which type-safety can be compromised in Java. </P>
<P> This is a revised version of an earlier note, of the same
name, that was informally circulated Monday Jul 21, 1997. That
version had (mistakenly, it now turns out) argued that some
run-time type-checks were unavoidable for unrestricted
class-loader functionality. Thanks to Gilad Bracha, Drew Dean,
Kathleen Fisher, Nevin Heintze, Tim Lindholm, Martin Odersky and
Fernando Pereira for useful feedback and discussion. I remain
responsible for the actual contents of this note. </P>
<H2><A NAME="Section 1. The"></A><FONT COLOR="#CC0000">Section 1. The problem
</FONT></H2>
<P>Let <I>A</I> and <I>A'</I> be two different classfiles defining a Java
class with the same fully qualified name (FQN) <I>N</I>. In a running Java
Virtual Machine (JVM) J, let <I>A</I> be loaded by a class loader <I>L</I>
(possibly the "null" loader) producing a <I>Class</I> object
<I>C</I> and <I>A'</I> by a class loader <I>L'</I> producing a <I>Class</I>
object C'. Let <I>v'</I> be a variable of "type" (we will have
more to say later about what is a "type" in Java) <I>N</I> in a class <I>D</I>
loaded in <I>L'</I>. </P>
<P><FONT COLOR="#CC0000">Proposition: </FONT>Any instance <I>t</I> of <I>C</I>
can be stored in <I>v'</I>. </P>
<P><FONT COLOR="#CC0000">Proposition: </FONT>J will (attempt to) execute
any operation defined in <I>A'</I> on <I>t.</I> J will (attempt to) read/write
any field defined in <I>A' </I>as if it existed in <I>t.</I></P>
<P>This behavior is unexpected. It contradicts the assertion <A HREF="#Lindholm">[Lindholm,
P 10]</A>: </P>
<BLOCKQUOTE>
<P>Compatibility of the value of a variable with its type is guaranteed
by the design of the Java language ... </P>
</BLOCKQUOTE>
<P>This behavior can be exploited to place the Java Virtual Machine in
an "undefined" state in which its behavior is unpredictable,
potentially compromising the Virtual Machine as well as the computer on
which it is running. </P>
<P>As I show below (<A HREF="#analysis"> Section 2 </A>), this
behavior is a consequence of the design of the constant pool
resolution process in the Java Virtual Machine. Empirically, I
have verified that this behavior is exhibited by Sun's JDK 1.1.3
system, on both Solaris and Windows. </P>
<P>But first let us examine some concrete examples and see what can go
wrong. </P>
<H3><A NAME="A concrete example."></A><FONT COLOR="#CC0000">A concrete
example. </FONT></H3>
<P>Let <A HREF="#R"><I>R</I> </A>be a base class that is desired to be
spoofed. For simplicity, let it contain just a <I>private</I> field: </P>
<PRE><A NAME="R"></A>public class R {
private int <A NAME="actual r"></A>r = 1;
}
</PRE>
<P>Assume that <I><A HREF="#R">R</A></I> has been loaded into J through
some class loader, L in J. (For simplicity, take L to be the "system
loader". So then it must be the case that this file for <I><A HREF="#R">R</A></I>
is stored in a directory on CLASSPATH.)</P>
<BLOCKQUOTE>
<P><FONT SIZE=-1><B>Footnote:</B> After this note was written, I
learnt (Lindholm, private communication) that, for some
essentially obscure reasons, the null classloader behaves
slightly differently from other classloaders in
ways not publically documented. However, I have since verified that the problems discussed
in this note arise when L is taken to be some non-null loader.
</FONT></P>
</BLOCKQUOTE>
<P>Assume that it is possible to obtain instances of <A
HREF="#R"><I>R</I> </A>through another class, <I><A
HREF="#RR">RR</A></I>, also loaded into L (thus <I><A
HREF="#RR">RR</A></I> also exists in a directory on
CLASSPATH). <I><A HREF="#RR">RR</A></I> is the crucial
"bridge" class --- accessible from within two
different classloaders, it will allow "crossover". For
simplicity, <I><A HREF="#RR">RR</A></I> may be thought of as
being defined as: </P>
<PRE><A NAME="RR"></A>public class RR {
public R getR() {
return new R();
}
}
</PRE>
<P><BR> Arrange now to load an <A HREF="#ersatz R1">ersatz class
<I>R</I></A> in another classloader L' in J. It is important that
this class have the same fully qualified name (FQN) as the target
class <I><A HREF="#R">R</A></I>. However, the signature of this
class (its fields and methods, and their associated types) may be
completely arbitrary, and designed to suit the requirements for
spoofing. For simplicity, assume that it is just desired to be
able to read/modify the value of the private variable. Then <I><A
HREF="#ersatz R1">R</A></I> can be defined simply as: </P>
<PRE><A NAME="ersatz R1"></A>public class R {
public int r;
}
}
</PRE>
<P>Arrange now for your code (say in a class <I><A HREF="#RT">RT</A></I>,
loaded into L') to receive in a variable, say <I>r</I> (of type <I>R</I>)
an instance of the <I><A HREF="#R">R</A></I> class loaded in L. </P>
<P>This can be accomplished, for instance, by arranging for L' to "share"
the use of the <I>Class</I> object for <I><A HREF="#RR">RR</A></I> loaded
into L, as follows. The code for <I>loadClass</I> in L' forwards a request
to load <I>RR</I> to L: </P>
<PRE><A NAME="DelegatingLoader"></A>/** A classloader that delegates some loads to the system loader,
* and serves other requests by reading in from a given directory.
*/
public class DelegatingLoader extends LocalClassLoader {
public DelegatingLoader (String dir) {
super(dir);
}
public synchronized Class loadClass(String name, boolean resolve)
throws ClassNotFoundException {
Class c;
try {
if (name.equals("RR") || name.startsWith("java.")) {
System.out.println("[Loaded " + name + " from system]");
return this.findSystemClass(name);
} else
return this.loadClassFromFile(name, resolve);
} catch (Exception d) {
System.out.println("Exception " + d.toString() + " while loading " + name + " in DelegatingLoader.");
throw new ClassNotFoundException();
};
}
}
</PRE>
<P>Here, <I><A HREF="#LocalClassLoader">LocalClassLoader</A></I> is an
abstract Class loader that knows how to load (through the method <I>loadClassFromFile</I>)
a class file from a local directory. This local directory should not be
on the system path (CLASSFILES). Thus an instance of <I><A HREF="#DelegatingLoader">DelegatingLoader</A></I>
will load all classes other than those named <I>RR</I> or in <I>java.* </I>packages
from the local directory. </P>
<P>Now, loading <I><A HREF="#RT">RT</A></I> into L' will eventually trigger
the loading of <I>RR</I> by L'. This request is met by returning the <I>Class</I>
object created by the system loader when it loaded <I>RR</I>. Loading <I><A HREF="#RT">RT</A></I>
will also eventually trigger the loading of <I>R</I> in L' --- however,
this will cause the <A HREF="#ersatz R1"> ersatz <I>R</I></A> file to be
loaded into L'. </P>
<P>Thus the stage is set for type confusion. <I><A HREF="#RT">RT</A></I>
is set to receive an object from <I><A HREF="#RR">RR</A></I> which it believes
to be an instance of the class described by <A HREF="#ersatz R1">ersatz
<I>R</I></A>. <I><A HREF="#RR">RR</A></I> is prepared to send an object
to <I><A HREF="#RT">RT</A></I> which is an instance of the class described
by <I><A HREF="#R">R</A></I>. </P>
<P>Here is a simple definition of <I><A HREF="#RT">RT</A></I>: </P>
<PRE>/** The user class, referencing and using the ersatz class R.
*/
<A NAME="RT"></A>Now all that remains is to ensure that <I><A HREF="#RT">RT</A></I> is
loaded into L'. This can be accomplished through the helper class <A HREF="#Test"><I>Test</I>
.</A></P>
<P>We may now get the trace: < (238 bytes)]
r.r is 1.
r.r is set to 300960.
...bye.
chit.saraswat.org%
</PRE>
<H3><A NAME="Consequences."></A><FONT COLOR="#CC0000">Consequences. </FONT></H3>
<P>Intuitively, the JVM is using the information associated with <A HREF="#ersatz R1">ersatz
<I>R</I></A> to operate on an instance of <I><A HREF="#R">R</A></I>. The
<A HREF="#ersatz R1">ersatz <I>R</I></A> class specifies the field <I>r</I>
to be public, so the JVM allows access and update. </P>
<P>But the structure of the <A HREF="#ersatz R1">ersatz <I>R</I></A> need
not be related to <I><A HREF="#R">R</A></I> at all. Suppose for instance,
<A HREF="#ersatz R2">ersatz <I>R</I></A> is defined as: </P>
<PRE><A NAME="ersatz R2"></A>public class R {
public int r0;
public String s = "This represents s.";
public int <A NAME="r"></A>r;
}
}
</PRE>
<P>Now the JVM believes that the field <I><A HREF="#r">r</A></I> lies at
a specific offset in the memory representing an instance of <A HREF="#ersatz R2">ersatz
<I>R</I></A> --- and this offset may well be different from that representing
the actual field <I><A HREF="#actual r">r</A></I> in <I><A HREF="#R">R</A></I>.
Indeed, given that the size of an instance of <I><A HREF="#R">R</A></I>
is smaller than the size of an instance of <A HREF="#ersatz R2">ersatz
<I>R</I></A>, references through fields of <A HREF="#ersatz R2">ersatz
<I>R</I></A> are going to access memory outside the region set aside to
represent the instance of <I><A HREF="#R">R</A></I>. We get: < (544 bytes)]
r.r is 6946913.
r.r is set to 300960.
...bye.
chit.saraswat.org%
</PRE>
<P>Similarly, ersatz <I>R</I> may define methods that do not exist in <I><A HREF="#R">R</A></I>,
or are in a different position in the method list, or take a different
number of arguments, or take arguments of different types ... causing complete
havoc. For instance, suppose ersatz <I>R</I> is defined as: </P>
<PRE><A NAME="ersatz R3"></A>public class R {
public int r0;
public String s = "This represents s.";
public int r;
public void speakUp() {
System.out.println("I have spoken!");
}
}
</PRE>
<P>and <A HREF="#RT2"><I>RT2</I> </A>is defined as: </P>
<PRE>/** Call a method defined on the ersatz class, but not the spoofed class.
*/
<A NAME="RT2"></A>public class RT2 {
public static void main() {
try {
System.out.println("Hello...");
RR rr = new RR();
R r = rr.getR();
System.out.println("Now checking to see if a method defined on this loader's r can be invoked.");
r.speakUp();
System.out.println("...bye.");
} catch (Exception e) {
System.out.println("Exception " + e.toString() + " in RT2.main.");
}
}
}
</PRE>
<P>We get the very interesting looking: </P>
<PRE>chit.saraswat.org% java Test RT2
[Loaded java.lang.Object from system]
[Loaded java.lang.Exception from system]
[Loaded RT2 from ersatz/RT2.class (934 bytes)]
[Loaded java.lang.System from system]
[Loaded java.io.PrintStream from system]
Hello...
[Loaded RR from system]
Now checking to see if a method defined on this loader's r can be invoked.
[Loaded R from ersatz/R.class (544 bytes)]
SIGBUS 10* bus error
si_signo [10]: SIGBUS 10* bus error
si_errno [0]: Error 0
si_pre [1]: BUS_ADRERR [addr: 0x443a7]
stackbase=EFFFF180, stackpointer=EFFFEEC0
Full thread dump:
"Finalizer thread" (TID:0xee300220, sys_thread_t:0xef320de0, state:R) prio=1
"Async Garbage Collector" (TID:0xee3001d8, sys_thread_t:0xef350de0, state:R) prio=1
"Idle thread" (TID:0xee300190, sys_thread_t:0xef380de0, state:R) prio=0
"Clock" (TID:0xee3000d0, sys_thread_t:0xef3b0de0, state:CW) prio=12
"main" (TID:0xee3000a8, sys_thread_t:0x40e08, state:R) prio=5 *current thread*
RT2.main(RT2.java:9)
Test.doIt(Test.java:17)
Test.main(Test.java:24)
Monitor Cache Dump:
Registered Monitor Dump:
Verifier lock: " <unowned>"
Thread queue lock: "<unowned>"
Name and type hash table lock: <unowned>
String intern lock: <unowned>
JNI pinning lock: <unowned>
JNI global reference lock: <unowned>
BinClass lock: <unowned>
Class loading lock: <unowned>
Java stack lock: <unowned>
Pre rewrite lock: <unowned>
Heap lock: <unowned>
Has finalization queue lock: <unowned>
Finalize me queue lock: <unowned>
Monitor IO lock: <unowned>
Child death monitor: <unowned>
Event monitor: <unowned>
I/O monitor: <unowned>
Alarm monitor: <unowned>
Waiting to be notified:
"Clock"
Sbrk lock: <unowned>
Monitor cache expansion lock: <unowned>
Monitor registry: owner "main" (0x40e08, 1 entry)
Thread Alarm Q:
Abort (core dumped)
chit.saraswat.org%
</PRE>
<H3><A NAME="Insidious example"></A><FONT COLOR="#CC0000">A more insidious example</FONT></H3>
Here is a more "natural" example of how such a problem may be
triggered. Suppose that a loader <code>L</code> "exports" the
service offered by a class <code>RR</code> to other loaders,
including <code>L'</code>. <code>RR</code> provides a public
method that needs an instance of <code>R</code>. But it so
happens that <code>L'</code>, unaware of the dependency of
<code>RR</code> on <code>R</code>, also loads <code>R</code> (the
<code>ersatz R</code>). Now any other class <code>RT</code> in
<code>L'</code> that wants to use <code>RR</code> will end up
sending an instance of its <code>R</code>, thereby triggering the
incompatibility.
<H3><A NAME="Can an applet exploit"></A><FONT COLOR="#CC0000">Can an applet
exploit type-spoofing?</FONT></H3>
<P>To answer this question, let us develop some terminology. Let
<code>J</code> be some running JVM, initialized with some program
<code>P</code>, and accepting inputs and delivering outputs to
its environment. In the following, we consider class objects in
<code>J</code> (i.e., instances of <code>java.lang.Class</code>)
to represent types in <code>J</code>. For any such object
<code>o</code>, <code>cl(o)</code> stands for the loader object
that created <code>o</code> (i.e. who's invocation of
<code>defineClass</code> created <code>o</code>). We say that
<code>cl(o)</code> defines <code>o</code>. The constant pool of
<code>o</code>, <code>cp(o)</code>, is the constant pool of the
class file that was used by <code>cl(o)</code> to create
<code>o</code>. <code>n(o)</code> is the fully qualified name of
the class whose classfile was read by <code>cl(o)</code> to
create <code>o</code>. </P>
<P>Over the course of execution of <code>J</code>, a loader <code>l</code> may be presented
with requests by the JVM to load a class, emanating from its
desire to do constant resolution. The JVM guarantees that, as
part of constant resolution, for any name <code>n</code>, it will call <code>l</code> at
most once to load a class with name <code>n</code>. Thus at any given instant
in the execution of <code>J</code>, <code>l</code> will have responded to some finite set
of requests, by either returning a valid class object, or
refusing to define a class object. (A loader <code>l</code> may also have
refused to terminate on some request, but since we are only
concerned with safety properties, we shall ignore that
possibility.) We shall model this by associating with <code>l</code> a mapping
m: m(l) from the set <code>dom(l)</code> of names in the domain of <code>l</code> to
class objects. </P>
<P>A name <code>n</code> is said to be <FONT COLOR="#008000">foreign</FONT>
for <code>l</code> if <code>n</code> is in <code>dom(l)</code> and <code>cl(m(l)(n))</code>
is different from <code>l</code>. </P>
<P><FONT COLOR="#CC0000">Definition[a refers to b</FONT>] Let
<code>a</code> and <code>b</code> be two class objects in
<code>J</code>. Say that <code>a</code> <FONT
COLOR="#008000">refers</FONT> to <code>b</code> if
<code>n(b)</code> occurs in <code>a's</code> constant pool, and
<code>m(cl(a))(n(b))</code> is defined and equals
<code>b</code>. That is, <code>a</code> refers to <code>b</code>
if the code for <code>a</code> refers to the name of
<code>b</code>, and the name of <code>b</code> is resolved by the
loader for <code>a</code> into <code>b</code>. </P>
<P><FONT COLOR="#CC0000">Definition[Bridge]</FONT> Let <code>J</code> be a
running JVM. A <FONT COLOR="#008000">bridge</FONT> in <code>J</code> is a set
of four class objects <code>(r, a', s, a)</code> such that:
(1) <code> cl(s) = cl(a) =/= cl(r) = cl(a')</code> (2) <code>r</code> refers to <code>s</code> (3) <code>r</code> refers to <code>a'</code>
(4) <code>s</code> refers to <code>a</code> and (5) <code>n(a) = n(a')</code>. <code>r</code> is said to be the
<FONT COLOR="#008000">receiver</FONT> of the bridge, <code>a'</code> the <FONT
COLOR="#008000">spoofer</FONT>, <code>s</code> the <FONT
COLOR="#008000">sender</FONT>, and <code>a</code> the <FONT
COLOR="#008000">spoofee</FONT>. </p>
<P><FONT COLOR="#CC0000">Definition[Bridge-safe] </FONT>A JVM <code>J</code> is
<FONT COLOR="#008000">bridge-safe</FONT> if at no time during its execution
(and for any input during its execution) may a bridge come into existence.
<P>Let us develop some general conditions on (class) loaders that
will be necessary and sufficient to prevent such bridges from coming into
existence. </P>
<P><FONT COLOR="#CC0000">Definition[Isolating foreigners]</FONT> A loader
<code>l</code> <FONT COLOR="#008000">isolates foreigners </FONT>if for every name <code>n</code>
foreign for <code>l</code> every class name <code>q</code> in the
constantpool of <code> m(l)(n)</code> (and in
the domain of <code>l</code> and <code> cl(m(l)(n)))</code> is foreign for <code>l</code>. </P>
<P>In the example discussed earlier, no instance of <code>DelegationLoader</code> isolates
foreigners, since the name <code>R</code> occurring in the constantpool of a foreign
name, <code>RR</code>, is not foreign. </P>
<P><FONT COLOR="#CC0000">Proposition.</FONT> Let <code>J</code> be a JVM. <code>J</code> is bridge-safe
iff every class loader that can come into existence during its execution
isolates foreigners. </P>
<P><FONT COLOR="#CC0000">Informal proof.</FONT> Suppose a bridge <code>(r, a',
s, a)</code> exists. Then, <code>n(s)</code> is a foreigner for
<code>cl(r)</code>. Assume <code>cl(r)</code> isolates
foreigners. Then <code> n(a)</code> is foreign for <code> cl(r)
</code>. But <code> n(a) = n(a')</code> and <code> n(a')</code>
is not foreign for <code> cl(r)</code> (it is mapped to <code> a'</code>). In the other direction assume
there is a loader <code>l</code> that does not isolate foreigners. Let <code>n</code> be a name foreign
to <code>l</code>, and name <code>q</code> be in the constant
pool of <code> m(l)(n)</code>, and <code>q</code> be not foreign
to <code>l</code>. Construct <code>a</code> class <code>r</code> in <code>l</code> that refers to <code>n</code> and <code>q</code>. Then each of <code>r</code>,
<code> m(l)(q), m(l)(n), m(cl(m(l)(n)))(q) </code> exists, and taken together constitute
a bridge. <FONT COLOR="#CC0000">End of proof.</FONT></P>
<P>In general, proving for any arbitrary class loader that it is bridge-safe
may be very difficult -- there may not be enough data available, e.g. about
the constantpools of the foreign classes. However, some general strategies
can be followed for <I>designing</I> loaders that isolate foreigners. </p>
<H3><A NAME="Applet classloader"></A><FONT COLOR="#CC0000">Applet
classloader </FONT></H3>
<p> For instance, a loader constructed as follows will always isolate
foreigners: It divides its domain into two disjoint parts, the
"core" domain, <code> cdom(l)</code> and the "user" domain,
<code> udom(l)</code>. All and only the names in the core domain are
foreign. Now any such <code>l</code> will isolate foreigners provided that it
is the case that for every <code>n</code> in the core domain of
<code>l</code>, <code> cp(m(l)(n))</code>
is a subset of <code> cdom(l)</code>. Again, in general there may not be enough
data available to make this decision --- but in practice, one
would write the "core classes" (the union, across
all <code>l</code>, of the sets obtained by mapping <code> m(l)</code> across <code>cdom(l)</code>) in
such a way that they only reference core classes. Under such a
design practice, the loaders would isolate foreigners. Note
however, that each time a new class was added to the core, one
would have to verify that it references only core classes. </P>
<P>From the informal description of the classloaders given in <A
HREF="">HotJava</A>,
it appears that they are written using this methodology. Thus, a
user may never be unconditionally certain that a particular
HotJava browser running on his desktop is bridge-safe --- but he
may be certain under the (reasonable) assumption that the core
classes already on his disk (and any other core class to be added
later) satisfy the property that they only reference core
classes. </P>
<H3><A NAME="Indirect bridges"></A><FONT
COLOR="#CC0000">Indirect bridges are already ruled out.
</FONT></H3>
<P>Before leaving this topic, I want to point out that another way
of causing type-spoofing, apparently described earlier by David Hopgood,
does not work. (I should say "does not work anymore".) Given
that a "direct" bridge is not possible for loaders that
isolate foreigners, one may try instead to construct an indirect bridge
as follows. Consider <code>s</code> and <code>r</code>, such that
<code> cl(s)</code> is distinct from <code> cl(r)</code>. Find
an intermediary class <code>i</code>, such that <code>cl(i)
</code>is distinct from <code>cl(s)</code> and <code> cl(r)</code>.
Thus <code>i</code> is foreign to both <code>s</code> and
<code>r</code>. Pick a name <code>q</code> in the domain of
<code> cl(s)</code> and <code>cl(r)</code>. Define <code>a</code>
in <code>cl(s)</code> to inherit from (the type associated with)
<code>i</code>, and <code>a'</code> in <code>cl(r)</code> to inherit from <code>i</code>. Now communicate from <code>s</code> an instance
of <code>q</code> typecast to <code>i</code>, receive it at <code>r</code> at type <code>i</code>, coerce it to type <code>q</code>, and
use it to spoof. </P>
<P>For instance, concretely, two applets <code>S</code> and <code>R</code> may work in tandem
to launch this attack. Both will be loaded into their own loaders. Both
define a type, say <code>RStream</code> to extend <code>java.lang.InputStream</code>, intending to
use <code>java.lang.System.in</code> as an unwitting conduit between them: <code>S</code> creates
an instance of its own <code>RStream</code>, and stores it in <code>System.in</code>. When the user
visits the page containing the applet <code>R</code>,
<code>R</code> reads <code>System.in</code>, casts the result
to (ersatz) RStream, and proceeds to wreak havoc. </P>
<P>The attack fails because the explicit cast at the receiving end generates
a <code>ClassCastException</code> <A HREF="#Lindholm">[Lindholm P. 175]</A>:
it checks that the class that the message is an instance of identical to
the class being typecast to, or inherits from it. So the <code>checkcast</code>
JVM instruction checks the "run-time type" as it should.
</P>
<H2><A NAME="Section2"></A><FONT COLOR="#CC0000">Section
2. How does this happen? </FONT></H2>
<P>Why does type-spoofing work? What is happening in the
JVM?
<P>On an abstract note, the heart of the problem lies in the
somewhat different views of "types" taken by the Java
compiler and the Java Virtual Machine. The reality in the JVM is
that multiple class files with the same name and arbitrarily
different fields and methods can be simultaneously loaded into
different classloaders. Therefore, a type should be a <b>pair</b>
<code> (FQN, CL)</code> of a name and the classloader in which the
corresponding class was loaded. (Primitive types can be
considered to be identical across all classloaders.) Thus two
classes have the type iff they have the same <code> FQN </code> and the
same <code> CL</code>. Though this is stated explicitly in <A
HREF="#Lindholm">[Lindholm P. 24, Sec 2.8.1]</A>, very
surprisingly neither the Java compiler, nor the JVM build this
more refined notion of types fully into their operation. </P>
<H3><A NAME="Current scope or base scope?"></A><FONT
COLOR="#CC0000">Current scope or base scope? </FONT></H3>
<p> If a type is to be thought of as the pair <code>(FQN,
CL)</code>, then the huge problem arises of how to make sense of
<A HREF="Gosling"> [Gosling 96] </A>! Throughout the book, a type is
talked of as if it is an <code> FQN</code>. There are clearly two ways of
obtaining an <code> (FQN, CL)</code> pair from an
<code>FQN</code> --- one may either assume that an <code>
FQN</code> stands for <code>(FQN, CL)</code> where <code>
CL</code> is the "current" classloader (I will call this <em>
current scope </em>), or one may assume <code> FQN</code> stands
for <code> (FQN, null)</code>, where <code> null</code> is the
"null" or the system classloader (I will call this <em> base
scope </em>).
<BLOCKQUOTE><p><b><i>
It appears that <A href = "Gosling"> [Gosling 96]</a> intends
different interpretations in different places.
</p></b></i></BLOCKQUOTE>
For instance, <A href = "Gosling"> [Gosling 96, p 40]</a> says:
<BLOCKQUOTE>
<P>The standard class <code> Object</code>
is a superclass (Sec 8.1) of all other classes. A variable of
type <code> Object</code> can hold a reference to any object,
whether it is an instance of a class or an array (Sec 10). </p>
</BLOCKQUOTE>
Which type <code>Object</code>? The one associated with the
class <code>(java.lang.)Object</code> loaded in the <em>
current </em> classloader (and hence in every class loader)
(current scope), or the one loaded in the <code> null </code>
classloader (base scope)?
Experimentally I have verified (in JDK 1.1.3) that an array
object can be assigned to a variable with typename <code>
java.lang.Object</code>, even though at runtime the class <code>
java.lang.Object</code> loaded into the current classloader is
different from the class <code> java.lang.Object</code> loaded in
the <code>null</code> classloader. So it seems that current scope
was intended.
However, we have on <A href = "Gosling"> [Gosling 96, p 466]</a>:
<blockquote>
There is no public constructor for the class <code>
Class</code>. The Java Virtual Machine automatically constructs
<code>
Class</code> objects as classes are loaded; such objects cannot
be created by user programs.
</blockquote>
<p>Which type <code> Class</code>? Current scope or base?
Experimentally I have verified that (in JDK 1.1.3) the <em>
base </em> interpretation is intended in this case: always the
<code> Class</code> objects created are instances of the <code>
Class</code> class loaded in the <code> null</code>
classloader. </p>
<p>It seems to me that the designers intended current scope for
"user-defined" classes (and this is how the JVM is
designed). Clearly, the notion of multiple classloaders does not
make sense otherwise. (You want the classnames in the applet code
loaded to refer to the classes loaded into the same loader.)
However it seems that base scope is intended for some predefined
"system" classes (this notion is not explicitly defined in the
book, but implicitly referred to) such as <code> java.lang.Class
</code> and <code> java.lang.String</code>.</p>
<p>In the interests of cleanliness of system design it seems to me
that current scope should be adopted uniformly. One very
attractive property of such a proposal would be that it would
allow different object systems, with very different
behaviors to be implemented very easily within Java --- merely by
changing the basic classes loaded into a given loader! --- increasing
its attraction as a language in which to experiment with
different OO language designs.</p>
<p>This confusion in thinking leads to the problem highlighted in
this paper. To see how, let us turn to an analysis of how Java
links and runs code. </p>
<H3><A NAME="Dynamic linking"></A><FONT COLOR="#CC0000">Dynamic
linking in Java. </FONT></H3>
<p>To support dynamic linking, the class file corresponding to a
Java source file retains (in its constant pool) the symbolic FQNs
of the classes, interfaces, fields, methods (and their typenames) in
its byte-code. For instance, a method invocation on an object is
associated in the class file with the name of the method being
invoked, the name of the class containing the declaration of the
method, and the <i> descriptor </i> of the method, which captures
the <i> name </i> (and sequence) of the argument typenames and the
return typenames of the method. </P>
<P> At run-time operations involving these symbolic references
are converted into operations involving actual offsets into field
and method-tables through a process known as
<FONT COLOR="#FF00FF">constant pool resolution (CPR) </FONT>
<A HREF="#Lindholm">[Lindholm Chapter 5]</A>.
<BLOCKQUOTE>
<P><FONT SIZE=-1><B>Footnote:</B>
The opcodes which can initiate CPR activity are:
<code> getfield</code>, <code> getstatic</code> (getting the
value of instance and static fields); <code> putfield</code>,
<code> putstatic</code> and <code> aastore</code> (setting the
value of instance and static fields, and entries in an array);
and <code> invokeinterface</code>, <code> invokespecial</code>,
<code> invokestatic</code> (invoking constructors and methods).
</FONT></P>
</BLOCKQUOTE>
<p>Now consider what happens at run-time when a method <code> m
</code> on class <code> c</code>, with descriptor d <code>
is</code> invoked on object <code> o</code> (using the <code>
invokevirtual</code> instruction, <A HREF="#Lindholm">[Lindholm
P267-8]</A>. (Similar considerations apply to other instructions
concerned with reading/writing fields, or invoking methods.) The
associated class loader is asked to load the class <code>
c</code>. (This may involve, recursively, the loading of other
classes, e.g. the superclass of <code> c</code>.)</P>
<BLOCKQUOTE>
<P><FONT SIZE=-1><B>Footnote:</B> Note that the code loaded by the class
loader in response to this request may have <I>no</I> relationship with
the code used by the compiler to compile this class. No "compiled-with"
information is stored by the compiler in the class file for use at link-time.
</FONT></P>
</BLOCKQUOTE>
<P>Once that is accomplished, <code> d</code> is matched against
the descriptors of methods defined in the just loaded
class (this is called resolving the method)
<A HREF="#Lindholm">[Lindholm 97, p148]</A>.
<BLOCKQUOTE><p><a name="NoSuchMethodError">
If the referenced method does not exist in the specified
class or interface, field resolution throws a
<code>NoSuchMethodError</code>. </a>
</P>
</BLOCKQUOTE>
<p>From the description it is not completely clear how it is
determined that the referenced method does not exist in the
specified class or interface. The most natural assumption seems
to be that two methods are considered "equal" if they are
<a name=name-equivalent> <FONT
COLOR="#FF00FF">name-equivalent</FONT> </a>, i.e., they have the same
name and the same method descriptor, which records the sequence
of FQNs for the arguments and the FQN for the result.</p>
<p> An exception is thrown if there is no such method. The result of
resolving is an index <code> i</code> into a method table. </P>
<P>Note that this entire process involves classes loaded by the current class
loader. These classes are supposed to be the runtime equivalents of the
classes used by the compiler when creating the class file, so this process
is analogous to what a compiler would have done in a statically-linked
language: identify the layout of the class on which a method is being invoked,
and determine the offset of the method in it. Note that: </P>
<BLOCKQUOTE>
<P><B><I>No "run-time" information (e.g., the actual <code> Class
</code> object corresponding to <code> o</code>) is used in this
process. </I></B></P>
</BLOCKQUOTE>
<P>Now that this offset has been determined, it is <I>assumed</I> that
this is a valid offset in the method table of the actual (run-time) class
of the object. The method description <I>assumed</I> to be at that offset
is then executed <A HREF="#Lindholm">[Lindholm 97, p267-8] </A></P>
<BLOCKQUOTE>
<P>The constant pool entry representing the resolved method includes an
unsigned <I>index</I> into the method table of the resolved class and an
unsigned byte <I>nargs</I> that must not be zero. </P>
<P>The <I>objectref</I> must be of type <I>reference</I>. The <I>index</I>
is used as an index into the method table of the class of the type of <I>objectref</I>.
</P>
</BLOCKQUOTE>
<BLOCKQUOTE> <P><FONT SIZE=-1><B>
<a name="Mtable"> Footnote:</a></B> On first glance,
it may seem that the index <code> k </code> could equally have
been used to index into the method table <code> M[B] </code> of
the resolved class <code> B </code>. However, that would be
incorrect.
The object being operated upon may actually be an instance of a
subtype <code> C </code> of the "compile-time" type <code> B
</code>. <code> M[C].k </code>, the entry at index <code> k
</code> in the method table for <code> C </code> may thus
contain a pointer to a piece of code that overrides <code>
M[B].k </code>, and it is <code> M[C].k </code> that should
execute, per the language rules detailed in <A HREF="#Gosling">[Gosling 96].</A></P>
For this technique to work, it is crucial that the index <code> k
</code> computed at link-time from the compile-time typename
<code> B </code> point to the "same" method in <code> M[C]
</code>. Therefore, the method lookup operation ---
which determines from a method signature and an object the piece
of code of that signature that should run on the object --- can
be optimized away at compile-time, as is standard for
statically-typed OO languages.
However, the notion of "method tables" --- and how they might be
computed, and how method lookup might be optimized away, and the
constraints that it imposes on method and field layout --- is not
discussed anywhere in <A HREF="#Lindholm">[Lindholm 97],</A>
a most regrettable oversight, particularly so because it will
turn out to be quite related to a <A HREF="#Fix"> proposed fix
</A> below.
</FONT></P> </BLOCKQUOTE>
<p> Here is where the problem becomes manifest: The
above scheme is a correct implementation strategy <B>exactly</B>
under the assumption that the class of the type of
<I>objectref</I> is <code> c</code>, the just-resolved
class. As we have seen, this assumption is not always true. </P>
<P>Therefore, type-spoofing arises as a consequence of the
particular way in which JVM instructions have been defined. Hence
it should arise in any valid implementation of the JVM spec. In
addition, Sun's JVM implementation uses certain "quick"
instructions to rewrite the opcode corresponding to the
invocation with the information obtained from method resolution.
This is crucial to avoid the cost of symbolic lookup on every
member access, and it makes sense under the assumption above,
since the information obtained from member resolution is
invariant under any operations on the JVM (e.g. the JVM does not
allow classes to be reloaded). But if the assumption is invalid
for a particular call, then the "quick" instructions
merely speed up an erroneous process. </P>
<P>However, it is clear that any reasonable implementation must
work to avoid incurring the constant pool resolution cost on
every member access. Therefore, an important consideration in
evaluating schemes to fix the type-spoofing problem has to be its
support for "quick" schemes. </P>
<H2><A NAME="Section 3"></A><FONT COLOR="#CC0000">Section
3. How can it be fixed? </FONT></H2>
<P>This particular failure of type-safety may be fixed in various
ways. One may consider enriching the notion of types that the
compiler works with to include also some static representation of
class loader identity. However, rather than modifying the Java
language, in the following I consider three ideas that tackle the
problem of repairing type-safety for Java at the level of the
JVM. </P>
<H3><A NAME="Allow only one class per FQN to be loaded in."></A><FONT COLOR="#CC0000">Allow
only one class per FQN to be loaded in. </FONT></H3>
<P>Type-spoofing cannot happen as long as every class loader L responds
to a <code>loadClass</code> request by performing a
<code>defineClass</code> on some appropriately obtained
bytes. Consequently, L will be asked to resolve
any type references within the class just loaded, and so on --- thus there
can be no possibility of an instance coming into L's world (that is, into
the state of an object that is an instance of a class loaded by L) which
is not an instance of a class loaded in L. And since L, like every other
class loader, guarantees that there is at most one loaded classfile for
every FQN, there can be no spoofing. </P>
<P>In a related vein, one may mandate a global consistency condition across
all classloaders: <I>for any given FQN, at most one class file can be loaded
into a JVM</I>. This can be achieved, for instance, by generating an exception
if any class loader attempts to call a <I>defineClass</I> for a FQN for
which a <I>defineClass</I> has already been called (regardless of the loader
involved). </P>
<P>This proposal has some merits. The notion of class loaders still makes
sense --- a particular class loader can still be used to enforce "name
space access" policies. Constant pool resolution can still be used
to trigger a request to the class loader to load a class --- which a class
loader is free to deny or service. </P>
<P>However, it will also make impossible some rather interesting
uses of class loaders that are currently permitted. Currently, it
turns out to be possible to define a class loader which can
redefine system objects, e.g. <code>java.lang.Object</code>, for the
classes loaded into it. This is of great use in cases (e.g. in
the design of <A HREF="#Matrix">Matrix</A>) where it is desired
to run arbitrary Java code unchanged, while guaranteeing some
additional properties (e.g. that the number of objects created by
the code is bounded). However this can only be accomplished if
there are two classes with the FQN <code>java.lang.Object</code>
loaded into the JVM: one is used in the name-space for the
application to provide the "controlled" version of
the type, and the other is used in some other loader to provide
the primordial class from which all other classes are
constructed. </P>
<UL> <P><FONT SIZE=-1><B>Footnote:</B> Some care has to be taken
in compiling these classes since the Java compiler --- unaware
that these two classes with the same FQN are going to be loaded
into different class loaders ... it has no conception even of
different class loaders!! --- may erroneously claim type
circularity. A simple solution is to transform the classfile
generated and splice in the correct superclass
manually.)</FONT></P> </UL>
<P>Schemes for security in a similar vein are also suggested in
<A HREF="#Wallach 97">[Wallach 97].</A> </P>
<H3><A NAME="Check for type-spoofing at run-time."></A>
<FONT COLOR="#CC0000">Modifying the semantics of the JVM. </FONT>
</H3>
<p>We consider now two proposals to fix this problem by fixing the
JVM. </p>
<h4><FONT COLOR="#CC0000">Check for type-spoofing at run-time.</FONT>
</h4>
<P>Java is often said to have a
"static" type-system. A more accurate term would
be "link-time" type system, since many type checks are
delayed till link-time (and almost no type-checks are performed
at run-time; here by run-time I mean the second or subsequent
invocation of an instruction). For instance, as discussed above,
symbolic references to methods are resolved into concrete offsets
into the method table only at link-time, after constant pool
resolution. If the method does not exist, an exception is
thrown. </P>
<P>One way of fixing the type-spoofing problem is to perform the check
for type-safety at runtime. Thus instructions such as <code>invokevirtual
</code>should check that the <code>Class</code> of the object being operated upon
is in fact the object generated by loading the classfile obtained by resolving
the type. If not, then an <code>IllegalReferenceException </code>should be thrown.In
essence it should not be possible for a class like <I><A HREF="#RT">RT</A></I>
to use static types to operate on an instance of <I><A HREF="#R">R</A></I>
--- in some sense the type corresponding to <I><A HREF="#R">R</A></I> should
be considered <I>hidden</I> in L' by <A HREF="#ersatz R1">ersatz <I>R</I></A>.
(However, it should continue to be possible for <I><A HREF="#RT">RT</A></I>
to operate on an instance of <I><A HREF="#R">R</A></I> through reflection
(that is, using the class object corresponding to <I><A HREF="#R">R</A></I>).
Such a use is type-safe since only the methods defined in <I><A HREF="#R">R</A></I>
can be used to operate on the instances of <I><A HREF="#R">R</A></I>.)</P>
<P>A natural question arises whether this run-time check can be
reduced to a link-time check. That is, would it work to just
check the use of the particular invokevirtual instruction first
time it is executed? The intuition would be that if the
first time around the <code> Class</code> of the object being
operated upon is identical to the class obtained by resolving the
type, the the instruction could be rewritten to the quick form of
the instruction. Subsequently the quick version would not need
to perform the runtime check. </P>
<P>This scheme cannot work, however, for there may be more than one sources
for the spoofed type. Using earlier terminology, there may be multiple
bridges, sharing the same receiving endpoint. Put the expression in a
method call, so now there is no link-time way of knowing whether or not all
or none of the executions of <code>invokevirtual</code> will generate errors:
</P>
<pre>
public callSpeakUp(R r) {
r.speakUp();
}
</pre>
<P>quick instructions may still be of some use however: Check if
the runtime class is the expected class, if so use the offset
stored in the quick instruction, else throw an exception.</p>
<H3><A NAME="Check types."></A>
<FONT COLOR="#CC0000">Check for type-equivalence not name-equivalence
</FONT> </H3>
<p> Run-time performance is a big drawback of the scheme
given above, though the additional flexibility of run-time typing
is considerable. </p>
<p>However, let us ask ourselves the question: why did the need for
run-time type-checking arise in the first place? Let us go back
and examine the canonical program:</p>
<PRE>> If we assume that this program text is to be understood
with FQNs resolved using current scope, then it is clear that the
<code>rr.get(R)</code> should return something of type
<code>(R,L')</code>, where <code>L'</code> is the classloader in
which <code>RT</code> is loaded. However, the method
<code>getR</code> defined in <code>RR</code> (which is of type
<code>(RR,L)</code> actually returns something of type
<code>(R,L)</code>, a different type! Therefore the method that
is being looked for here, namely a method named <code>getR</code>
of type <code> () -> (R,L')</code> does not actually exist in
class <code>(RR,L')</code> (which is the same as
<code>(RR,L)</code>). Therefore <a href="NoSuchMethodError">
method resolution </a> should <em> fail </em>, and a <code>
NoSuchMethodError</code> should be thrown.</p>
<p> This therefore is a general <A name="Fix"> fix </A> for this problem: use
<em> type-equivalence </em> instead of name-equivalence when resolving
methods and fields. Instead of comparing equality of method
descriptors, resolve the names that occur in the descriptors, and
consider the descriptors to be the same only if the resolved
names are identical. Thus, in this example, compare the
signatures <code> () -> (R, L) </code> and <code> () -> (R,L')
</code> instead of the descriptors <code> () -> R </code> and
<code> () -> R </code>. </P>
<p>We do not yet have a formal semantics for the JVM (though a
simple constraint-based typing scheme for Java and the JVM is
being developed for which it should be easy to establish
soundness). Here we can only argue informally for correctness.
Intuitively, with this fix, we will have the property that any
location <code> l</code> with typename <code>N</code> (e.g. local
variable) created from a class <code>C</code> can only store
objects whose type is <code>(N, L)</code> where <code>L</code> is
the classloader that <code>C</code> was loaded in. Thus it is as
if the code executing at run-time is obtained from the code at
compile-time by uniformly replacing the names <code>N</code> by
the types <code>(N,L)</code>. If at compile-time the constraints
on types generated from a class were consistent when type-names
were substituted for types, then at run-time these constraints
should be consistent with <code>(name, CL)</code> pairs being
substituted for the types --- or else a linkage error would
occur. (One can think of these errors being discovered through
propagation of equality constraints between types; when a
classloader <code>L</code> forwards a request to load a class
<code>C</code> to a loader <code>L'</code>, it is as if it is
publishing the constraint <code>(C,L) = (C,L')</code>. Link time
type-checking is merely propagating the consequences of a
conjunction of such constraints.) Thus compile-time
type-consistency should "parametrically" translate to run-time
type-consistency. This argument needs to be made precise.</p>
<p>An attractive property of this fix is that there is no run-time
cost, since constant pool resolution is a link-time
activity. Thus this appears to be the appropriate fix for this
problem. </p>
<H4><FONT COLOR="#CC0000"><A NAME="MTComp"> Implications for method table computation. </A></font></H4>
<p> An important implication of uniformly using type-equivalence
rather than name-equivalence is worth describing explicitly,
since it highlights some subtle interactions. </p>
Consider the code:
<pre>
class B {
void m(T a) {..code1...}
}
class C extends B {
void m(T a) {...code2...}
}
class D {
void r(B b) {
b.m(new T());
}
void s() {
r(new C());
}
}
</pre>
<p>Now consider two class loaders <code> L</code>and
<code>L'</code> such that (in our earlier terminology) <code>
cl(m(L)(B))=L', cl(m(L)(C))=L</code> and further <code>
cl(m(L)(T)) =/= cl(m(L')(T)).</code> That is, <code> B</code> and
<code>C</code> are loaded into different class loaders, and the
two classloaders differ on how they interpret <code>T.</code>
Suppose <code> D </code> is loaded in <code> L'.</code> In this
case, the call to <code> b.m </code> will resolve at type <code>
(T, L') -> void </code> and will obtain the offset corresponding
to <code> code1.</code> Suppose <code> D</code> is loaded in
<code> L.</code> In this case, the resolution of <code>
b.m</code> at type <code> (T, L) -> void</code> will yield a <code>
MethodNotFoundError</code>. In neither case will <code> code2
</code> be considered to have overridden <code> code1 </code>.
This is the case even if at runtime, as in the case of the call
from within <code> s</code>, the actual argument passed into
<code>r</code> is an instance of a class with typename
<code>C.</code>
<p> An implication of this example is that type information, rather than just
typename information, must be taken into account at the time that
the method table for a class is built. In detail, when a loader
<code> L</code> is ready to create an instance of class <code> C</code> that inherits
from <code> B</code>, <code> L</code> must determine the method
table of <code> C</code> given that of <code> B</code>. In
order to do so, the typenames that occur in the arguments of
methods defined in <code> C</code> must be resolved, so that it
can be determined whether <code> L</code> and the classloader
for <code> B</code> agree on their interpretation. (Two
classloaders <code> L</code> and <code> L'</code> agree on
the interpretations of a name <code> N</code> if they both map
<code> N</code> to the same <code> Class</code>
object.)</p>
<p>The requirement to resolve method typenames when a method table
is to be constructed for a class may be considered somewhat
onerous. It requires "preloading" some classes (the classes
corresponding to argument types of methods). Three points are to
be made here.
<p> First, preloading is needed only if the class is not already
loaded --- as more and more classes get loaded over time, the
number of classes that would need to be preloaded should
decrease.</p>
<p> Second, preloading is necessary only if the parent class has
been loaded into a different class loader. If it is loaded into
the same loader, then by definition the types associated with the
same name in the constant pools of both classes will be the same.
For most (perhaps even almost all) classes, this will be the
case. </p>
<p> Third, it is not necessary to perform any of the operations
with the preloaded code (e.g. preparation, initializaton,
verification etc). Rather, an even weaker notion than
interpretation-equivalence --- <em> definer-equivalence </em> ---
can be used. For a classloader <code> L</code> and name <code> N
</code>, define <code> D(L, N)</code> to be the classloader whose
<code> defineClass</code> operation will yield the <code>
Class</code> object that <code> L</code> will return when asked
to resolve <code> N</code>. Then, all that is needed is to
determine, for each relevant <code> N</code>, whether <code> D(L,
N) = D(L', N)</code>. </p>
<p> As an aside, it is not very difficult to design a protocol
between the JVM and the classloader which allows the JVM to
deduce definer-equivalence information in a reliable way. When
the JVM needs to obtain <code> D(L, N)</code> information, it
calls a (user-definable)
<pre>
java.lang.ClassLoader definingLoader(String n)
</pre>
method on <code> java.lang.ClassLoader</code> object <code>
L</code> with argument <code> N</code>, recording the result in
an internal table. This table may now be used to resolve
definer-equivalence questions. Subsequently, when the JVM has need
(e.g. through the constant pool resolution process), to resolve
<code> N</code>, it will call
<pre> Byte[] loadBytes(String)
</pre>
operation on the object previously recorded, and perform
an internal <code> defineClass</code> operation to obtain the
class object.
</p>
<UL> <P><FONT SIZE=-1><B>Acknowledgement:</B> Thanks to Gilad Bracha for
clarifying discussions on this point, and for suggesting that an
explicit discussion here would be appropriate.
</font></ul></p>
<H4><FONT COLOR="#CC0000"> Implications for name
space coordination. </font></H4>
<p>A consequence of this fix is that the responsibility for avoiding
link-time type-errors now falls on the class-loaders. If they are
to share a type (e.g. <code>RR</code>), then they must arrange to
share all types referenced in that type (e.g., <code> R</code>),
otherwise link-time errors will be generated. Crucially, the JVM
will not crash --- only link-time errors will be generated,
which, in some sense, is the best that can be expected. It is not too
difficult to devise "type-publication" schemes (as we have done
for <a href="Matrix"> Matrix </a> by which
class-loaders can cooperate (by dynamically sharing appropriate
parts of their name spaces) so that link-time type-errors can
also be avoided. More details will be developed in a fuller
version of this paper. </p>
<p>A final remark. If this solution were to be taken to be the
one that Java designers had in mind, it is rather surprising that
there is such a big gap between the type-expressiveness of Java
and what is possible with classloaders. In essence, the notion of
classloaders has not been reified in the type-structure of the
language --- it remains strictly under the hood. The only
programs that can be written in Java (the language as it now
stands) are those that are "uniformly parametric" over
classloaders (that is they work the same way in all
classloaders), and that cannot statically refer to types other
than in the current classloader. I do not view either of these
conditions as necessary for what I take to be a real technical
contribution of Java designers, namely, link-time
type-checking. For instance it should be possible to define
link-time type-checkable schemes which allow a class to impose
certain constraints on "foreign types", e.g. requiring that they
be mutually consistent (i.e., come from the same classloader).
This view of a classloader as imposing a certain consistency
condition on type-resolution needs to be developed more fully.
</p>
<H2><A NAME="Section 4."></A><FONT COLOR="#CC0000">Section 4. Conclusion
</FONT></H2>
<P>Java is a big, paradigm-forming leap forward for the C/C++
family of languages. It is clean enough that formal analyses of
the language (and its type system) can be contemplated, and rich
and powerful enough that large (distributed) systems development
can be supported. Even more importantly, its elegance makes it a
pleasure to program in.</P>
<P>Nevertheless, it is a new language being developed with breakneck speed,
sometimes in areas which are not yet clearly understood by researchers.
A rigorous, perhaps even formal, analysis of the language, focusing on
its security properties seems urgently called for. Otherwise we will continue
to have the spectre of subtle, but potentially fatal, design flaws hovering
over our heads.</P>
<P><FONT COLOR="#CC0000">Related work. </FONT>Some brief comments about
related work. Recently there has been much interest in security for Java.
<a href="">Javasoft's security FAQ</a> contains
information their status on security-related bugs they know of currently.
<a href="">The Kimera project</a> has developed
their own bytecode verifier and is using some weak methods to probe for
flaws in Javasoft's bytecode verifier. In addition, they are working on
a security architecture for Java. <a href="">The
Secure Internet Programming group</a> at Princeton has explored a variety
of security-related issues. The <a href="">Java
Security: Hostile Applets, Holes, and antidotes</a> contains a very
readable account of recent work on security bugs in Java. </P>
<P>Classloaders have come under some scrutiny recently. The so-called Princeton
class-loader attack involves a hostile class-loader that responds with
different class objects to queries for the same name. This has been neutralized
by keeping the table mapping names to classes internal to the JVM --- the
JVM now guarantees that it will call a loader at most once for any given
name. The Hopwood tag-team applet attack is described above (building an
indirect bridge). The attack apparently used to work because classcasting
of exceptions and interfaces was not implemented correctly in earlier versions
of Java. The technique for subverting the type system described above is
more insidious in that it does not rely on any classcasting. </P>
<P> After I circulated this note, some earlier related work was
brought to my attention. Drew Dean remarked that he had made this
realization in January 97, after someone posted a program on a
news group, which implied this problem. He has since developed
some ideas for fixing this problem.
</p>
<p> In his ECOOP '96 tutorial, Martin Odersky noted that multiple
classes with the same name can be loaded at once in different
classloaders and are treated as "the same type". This is not
strictly true, since as we have seen above, different instructions
behave differently, some (such as checkcast) are sensitive to
(typename, loader) information, and some only to typename
information. He also noted that private variables can be accessed
by declaring them public in a clone class. Indeed, there seems to
be a "related" bug in JDK in which public access (from classes
loaded from the null classloader) to private methods is not
checked by the Javasoft verifier. (This privacy violation was
also pointed out to me by Nevin Heintze.) </p>
<H2><A NAME="Bibliography"></A><FONT COLOR="#CC0000">Bibliography </FONT></H2>
<P><A NAME="Lindholm"></A>[Lindholm 97] Tim Lindholm and Frank Yellin "The
Java Virtual Machine Specification", Addison-Wesley,
1997. </P>
<P><A NAME="Gosling"></A>[Gosling 96] James Gosling and Bill Joy
and Guy Steele "The Java Language Specification",
Addison-Wesley, 1996. </P>
<P><A NAME="Matrix"></A>[Saraswat 97] Vijay Saraswat "The Matrix of
Virtual Worlds", AT&T Research, manuscript, July 1997.</P>
<P><A NAME="Wallach 97"></A>[Wallach 97] Dan S. Wallach, Dirk Balfanz,
Drew Dean, Edward W. Felten "Extensible security architectures for
Java", Technical Report 546-97, Department of Computer Science, Princeton
University, April 1997. <A HREF="">Online
version. </A></P>
<H2><A NAME="Appendix: Code"></A><FONT COLOR="#CC0000">Appendix: Code listing</FONT></H2>
<P>Place in the current directory the (.class) files for: Test, (the real)
R, RR, DelegatingLoader, LocalClassLoader. Make sure the current directory
is on CLASSPATH. </P>
<P>Place in ./ersatz the (.class) files for: (ersatz) R, RT, RT2, RT3.
</P>
<PRE><A NAME="LocalClassLoader"></A>// LocalClassLoader.java
import java.lang.*;
import java.util.*;</PRE>
<PRE>import java.lang.reflect.*;
import java.io.*;
/** Defines a Class Loader that knows how to read a class
* from the local file system.
*/
public abstract class LocalClassLoader extends java.lang.ClassLoader {
private String directory;
public LocalClassLoader (String dir) {
directory = dir;
}
protected Class loadClassFromFile(String name, boolean resolve)
throws ClassNotFoundException, FileNotFoundException {
File target = new File(directory + name.replace('.', '/') + ".class");
if (! target.exists()) throw new java.io.FileNotFoundException();
long bytecount = target.length();
byte [] buffer = new byte[(int) bytecount];
try {
FileInputStream f = new FileInputStream(target);
int readCount = f.read(buffer);
f.close();
Class c = defineClass(name, buffer, 0, (int) bytecount);
if (resolve) resolveClass(c);
System.out.println("[Loaded " + name + " from " + target + " ("+ bytecount + " bytes)]");
return c;
}
catch (java.lang.Exception e) {
System.out.println("Aborting read: " + e.toString() + " in LocalClassLoader.");
throw new ClassNotFoundException();
};
}
}
</PRE>
<PRE>//<A NAME="Test"></A> Test
import java.lang.reflect.*;
/** Test harness for classloader examples. Loads the user class into
* a newly constructed DelegatingLoader.
*/
public class Test {
DelegatingLoader loader;
public void doIt(String argv[]) {
try {
if (argv.length < 1) {
System.out.println("Usage: java Test <package>");
return;
}
String target = argv[0];
this.loader = new DelegatingLoader("ersatz/");
Class c = this.loader.loadClass(target, true);
Object [] arg = {};
Class [] argClass = {};
c.getMethod("main", argClass).invoke(null, arg);
} catch (Exception e) {
System.out.println("Error " + e.toString() + " in Test.doIt.");
}
}
public static void main(String argv[]) {
Test t = new Test();
t.doIt(argv);
}
}
</PRE>
<PRE>// RT3
public class RT3 {
public static void main() {
try {
System.out.println("Hello...");
System.out.println("Going to attempt to read a field that exists in the ersatz class but not the real class...");
RR rr = new RR();
R r = rr.getR();
System.out.println(" r.s is " + r.s + ".");
System.out.println("...bye.");
} catch (Exception e) {
System.out.println("Exception " + e.toString() + " in RT3.main.");
}
}
}
</PRE>
<P></P>
</BODY>
</HTML> | http://packetstormsecurity.org/files/16239/bug.html.html | crawl-003 | refinedweb | 10,662 | 53.51 |
This procedure is my solution method...
Take an upgrade_export file from the source SMC and import it to your vm machine with the same name and upgrade it to the version u want.
This is a MNG so you cant export and import it to a standalone firewall machine,
lets fake the system that its also a firewall with the command
# cpprod_util FwSetFirewallModule 1
check it via # cpprod_util FwIsFireWallModule
close SmartDashboard and relogin, you will see the firewall tab.
take a new upgrade_export for the utm box
You have to install the appliance as full HA primary cluster member and then,
# cp_conf fullha disable disable its cluster membership...
import the config reboot and
# cp_conf fullha enable to set it back to fullhacluster
Thats it, Goodluck
Cagdas | http://cagdasulucan.blogspot.com/2012/08/how-to-upgrade-software-and-migrate.html | CC-MAIN-2017-47 | refinedweb | 126 | 54.36 |
29783/hyperledger-fabric-pem-encoded-certificate-is-required
I am trying to access the remote peer from SDK using Hyperledger Fabric using following code
var peer = new Peer('Remote path', PemFile name)
it is giving me error that Error: PEM encoded certificate is required.
Hey, the syntax you are using is wrong. The right syntax is:
var peer = newPeer('Remote Path', { pem: 'PEM file name' })
Hyperledger client SDK is a component used ...READ MORE
Firstly, your web application will interact with ...READ MORE
Since it is a private blockchain platform, ...READ MORE
The consensus is achieved in the ordering ...READ MORE
Summary: Both should provide similar reliability of ...READ MORE
This will solve your problem
import org.apache.commons.codec.binary.Hex;
Transaction txn ...READ MORE
To read and add data you can ...READ MORE
Let me explain with an example. Suppose ...READ MORE
The transactions in the network is ordered ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/29783/hyperledger-fabric-pem-encoded-certificate-is-required | CC-MAIN-2020-05 | refinedweb | 160 | 60.11 |
I've spent the last 2 days staring at as many CGI / webapp frameworks as I could:
being a fan of clean MVC designs, the classes become the controllers
... and CGI::Prototype a sort of "archetypal" controller.
$next_page->render;
[download]
sub activate {
my $self = shift;
eval {
$self->prototype_enter;
$self->app_enter;
my $this_page = $self->dispatch;
$this_page->control_enter;
$this_page->respond_enter;
my $next_page = $this_page->respond;
$this_page->respond_leave;
if ($this_page ne $next_page) {
$this_page->control_leave;
$next_page->control_enter;
}
$next_page->render_enter;
$next_page->render;
$next_page->render_leave;
$next_page->control_leave;
$self->app_leave;
$self->prototype_leave;
};
$self->error($@) if $@; # failed something, go to safe mode
}
[download]
I said to focus on $next_page->render because that is
what I will demonstrate from a practical perspective. But as you can
see any aspect of the HTTP response cycle can be handled in an
object-oriented fashion.
I stared in utter confusion at every single framework above. I looked
at Catalyst subroutines, Jifty actions, Mason components, and
so on. And in each case, they seemed to miss the magick of merlyn's
methodic approach to web application control.
With CGI::Prototype, it is very easy to create a "family" of
actions and have them derive behavior from each other.
But enough talk. Let me provide a simple concrete example.
->render
[download]
package Gimble::Page::Login::Base;
use base qw(Gimble::Page::Base);
sub engine {
my ($self,$tree) = @_;
$self->snip_validate($tree);
$tree
}
sub template { require html::login; html::login->new }
1;
[download]
Of course there are other logic tasks in a CGI application - dispatch,
authentication, authorization, to name a few. But having had
experience with many CGI / webapp frameworks, I think merlyn
describes exactly how CGI::Prototype fits into the picture
perfectly:
Create a CGI application by subclassing
Of course, it needs a Moose rewrite...
Now what happened? I had written a few CGI apps using CGI::Application. Then they turned the k0der loose to do his own. And guess what? He stuck everything for a particular CGI action in each subroutine. Now we have a 300k .pm file.
Now, refactoring this is going to lead to merge conflicts. If he had been forced into the CGI::Prototype mode of "creating an application by subclassing" he would have had to partition his spaghetti brainfuck into separate modules and we could have a developer per module and no merge conflicts to sort out.
CGI::Application was a great step away from the HTML::Mason / Embperl approach to web application flow control. In my opinion, the next improved step is CGI::Prototype, having done my best to understand the merits of other CGI / web app frameworks, be they big or small, popular or unpopular!
And yes, had I started today, I would have done it all with Moose... a lot of things that I had to lean pretty heavily on Class::Prototyped for, almost to the point of breaking it, would have been simpler in Moose. In fact, I remember asking for prototype-style inheritance in Moose, to be told "it's possible, but we haven't done it yet". But that was two years ago.
If I wasn't so busy pushing Seaside for my newest web apps, I'd still be building on CGIP.
-- Randal L. Schwartz, Perl hacker
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119.
As such, I have reserved the namespace CGI::Class but not released anything to CPAN.
It's not as obvious as the CGI::Prototype from my perspective. But given the user support for Catalyst, there is always help getting | http://www.perlmonks.org/index.pl?node_id=786745 | CC-MAIN-2015-35 | refinedweb | 602 | 53.41 |
Simplify your code with mbed-events
In mbed OS 5.2, we introduced mbed-events, an eventing system that can run in an RTOS thread. Using an event loop is very useful to defer execution of code to a different context. An example would be to defer execution from an interrupt context (ISR) to the main loop, or to defer execution from the high-priority thread to a lower priority thread. Now that mbed-events is part of mbed OS 5.2, we'd like to show how this can be used to improve your applications.
For more information about the mbed-events library, have a look at the documentation. All code in this blog post was tested against mbed OS 5.2.3.
Calling printf in an interrupt context
The following program has probably been written by anyone learning how to program microcontrollers. It registers an interrupt handler when a button is pressed, and then calls
printf from the ISR.
Naive approach
#include "mbed.h" DigitalOut led(LED1); InterruptIn btn(SW2); void do_something() { led = !led; printf("Toggle LED!\r\n"); // CRASH! Blocking call in ISR... } int main() { btn.fall(&do_something); while (1) { } }
When you compile this code with ARMCC, the program will crash right after toggling the LED. This is because calls to stdio (like
printf) are guarded by mutexes in the ARM C standard library, and mutex functions cannot be called from an ISR. We can get around this by signalling the main thread from the ISR and do the
printf call in there. That's especially confusing when teaching beginners, as now we need to explain the concept of Semaphores or Mailboxes as well.
Using a Semaphore
#include "mbed.h" DigitalOut led(LED1); InterruptIn btn(SW2); Semaphore updates(0); void do_something() { // release the semaphore updates.release(); } int main() { btn.fall(&do_something); while (1) { // wait for the semaphore to be released from the ISR int32_t v = updates.wait(); // now this runs on the main thread, and is safe if (v == 1) { led = !led; printf("Toggle LED!\r\n"); } } }
While this works, it's a lot more unclear, and we need to build a state machine to determine why the semaphore was released if we're adding more interrupts. Preferably we'd also run this in a separate thread.
With mbed-events we can easily spin up a new RTOS thread with the event loop running in it, and we can defer from ISR to that thread in one line of code.
Using mbed-events
#include "mbed.h" DigitalOut led(LED1); InterruptIn btn(SW2); // create an event queue EventQueue queue; void do_something() { // this now runs in the context of eventThread, instead of in the ISR led = !led; printf("Toggle LED!\r\n"); } int main() { // create a thread that'll run the event queue's dispatch function Thread eventThread; eventThread.start(callback(&queue, &EventQueue::dispatch_forever)); // wrap calls in queue.event to automatically defer to the queue's thread btn.fall(queue.event(&do_something)); while (1) {} }
When the interrupt fires, it now automatically defers calling the
do_something function to the other thread, from where it's safe to call
printf. In addition, we don't need to taint our main thread's main loop with program logic.
Manually deferring from ISR to a thread
The downside of this approach is that both the toggling of the LED and the
printf call are now executed outside the ISR and thus are not guaranteed to run straight away. We can work around this by toggling the LED from the ISR, then manually deferring the printf event to the thread.
#include "mbed.h" DigitalOut led(LED1); InterruptIn btn(SW2); EventQueue queue; void do_something_outside_irq() { // this does not run in the ISR printf("Toggle LED!\r\n"); } void do_something_in_irq() { // this runs in the ISR led = !led; // then defer the printf call to the other thread queue.call(&do_something_outside_irq); } int main() { Thread eventThread; eventThread.start(callback(&queue, &EventQueue::dispatch_forever)); btn.fall(&do_something_in_irq); while (1) {} }
Mixing high priority and low priority events
We can differentiate between the importance of events by using multiple threads that run with different priorities. We can easily add a Ticker to the program which toggles
LED2 every second, which runs with a higher priority than the
printf calls by creating a second event queue.
#include "mbed.h" DigitalOut led1(LED1); DigitalOut led2(LED2); InterruptIn btn(SW2); EventQueue printfQueue; EventQueue eventQueue; void blink_led2() { // this runs in the normal priority thread led2 = !led2; } void print_toggle_led() { // this runs in the lower priority thread printf("Toggle LED!\r\n"); } void btn_fall_irq() { led1 = !led1; // defer the printf call to the low priority thread printfQueue.call(&print_toggle_led); } int main() { // low priority thread for calling printf() Thread printfThread(osPriorityLow); printfThread.start(callback(&printfQueue, &EventQueue::dispatch_forever)); // normal priority thread for other events Thread eventThread(osPriorityNormal); eventThread.start(callback(&eventQueue, &EventQueue::dispatch_forever)); // call blink_led2 every second, automatically defering to the eventThread Ticker ledTicker; ledTicker.attach(eventQueue.event(&blink_led2), 1.0f); // button fall still runs in the ISR btn.fall(&btn_fall_irq); while (1) {} }
Conclusion
mbed-events makes it a lot easier to defer calls from one context to another, whether it's from an ISR back to a user thread, or from one thread to another. It also makes it easy to prioritise certain events over other events, and does not require you to write your own state machine or taint your main loop. Since it's a one-liner (wrap the callback in
queue.event()) to wrap a call that would normally run in an ISR, it's also very friendly for beginners.
For more information see the documentation.
-
Jan Jongboom is Developer Evangelist IoT at ARM and does not like to explain Semaphores during workshops.
Please log in to start a discussion or ask a question. | https://developer.mbed.org/blog/entry/Simplify-your-code-with-mbed-events/ | CC-MAIN-2017-09 | refinedweb | 955 | 57.06 |
There are a variety of workflows that docassemble developers can use. Which one is best for you will depend on your circumstances.
Workflow for a quick start
If you are new to docassemble, we recommend that you start by
installing docassemble on your personal laptop or desktop using
Docker. Then you can access docassemble at.
You can log in using the default username of
admin@admin.com and the
default password of
password. After you change your password, you
can use the menu in the upper-right hand corner to navigate to the
Playground, where you can try modifying the default interview, or go
through the steps of the tutorial.
Using the Playground, you can start developing and testing interviews of your own, with the help of the documentation and the examples area.
Workflow for speedy development
The Playground allows you to edit your interview in the browser and then immediately test the interview by pressing “Save and Run.”
Even when you are in the middle of testing an interview, you can make
changes to the interview source, reload the screen in the tab of your
web browser containing your test interview, and immediately see the
effect of your changes. (Note, however, that there are some
circumstances when you will need to backtrack or restart your
interview to see changes, for example if you change a
mandatory
block that your interview has already processed.)
If you are using DOCX templates and you are making frequent changes to your DOCX template, you may find it cumbersome to repetitively save and upload the template. You can make this process faster by configuring Google Drive integration. That way, you can see all of the files in your Playground in your Google Drive folder on your hard drive, and can edit them there. Then, when you are ready to test your interview, press the “Sync” button to synchronize your Playground with your Google Drive.
You may also wish to use Google Drive integration if you have a favorite text editor that you like to use to edit text files like YAML interview files and Markdown templates.
Workflow for upgrading docassemble
As you continue to use docassemble, you will probably want to take advantage of updates to the software. To see what version you are running, go to “Configuration” from the menu. You can find the current version of docassemble on the PyPI page or the GitHub page.
Most docassemble software upgrades can be accomplished by going to “Package Management” from the menu and clicking the “Upgrade” button.
However, sometimes new versions of the docassemble software require an update to the whole system. You will see a notification on the screen if the underlying system needs an upgrade. The problem with doing an update to the underyling system is that if your user profiles and Playground data are stored in the docassemble Docker container, then removing and reinstalling the container will delete all that data.
You can back up your Playground data by creating a package containing all of your work product, then downloading that package as a ZIP file. You can then stop and remove the Docker container, pull the latest version, run a new version of docassemble, and upload that ZIP file into the Playground on the new system. This will restore your Playground work product, but it will not keep your user profiles or any data from interview sessions.
There are other, less cumbersome ways to ensure that your Playground data and other data persist through the process of removing and reinstalling the Docker container:
- You can sign up with Amazon Web Services and create an S3 bucket to store the contents of your Playground, so that the contents persist “in the cloud” after you remove the docassemble container. This requires figuring out how AWS and its access keys work. AWS is a bit complicated, but this is a good learning curve to climb, because AWS is used in many different contexts. A big advantage of transitioning to S3 storage is that you can continue to use your personal laptop or desktop, but when you want to transition your docassemble server to the cloud, the process of transitioning will be seamless.
- Instead of using S3, you could use Azure blob storage, another cloud storage service.
- Instead of storing your information in the cloud, you could store it in a Docker volume on the same computer that runs your Docker container. The disadvantage is that the data will be located in a hard-to-find directory on the computer’s hard drive, and if you want to move docassemble to a different server, you will need to manually move this directory.
To transition to using S3 for persistent storage, you need to create
a bucket on S3, add an
s3 directive to your configuration
that refers to the bucket, and then immediately stop the container
and start it again. Similarly, to transition to
Azure blob storage, you need to create a container on the
Azure Portal, add an
azure directive to your configuration
that refers to the container, and then immediately stop the
container and start it again.
Transitioning to using a Docker volume for persistent storage is not as seamless. Start by creating a package in your Playground containing all of the work you have developed so far. Then download this package as a ZIP file. This will back up your work. Then you can stop and remove the container, pull the new docassemble image from Docker Hub, and run it with the configuration necessary to use one of the above data storage techniques. Then, log in to the Playground, go to the packages folder, and upload the ZIP file. You will need to recreate your user accounts on the new system.
Once you set up persistent storage, all you need to do to upgrade the full system is stop your Docker container, remove it, pull the new image from Docker Hub, and run the new image. Your user profiles, Playground data, and installed packages will automatically appear in the new container.
Workflow for manual testing
Manual testing of interviews should be part of your workflow. Automated testing is also important – there is a separate section on that – but you need to put yourself in your user’s shoes to see how your interview operates. People other than yourself should also try out the interviews, because they will likely use the system in a different way than you do and thereby uncover problems that you would not encounter.
If your development server is accessible over the network, you can involve testers in your interview while it is still in the Playground. Every interview in the Playground is accessible at a hyperlink. To get this hyperlink, right-click on the “ Share” button in the Playground, copy the URL to your clipboard, then paste the URL into an e-mail to your testers.
If your development server is your desktop computer, and you access it
in your browser at, other users will not be able to
run your interviews by going to. However, if you
can figure out your computer name, and if your computer’s firewall
does not block access to the HTTP port (port 80), then other people
should be able to access docassemble at a URL like or.
If you have testers who do not have access to your local area network, you should consider putting your development server on a server on the internet. If you run docassemble on your desktop computer, you could configure your firewall to direct traffic from an external IP address to your desktop, but for security reasons this is probably not a good idea. It is better to put your docassemble server on a dedicated machine (or virtual machine) that is connected to the internet. When you do so, you should enable HTTPS so that passwords are encrypted.
If you are using a local machine for hosting but using S3 or Azure
blob storage for storage, moving from a local server to a cloud
server is relatively easy because your configuration and data is
already in the cloud. You just need to stop your local Docker
container and then start a Docker container on the cloud server
using environment variables that point to your persistent storage in
the cloud (e.g.,
S3ENABLE,
S3BUCKET,
AZUREENABLE,
AZUREACCOUNTNAME,
AZURECONTAINER, etc.).
If you are not using cloud storage or Docker volumes, you can move your server from your local machine to a machine in the cloud using Docker tools. You will need to stop your container, commit your container to an image, save the image as a file, move the file to the new server, load the file on the new server to create the image there, and then run the image.
Production environment workflow
Separating production from development
If end users are using your interviews, you will need to make sure that they are reliable, so that your users do not encounter the types of problems that tend to appear unexpectedly in a development environment.
Therefore, it is recommended that you run two servers:
- a development server; and
- a production server.
On your development server, you will make sure your interviews run as
intended, and then you will put your interview into a package and
save that package somewhere: on PyPI, on Github, or in a ZIP file.
You will then install that package on the production server by
logging into the production server as an administrator and going to
“Package Management” from the menu. Your users will access the
interviews at links like,
where
docassemble.example.com is the address of your production
server,
docassemble.bankruptcy is the name of your package, and
chapter7.yml is the main YAML file of your interview.
This way, your users will always see a “stable” version of your software. When you are actively developing an interview, you never know when a change that you make might have unanticipated side effects.
To minimize the risk that your end users will see errors, you should make sure the development server and the production server are as similar as possible. Ideally, they should both be running the same version of docassemble, they should both have the same configuration, except for minor differences like server name, and they should both have the same set of Python packages installed, with the same version numbers for each package. This protects against the risk that an interview will fail on your production server when it works without a problem on your development server.
For example, if you forget to specify a Python package as a dependency in your docassemble extension package, your package will still work on the development server even though it will fail on the production server. Problems could also occur if your interview depends on a configuration setting that exists on your development server but not on your production server. There could be other, hard-to-predict reasons why an interview might work on one server but not on another. If you ensure that your development server is virtually identical to your production server, you will protect against these types of problems.
It is also important to separate the development server and the production server because there is a risk that the process of developing a new interview could interfere with the operation of existing interviews. A docassemble user who has developer privileges can run any arbitrary Python code on the server, can install any Python package, and can change the contents of many files on which docassemble depends for its stable operation. A user who has administrator privileges can edit the configuration, and it is possible to edit the configuration in such a way that the system will crash.
Since a development server is often used for experimentation, it can be difficult to keep its configuration matched with that of the production server. It may be easier to use three servers:
- a development server where you develop interviews using the Playground,
- a production server; and
- a testing server which is virtually identical to the production server and exists primarily to test the installation of your interview packages to make sure they work as intended before you install them on the production server.
It is a good idea to use the
metadata block or the README area
of your package to make a note about where the original development
files are located. For convenience, you may find yourself using
multiple servers for development and experimentation, and if time
passes, you may forget where the authoritative version of the package
lives.
Managing the production upgrade process
Since docassemble sessions can be saved and resumed later, it is possible that a user could start an interview in January, log out, and then you upgrade the software behind that interview in February, and then the user logs back in again in March.
This could lead to problems. Suppose that in the first version of
your interview, you had a variable named
recieved_income. But in
the second version of the interview, you changed the name of the
variable to
received_income. If the user had already answered the
question that defined
recieved_income, then when they log in and use
the second version of the interview, they may be asked the same
question again, since
received_income is not defined in their
interview answers.
Or, if the user started an interview in December, and then resumed it in January, but in the meantime an applicable law changed, the interview may have made legal determinations that are now outdated and need to be reconsidered.
So if you will be upgrading your software as your users are using it, you will need to be careful about ensuring that your changes are “backwards-compatible.”
There are a variety of techniques that you can use to prevent problems caused by software updates.
- You could include a version number in your package. So if users start using the interview
docasemble.bankruptcy102:data/questions/controversy.yml, you can upgrade your software by publishing
docasemble.bankruptcy103:data/questions/controversy.yml, and the users with existing sessions will continue to use version 102.
- When you upgrade, you can add a
mandatorycode block early on in your interview that performs upgrade-related functions, like renaming the variable
recieved_incometo
received_income.
- In every version of your interview, you can include a
mandatorycode block that sets a variable like
interview_versionto whatever the current interview version is. Then, if the user resumes an old session, your code can be aware of the fact that the session was started under the old version.
Workflow for collaboration
Sharing files with Google Drive
If you are working as part of a team of developers on a single interview, you can use Google Drive integration so that all members of the team share the same Playground, even though you log in under different accounts. One developer would set up Google Drive integration, and then share his or her “docassemble” folder with the other developers. The other developers would then set up Google Drive integration and select the shared folder as the folder to use. If more than one developer tries to edit the same file at the same time, there will be problems; one developer’s synchronization may overwrite files another developer was editing. However, if the interview is split up into separate files, and each developer works only on designated files, this should not be a problem.
It is important that developers use different docassemble accounts to log into the Playground. If two web browsers use the Playground at the same time, there is a danger that one developer’s changes could be erased by another developer’s activity.
Using version control
As you work on interview development, you should use version control to track your changes.
If you enable the GitHub integration feature, you will have a “GitHub” button on your packages folder page. Every time you want to take a snapshot of your code, press the “GitHub” button, type a “commit message” that describes what changed in the latest snapshot, and then press “Commit.” Your changes will be “committed” to your package’s repository on GitHub.
You can also bring files from a package’s GitHub repository into the Playground using the “Pull” button.
This enables a workflow like the following (assuming you know how to use git):
- Start a package in the Playground.
- Push the package to GitHub using the “GitHub” button in the packages folder.
- On your computer, clone the GitHub repository and make changes to the package by editing files with a text editor, by copying files into the
datafolders, or other means.
- When you want to use the Playground again for testing, push your changes to GitHub, and then go into the packages folder and use the “Pull” button to bring the updated package files into the Playground.
This also facilitates collaboration:
- You could do all your development in the Playground, while committing snapshots to GitHub as you go.
- If another person has an idea for a change to your package, he or she could open a pull request on the GitHub repository for your package.
- If you like the changes that person made, you could merge the pull request on GitHub, and then to bring the changes into your Playground, you could press the “Pull” button.
Using separate packages
Developers can work independently while still working collaboratively.
The open-source software community does this all the time: for
example, one Python developer will create a package, and then other
developers will make that package a “dependency” for their own
packages and
import it into their code. The initial developer can
continue to make improvements to the software package, and the other
developers can take advantage of these changes. Every time the
developers reinstall their own packages, Python downloads and
installs the latest version of the dependencies. The other developers
can use the first developer’s code without needing to copy and paste
it, or even look at it.
This kind of collaboration is possible among docassemble interview developers as well, since interviews can be uploaded as Python packages to PyPI and GitHub.
- Developer One creates an interview, packages it, and presses the “PyPI” button to upload the package to PyPI as
docassemble.bankruptcy.
- Developer Two, using a different docassemble server, goes to “Package Management” from the menu and installs the
docassemble.bankruptcypackage from PyPI.
- Developer Two then develops an interview file that makes reference to files in the
docassemble.bankruptcypackage. For example, the interview might
includethe file
docassemble.bankruptcy:data/questions/common_questions.yml, a file that contains some standard
questions that might be asked of a debtor.
- Developer Two then goes to the packages folder of the Playground, creates a package called
debtconsult, and makes
docassemble.bankruptcya dependency of that package.
- Developer Two then presses the “PyPI” button to upload the package to PyPI as
docassemble.debtconsult.
- Months later, Developer Three, using yet another docassemble server, goes to “Package Management” from the menu and installs the
docassemble.debtconsultpackage from PyPI. This will cause the latest versions of both
docassemble.bankruptcyand
docassemble.debtconsultto be installed.
In order to facilitate collaboration, Developer One should prepare
interview files in a “modular” way, putting general purpose
questions
and
code blocks in separate YAML files that are
included in
special-purpose interview files.
Using private GitHub repositories
If you want to keep your docassemble extension package in a private GitHub repository, you can still use the Playground.
Create the repository on GitHub, give it a name that follows the
standard naming convention (
docassemble-debtconsult), and mark it as
private.
Then, on your docassemble development server, set up GitHub
integration so that
your Playground can access the private repositories that your GitHub
account can access. Then, using the “Packages” folder, you can create
a package called, e.g.,
debtconsult, and when you save it, you will
see that the Playground recognizes that the package is already
installed on GitHub. When you use the Commit button, you will commit
to the private repository.
You can also “Pull” your private repository into your Playground.
When you click “Pull,” it asks for a GitHub URL. For public
repositories, this is usually something like, for private
repositories you can use the SSH form of the repository, which is
git@github.com:jsmith/docassemble-debtconsult.git.
When it comes time to install your private repository on a production
server, you will not be able to use SSH authentication, so you will
need a GitHub URL that embeds an “OAuth” code. You can create these
codes on the GitHub web site. Within your “Settings,” go to
“Developer settings” and go to the “Personal access tokens” tab.
Click “Generate new token.” You can set the “Token description” to
whatever you like (e.g. “docassemble”). Check the “repo” checkbox, so
that all of the capabilities under “repo” are selected. Then click
“Generate token.” Copy the “personal access token” and keep it in a
safe place. If your token is
e8cc02bec7061de98ba4851263638d7483f63d41, your GitHub username is
jsmith, and your package is called
docassemble-debtconsult, then you can access your private
repository at this URL:
This functions just like a URL to a public repository. For example, you could do:
git clone
Within docassemble, you can go to “Package Management” and enter
this URL into the “GitHub URL”. This will install the package on your
server. Any time you wanted to update the package, you could visit
the link
/updatepackage?action=update&package=docassemble.debtconsult on your
server.
Editing Playground files in a text editor on a local machine
Not using Docker
If you are not using Docker to run docassemble, you can use sshfs to “mount” your Playground.
sshfs www-data@localhost:/usr/share/docassemble/files pg
This way, you can use a text editor to edit your Playground files.
Using Docker
If you are running docassemble Docker on a local machine, and you are not using S3 or Azure Blob Storage, you can use Docker volumes to access your Playground files using a text editor running on your local machine.
This requires running
docker run, so if you already have a running
docassemble Docker container, you will have to delete it and
create a new one.
In the following commands, we create a directory called
da, and then
use
docker run to start docassemble in a way that maps the
da directory to the container’s directory
/usr/share/docassemble/files.
mkdir da docker run \ --env WWWUID=`id -u` --env WWWGID=`id -g` \ -v `pwd`/da:/usr/share/docassemble/files \ -v dabackup:/usr/share/docassemble/backup \ -d -p 80:80 -p 443:443 jhpyle/docassemble
The
WWWUID and
WWWGID options are important because they ensure
that you will be able to read and write the files in
da. This
command also creates a Docker volume called
dabackup so that you
can use
docker stop to stop the container,
docker rm to remove
the container, and then you can re-run the
docker run command
above, and you will not lose your work.
The contents of
da will include:
000- This is where uploaded files are stored. You can ignore this.
playground- This is where interview YAML files are.
playgroundmodules- This is where module files are.
playgroundpackages- This is where package information is stored. If you use GitHub integration, the SSH key is stored in here, in hidden files called
.ssh-privateand
.ssh-public.
playgroundsources- This is where “sources” files are stored.
playgroundstatic- This is where “static” files are stored.
playgroundtemplate- This is where “template” files are stored.
Editing locally and running interviews in the Playground
Within each
playground directory, there are subdirectories with
numbers like
1. These refer to user numbers. Each user has their
own separate folder. Typically, if you have a server all to yourself,
you will do everything as user
1. The directories you will use most
often are
da/playground/1 and
da/playgroundtemplate/1, for
interview files and templates, respectively. For convenience, you
might want to create symbolic links from your home directory to these
folders. If you change the directory structure within
da, you will
probably cause errors.
To run interviews in your Playground, you can use links like
The
docassemble.playground1 part refers to the Playground of user 1,
which is a “package” that isn’t really a package.
The
interview.yml part refers to the interview file you want to run.
The
cache=0 part means that you are telling docassemble to
re-read the interview from the disk. This is important; normally
docassemble caches interviews in its memory. So if you make
changes to the interview file on disk, you need to tell
docassemble that the interview changed. That is what
cache=0
does.
The
reset=1 part means that you want to start the interview at the
beginning. This might not be the case; if you want to try to resume
an interview you had already been running, you can omit
reset=1.
If you use the Playground in the web browser, you can use the “Run” button in the “Variables, etc.” section to launch interviews. Be careful about using “Save and Run” because it will save whatever version is in the text area in the web browser; this may overwrite the version you had been working with.
Note that editing files in your Playground in this way is a “hack” that bypasses docassemble’s front end, so do not be surprised if you encounter problems. For example, if the server is unable to access a file because your text editor has placed a lock on it, you might see an error.
If you are not using Docker, but you are using Linux, you can use sshfs to create a mount in your home directory that maps to the Playground.
First, if you don’t have an SSH key stored in
~/.ssh/id_rsa and
~/.ssh/id_rsa.pub, generate one:
ssh-keygen -t rsa
Then, run the following as root, from your home directory:
mkdir -p /var/www/.ssh cat .ssh/id_rsa.pub >> /var/www/.ssh/authorized_keys chown www-data.www-data /var/www/.ssh/authorized_keys chmod 700 /var/www/.ssh/authorized_keys
mkdir pg sshfs -o idmap=user www-data@localhost:/usr/share/docassemble/files pg
Workflow for making changes to the core docassemble code
If you want to make changes to the docassemble code, clone the GitHub repository:
git clone
The source code of docassemble will be in the
docassemble
directory.
In order to test your changes, it helps to have a convenient workflow
for installing your changed code. Theoretically, your workflow could
involve running
docker build to build a Docker container, but
that would probably be overkill. Most of the time, you will make
changes to Python code, rather than system files. To test your
code, you will only need to install the Python packages and then
restart the three services that use those packages (the web server,
Celery server, and web sockets server).
The first complication is that the machine on which it is convenient for you to edit files may not be the machine where you are running docassemble. You may wish to edit the files on your laptop, but you have docassemble running in a Docker container on your laptop, or on another machine entirely.
There are a variety of ways to get around this problem. If your local
machine uses Linux, you can follow the installation instructions and
run docassemble without Docker. Then your source code will be
on the same machine as your server, and you can run
pip directly on
your source files.
Another alternative is to fork the docassemble GitHub repository
and use GitHub as a means of transmitting all of your code changes
from your local machine to your server. You can use
git add,
git
commit,
git push on your local machine to publish a change, and
then, on the server, you can use
git clone to make a copy of your
repository on the remote machine (and use
git pull to update it).
Then on the server you can run
pip to install the updated versions
of your packages.
If you are using Docker on your local machine, you can use a Docker
volume to share your code with your container. If you cloned the
docassemble GitHub repository, then from the directory in which the
docassemble directory is located, launch your Docker container by
running something like:
docker run \ --env WWWUID=`id -u` --env WWWGID=`id -g` \ -v `pwd`/docassemble:/tmp/docassemble \ -d -p 80:80 jhpyle/docassemble
Then you can
docker exec into the container and run
cd
/tmp/docassemble to go to the directory in which the docassemble
source code is located.
The second complication is that you need to install the Python
packages in the right place, using the right file permissions. On
your server, your docassemble server will be running in a Python
virtual environment located in
/usr/share/docassemble/local3.6 (unless
you significantly deviated from the standard installation procedures).
The files in this folder will all be owned by
www-data. The uWSGI
web server process that runs the docassemble code runs as this
user. The files in the virtual environment are owned by
www-data so
that you can use the web application to install and upgrade Python
packages. If you change the ownership of any of the files in
/usr/share/docassemble/local3.6 to
root or another user, you may get
errors in the web application. When using
pip from the command line
to install your own version of the docassemble packages, you need
to first become
www-data by running
su www-data as root. Then you
need to tell
pip that you are using a specific Python virtual
environment by running
source
/usr/share/docassemble/local3.6/bin/activate. Then, you can run
pip
to install your altered version of the docassemble code. This
line will install all the packages:
pip install --no-deps --no-index --upgrade ./docassemble_base ./docassemble_webapp ./docassemble_demo ./docassemble
The
--no-deps and
--no-index flags speed up the installation
process because they cause
pip not to go on the internet to update
all the dependency packages.
After you run
pip, you need to restart the services that use the
Python code. If you are only going to test your code using the web
server, and you aren’t going to use background tasks, it is enough to
run
touch /usr/share/docassemble/webapp/docassemble.wsgi as the
www-data user. This updates the timestamp on the root file of the
web application. Updating the timestamp causes the web server to
recompile the Python code from scratch. Restarting the uWSGI
service also does that, but it is slower.
If you want to ensure that all the code on your server uses the new
versions of the Python packages, you can run the following as
root
(or with
sudo):
supervisorctl start reset
This will do
touch /usr/share/docassemble/webapp/docassemble.wsgi
and will also restart Celery and the web sockets server.
Then you can test your changes.
These are significant barriers to a smooth workflow of testing changes to docassemble code, but with the help of shell scripts, you should be able to make the process painless.
Here is one set of scripts that could be used. You can run the script
compile.sh as yourself. It will ask you for the
root password,
and then it will run the second script,
www-compile.sh, as
www-data after switching into the Python virtual environment.
Here are the contents of
compile.sh:
#! /bin/bash su -c '/bin/bash --init-file ./www-compile.sh -i' www-data" root
Here are the contents of
www-compile.sh:
#! /bin/bash source /etc/profile source /usr/share/docassemble/local3.6/bin/activate pip install --no-deps --no-index --upgrade ./docassemble_base ./docassemble_webapp ./docassemble_demo ./docassemble && touch /usr/share/docassemble/webapp/docassemble.wsgi history -s "source /usr/share/docassemble/local3.6/bin/activate" history -s "pip install --no-deps --no-index --upgrade ./docassemble_base ./docassemble_webapp ./docassemble_demo ./docassemble && touch /usr/share/docassemble/webapp/docassemble.wsgi"
When
compile.sh runs, it will leave you logged in as
www-data in
the virtual environment. It also populates the shell history so that
to run
pip again and reset the web server, all you need to do is
press “up arrow” followed by “enter.” This is then the process for
re-installing your changes to the docassemble Python code.
These scripts might not work for you in your specific situation, but some variation on them may be helpful.
Ensuring quality
How can you ensure that a docassemble interview is high quality?
A common mindset is that the way you produce a web application is to hire a developer for a “project.” The developer writes code over a period of time and then provides a “deliverable” that meets your specifications. The developer then goes away and works on other projects. After you publish the application on the internet, your expectation is that it will work perfectly and operate indefinitely. Over time, it may need to be tweaked because of changing circumstances, so you may hire someone to make minor changes to the application. But otherwise, you consider the application “done” when the developer delivers it to you. If quality problems emerge after the developer has moved on to other things, you are annoyed. You wish that you had hired a better developer, or that you had done a better job communicating your requirements. You feel like you shouldn’t have to be bothered with bugs; the application should just work, and should require minimal maintenance. Maybe after a few years, your annoyance reaches a point where you take the application down and hire a different developer to produce a new version of the application.
This mindset can be present even when you are a computer programmer yourself. After you have “finished” the application, you want to be able to move on and do other things. Making changes to an application is something you feel like you don’t have time to do. Even if you budgeted time for “maintenance,” because you expected there was a finite probability that something would need to be fixed, you would still like to minimize the time you spend fixing bugs.
Another aspect of the common mindset is to think of web applications as falling under the “information technology” umbrella. If there are quality problems, people think it’s an “IT issue” that needs to be delegated to a person with computer skills, even when the quality issues are actually related to poor communication or poor substantive design, neither of which are information technology problems.
These ways of thinking are bound to result in low-quality web applications.
Managers of technology “projects” need to understand that quality assurance is not simply a technology problem; like all problems, it involves “people, process, and technology.” All three need to be considered when planning for quality assurance.
Who are the people who should ensure that a guided interview is high-quality? What skill sets are necessary? Do interviews need to be developed by individuals who have subject matter expertise as well as technical skills? Or can subject matter experts without technical skills work together with people who have technical skills? Should someone take on a managerial role to coordinate developers and subject matter experts? If subject matter experts work on the project, should their role be to “look things over” and be available for questions, or should they play an active role in the design?
Which subject matter experts should be involved? Even if a subject matter expert knows the subject matter very well, that doesn’t mean they are good at communicating about that subject matter through the medium of an app. In litigation, by analogy, lawyer A who has written briefs for 20 years may understand the law as well as lawyer B who has tried cases in court for 20 years, but that doesn’t mean that lawyer A is capable of standing up in court and persuading the jury to favor his or her client. One lawyer may be very good at litigating contract disputes, but not good at drafting contracts so that they are concise, and anticipate every possible scenario that may develop.
What processes should be used to ensure that an interview is high-quality? Should the development work be seen as part of a time-limited “project,” or rather as a long-term commitment to deliver a “product” or “service” to users? Should the output of the interview be reviewed by a human before it is provided to the user? Should users have access to customer support while using the interview? Should someone be staffed with observing users as they use the application in order to figure out why users are getting stuck? Is testing a process that is started shortly before the interview goes live, or integrated into the development process from the beginning? How intensive should the testing be? Should the testing process be informal (“try it out, click around, see if it breaks”) or formal (“Try scenario A to completion, then scenario B to completion”)? Should a process of continuous quality improvement be followed, in which information is collected from user surveys or customer service requests and used as the basis for improvements? Should metrics be collected and reviewed? Should team meetings be held to brainstorm improvements? Should testing be conducted every time a new version is published? Should this testing process test new features only, or also test features that used to work without a problem? After an interview goes live, should a subject matter expert review it periodically to make sure the logic is not out of date? Should the interview be tested in some way every day to make sure the site hasn’t crashed without sending a notification?
Lastly, how can technology assist the people who implement these processes? It is important to view technology for quality assurance in this context. Think about the role of technology after you think about what people and processes are optimal.
Before thinking about how you wish to provide quality assurance, it may be helpful to read about various approaches to software development as a whole (such as the difference between waterfall and Agile lifecycles, and the DevOps methodology) and specifically about different approaches to software testing. The approaches that have been used in the past are not necessarily “best practices.” However, reading about other people’s approaches may help you realize that your initial ideas about how to handle quality assurance may not make sense.
In particular, think about breaking out of the project-oriented, time-limited development paradigm. Do what is right for your users, not what other people do. Don’t imitate big corporations; corporations that charge a lot of money still produce low-quality products. When it comes to guided interviews, “building the airplane while flying it” is not an absurdity; it may even be advisable. It may be better to spread development resources out over the course of your product’s lifetime than to invest them all at the beginning and hope that your “specification” was perfect. If you develop a minimum viable product, let users use it, study the pain points, and adapt your product incrementally to address the actual concerns of actual users, perhaps your product will be higher quality than anything you could have pre-envisioned while sitting in meetings talking about what “requirements” to give to a vendor. Is it the end of the world if a user encounters a bug? Perhaps the user will not mind about the bug if you communicate with them immediately, demonstrate that you care, and fix the bug promptly. In fact, if the user sees that there are real people behind the application, and that those people truly respect the users, their opinion of your application may increase after they encounter a bug.
Think of every event in the software lifecycle as good, important, and worthy of allocation of resources. Did you discover a flaw in your software after it went live? Good, fix it; now your product is more robust than it was yesterday. Did your code break because a dependency changed? Great, make changes to adapt; now your code is more up-to-date. If you concentrate all your energy on preventing, insuring against, or hiding from low-probability events, rather being resilient when those events happen, your software will will stop evolving. When your software stops evolving, it will start being “legacy.”
You might think, “I don’t have the resources to pay developers to continually improve a product.” First, maybe the resources necessary are not as expensive as you think. Maybe how you are managing the development of the software is the problem, not the money you are spending. For example, maybe instead of spending hundreds of hours of staff time developing a custom color scheme, you could allocate those hours toward something that matters more, like developing a continuous quality improvement process that ensures the application does what it is supposed to do. Second, maybe you do have the necessary resources, but you are not allocating them to software development because you have a preconceived notion of how you should be allocating those resources. Are you actually thinking about return on investment, or do you just assume that software development is only worth a small amount of money? Third, if you truly lack the resources to produce a quality software application, that’s fine; in that case, instead of putting a low-quality product on-line, maybe you should allocate resources to something more worthwhile.
People who are involved in the development of a web application but lack technology skills often feel a lack of agency over the way the application operates. Sometimes this is because the engineers do not allow them to have such agency. Other times, the non-technical people do have agency, but do not exercise it because of “learned helplessness”; they know that problem-solving is difficult, and they can avoid it by telling themselves that the task of problem-solving is someone else’s responsibility, namely, the “IT people.”
How should subject matter experts be involved, and what can be expected of them?
There are different levels of subject matter expert engagement in a guided interview project. Many experts may view working on a guided interview project as an “extra credit” responsibility, which they can take on when they already have a day job without decreasing their existing work load. They may see their role as reviewing the work of others, spotting substantive mistakes, and suggesting improvements.
At the other end of the spectrum, the subject matter expert could see their role as that of a tech startup founder, who wants to build a great guided interview that thoroughly implements their subject matter expertise. They see their role as ensuring excellence, and will give the development process their full attention.
Since an expertise automation “industry” does not really exist yet, there is no clearly defined role for the expert. How much should the expert be expected to understand the technology? How much should the technologists be expected to understand the subject matter?
For purposes of comparison, consider the film industry. Is the role of the subject matter expert like that of the screenwriter, who has a clear vision for the end result and does much of the creative work? Or is it like that of a film critic, who critiques the film after-the-fact and suggests ways that it could have been better?
Or consider the construction industry. Is the role of the subject matter expert like that of the architect, who creates the blueprints, or like that of a municipal agency that approves building permits?
Because there is no existing expertise automation “industry,” there are no existing expectations of what roles are necessary to create a high-quality guided interview. In the film industry, there are producers, screenwriters, directors, cinematographers, lighting directors, and more, who are acknowledged to be practitioners of a craft. In the construction industry, there is an understanding that architects, structural engineers, and builders work together to get buildings constructed and make sure they don’t fall down. Each of these roles is acknowledged to be a special skill, the development of which depends on talent, education, and experience.
In the guided interview industry, by contrast, there is a popular belief that expertise automation is inherently “easy,” and that a subject matter expert from any background just needs to sit down in front of a computer, use some user-friendly software, and produce a high-quality app by themselves in a short period of time. Others assume that guided interviews are an “IT thing,” and some “smart techie” can do all the work if there is a subject matter expert who makes themselves available to answer questions. Others assume that a guided interview project simply needs a project manager who communicates specifications to contracted developers who work offsite.
Whether expertise automation is inherently “easy” depends on the complexity of the expertise automation process being attempted. At one end of the spectrum there are “form-filling” projects that simply involve asking a question for each field in a PDF form, with a little bit of logic, and delivering a PDF form. At the other end of the spectrum there are guided interviews that ask the same question multiple times from different angles, reconcile API-gathered information with user-gathered information, allow the user to spot-edit information while ensuring logical correctness, allow administrators to have special back-door access to investigate and resolve problems, and contain safeguards to allow incorrect information to be identified and corrected. Whether the development of complex guided interview systems can be made “easy” with technology is doubtful. When it is difficult to even figure out what you want the system to do, the computer is not going to be able to read your mind.
While a typical subject-matter expert may be able to figure out how to use TypeForm and WebMerge, they may not be able to envision the most elegant data structure for collecting nested information, or envision what to do in every circumstance where a call to an API might fail. Nor may they know the right way to communicate effectively with a user through the medium of a guided interview.
Is “guided interview developer” a profession? The problem with professions is that it is very difficult to determine in advance whether a professional would add value over what you could do yourself with the right tools, or just extract a fee. However, just because you can go to Ikea and get a nice piece of furniture that you can assemble yourself with a screwdriver does not mean that there is never a good reason to hire an experienced cabinet maker. If you have a firm belief that building beautiful, functional, and durable custom furniture should be as easy and quick as assembling Ikea furniture, and you think tech companies just need to hurry up and build DIY tools for this, you’re probably going to be waiting a long time. Although the profession of “guided interview developer” does not really exist yet, it is likely that over time, it will be acknowledged to be a skilled profession that is necessary in situations of greater complexity.
If the complexity of a project exceeds what is possible for a subject matter expert to accomplish with DIY tools, who should be part of the team? Some assume that a “guided interview developer” is synonymous with “someone good with computers.” However, IT professionals who understand network administration may not have sufficient facility with algorithms, data structures, and debugging to implement complex guided interview processes. Someone who has too much expertise in certain areas of software development may not not be ideal for the “guided interview developer” role. As the saying goes, “if the only tool you have is a hammer, everything looks like a nail.” Front-end developers tend want to write complicated CSS and JavaScript. Developers with experience on other platforms will tend to spend time thinking about integrating the guided interview platform with their favorite platform, rather than working within the guided interview platform they are using.
A good developer does not just deliver the deliverable, but will figure out a way to do so in the simplest way possible. Simplicity means maintainability; it means that the code base will not need to be scrapped just because the person who created it gets a job elsewhere. If the project is implemented in the simplest way possible, another developer will be able to step in and build on the work of the prior developer. However, if that prior work is inscrutable, the new developer will have not choice but to redo it.
Maintaining simplicity sometimes means pushing back against feature requests. Even if the developer could implement a feature, if there is a high maintainability cost to adding the feature (a cost which is usually invisible to everyone except the developer), it may make sense to modify the feature or not implement it at all. In many cases, if the feature that someone wants cannot be implemented without harming maintainability, it might be a bad feature anyway. When a feature cannot be implemented elegantly, this is often because it diverges from standards. Features that adhere to standards tend to be easier to implement and often result in a better product for the end user because they are similar to features the user has seen in other products. Often, the only person who knows enough to advocate for standards is the developer who is asked to implement a feature, since the non-developers who request features may not be aware of what the standards are.
Other skills sets that are necessary for a guided interview project are user experience design. User experience is more than a matter of CSS; it’s about making sure the flow through the interview is intuitive.
A related skill set is plain language communication. How do you ask a question in a way that is concise and readable and yet conveys the correct meaning?
There is no reason to expect that any given subject matter expert or a software developer will have all of these skills. Subject matter experts whose professional life involves communicating with other experts in the same subject matter typically have a difficult time writing in plain language. Maybe subject matter experts and developers could acquire these skills over time, but if you want your guided interview to be good, these skills need to be on the team. Someone needs to be able to look at the product objectively, with empathy for the wide variety of users who might use the guided interview, and envision ways that it can be better. The designer does not need to be able to write code to indicate how they think an interview could be re-designed; they could convey it on paper. The coder then needs to be able to figure out ways to implement what the designer suggests without breaking with standards or making the interview unmaintainable.
All of the people contributing to the project are “guided interview developers,” just like producers, screenwriters, directors, cinematographers, lighting directors are all “movie developers.” All the people involved in guided interview developed should think of themselves as artists producing a masterpiece; none of them should think that “development” is something someone else is doing; they are all “developing.”
Behavior-driven development
Automated testing of software is useful because when you have a rapidly changing code base, unexpected changes may occur at any time. If you can automatically run acceptance tests to ensure that the software behaves the way you and your subject matter experts think it should behave, you can detect not only obvious bugs and also the stealthy bugs that most people won’t notice or report.
docassemble comes with scripts and examples for running automated acceptance tests using Lettuce, which is a Python version of the Cucumber system for Behavior-Driven Development.
The idea behind “Behavior-Driven Development” is for development and management teams to work together write acceptance tests in a human-readable domain-specific language that can also be interpreted by the computer in order to test the software. In Cucumber and Lettuce, this human-readable language is a plain text file written in the Gherkin format. docassemble allows interview developers to write Gherkin scripts that look like this:
Scenario: Test the interview "Annual income calculator" Given I start the interview "docassemble.demo:data/questions/income.yml" Then I should see the phrase "What is your income?" And I set "Income" to "400" And I select "Twice Per Month" as the "Period" And I click the button "Continue" Then I should see the phrase "You earn $9,600 per year."
These scripts test the interviews by automating Chrome or Firefox. The software converts human-readable commands into keystrokes and pointer clicks, and reads the screen to verify that the correct language appears. This ensures that testing is thorough because it tests the software from the user’s perspective. Everything the technology does, from the JavaScript running in the user’s browser to the background processes running on docassemble, is tested. More information about deploying Lettuce is available below.
Technology for web browser automation exists that allows you to “record” keystrokes and button clicks and then “play” it back at a later time. By comparison, it may seem time time consuming to write out English language sentences. However, the advantage is that English language sentences are human-readable. The Gherkin scripts themselves can be reviewed by a subject matter expert for validity, and can easily be edited when the underlying interview changes.
Acceptance testing using the Behavior-Driven Development model requires management and development teams to envision different scenarios and precisely specify the expected outputs that result from particular inputs. As the interview changes, the Gherkin scripts will need to be changed in parallel. This is a significant commitment of time. However, the strictness of the testing scripts helps to uncover unexpected bugs. When an interview passes a test at one time and then fails it later due to a subtle change, that subtlety can be the tip of the iceberg of a more systemic problem.
The downside of the Behavior-Driven Development model is that it is not feasible to envision and test every possible scenario. For example, if an interview has five multiple-choice questions with five choices each, that means there are 3,125 possible scenarios. It would be too much work to envision and separately test that many scenarios. While there may be a latent bug lurking in one of those 3,125 combinations of answers, in practice, Behavior-Driven Development teams will only have the resources to conduct acceptance testing on a handful of those scenarios. If these scenarios are diverse, they will catch a lot of bugs, but they won’t catch all the bugs.
Random-input testing
Another way to test interviews is use docassemble’s API, which allows an interview session to be driven with a computer program. Using the API, an interview can be repeatedly tested with random multiple-choice selections and random input values. If a random combination of inputs results in an error screen, the test fails, and the developer will know that there is a bug in the interview.
An example of such a script is the
random-test.py file in the
docassemble.demo package. This is a general-purpose script for
testing any interview, but you will likely need to tweak it to work
appropriately with any of your own interviews. For example, it does
not adapt to questions that use the
show if feature to conceal
fields.
Repeatedly testing a web application with random data can uncover bugs that result in the user seeing an error message, but it cannot identify substantive errors, such as situations where the user is asked an inappropriate question or given inappropriate information.
Input-output testing
Another approach for testing a docassemble interview without using Behavior-Driven Development is to manually populate a full set of interview answers and then inspect the “output” of the interview to ensure it correctly corresponds to the input. This procedure bypasses the information-gathering process of the interview and tests only the end-result logic.
One way to do this is to add blocks to your interview like:
mandatory: True code: | if user_has_privilege(['developer', 'admin']): if scenario_to_test != 'skip': value(scenario_to_test) --- question: | Which scenario do you want to test? field: scenario_to_test choices: - Scenario One: scenario_one_defined - Scenario Two: scenario_two_defined - No Scenario: skip --- code: | # Make sure necessary objects are defined # early on so that this block can run idempotently. client.name client.asset client.name.first = 'Joseph' client.name.last = 'Jones' client.birthdate = as_datetime('5/1/1995') car = client.asset.appendObject() car.value = 323 car.purchase_date = as_datetime('5/1/2015') # etc. etc. scenario_one_defined = True
If the user is not a developer or an administrator, the
mandatory
runs to completion and is never run again. But if the user is a
developer or administrator, the interview will start with a screen
that the user can use to select a scenario. The
mandatory block
uses the
value() function to seek a definition of
scenario_one_defined or
scenario_two_defined. Once the scenario
is defined, the
mandatory block runs to completion and the interview
proceeds normally. The next screen that is shown is whatever screen
would be shown to a user who had input the information listed in the
scenario.
You can use this technique to “fast forward” to a part of the interview you want to test, or to “fast forward” to the very end.
You could use “sub-scenarios” so that you can mix-and-match different
collections of variables. For example, your
scenario_one_defined
block could seek the definition of
scenario_user_self_employed and
scenario_high_tax_bracket, while your
scenario_two_defined block
could seek the definition of
scenario_user_has_employer and
scenario_high_tax_bracket. This will allow you to avoid having to
copy and paste code.
You could then have a Lettuce script that starts with:
Scenario: Test the interview "Debt collection advice" Given I log in with "jsmith@example.com" and "sUper@sEcr3t_pAssWd" And I start the interview "docassemble.massachusetts:data/questions/debt.yml" Then I should see the phrase "Which scenario do you want to test?" And I click the "Scenario One" option And I click the button "Continue"
These few lines effectively “stand in” for many lines of Gherkin sentences you would otherwise have to write to simulate the user typing in information. A Lettuce script like this is easier to maintain than one that you have to modify every time you make a change to the language or order of your information-gathering screens.
Another way to prepopulate interview answers is to use the API. However, the downside of using the API to set variables is that the API’s variable-setting endpoint is not capable of creating objects.
Since there can be bugs in the logic of the information-gathering process, this procedure is not as thorough as a Behavior-Driven Development approach that goes through all of the information-gathering screens.
Unit testing
docassemble also supports the technique of testing components of an interview in isolation (“unit testing”). Unit testing is feasible when the legal logic of an interview is written in the form of Python classes, methods, and functions. For example, the interview might have an algorithm that determines jurisdiction:
class Plaintiff(Individual): def jurisdiction_state(self, cause_of_action): if self.lived_in_current_state_for_two_years(): return self.address.state return cause_of_action.state_arose_in
This method could be tested on a variety of inputs to ensure that the legally correct answer is given:
import unittest from docassemble.base.util import as_datetime from .massachusetts_law import Plaintiff, CauseOfAction class TestJurisdiction(unittest.TestCase): def test_moved_recently(self): plaintiff = Plaintiff() plaintiff.address.state = 'MA' plaintiff.address.move_in_date = as_datetime('1/5/2017') plaintiff.prior_address.appendObject(state='NH', move_in_date='9/2/2015') cause_of_action = CauseOfAction(state_arose_in='NH') self.assertEqual('NH', plaintiff.jurisdiction_state(cause_of_action)) def test_did_not_move_recently(self): plaintiff = Plaintiff() plaintiff.address.state = 'MA' plaintiff.address.move_in_date = as_datetime('10/5/2005') cause_of_action = CauseOfAction(state_arose_in='NH') self.assertEqual('MA', plaintiff.jurisdiction_state(cause_of_action)) if __name__ == '__main__': unittest.main()
This module uses the
unittest framework. A module using the
unittest framework can be called from an interview using the
run_python_module() function.
It may seem like a waste of time to write a computer program to test two scenarios when it would be much faster to simply test the two scenarios manually, and if they work right, conclude that the feature works and will continue to work. However, writing out the test scripts is worthwhile because test scripts can then be run in the future in an automated fashion to prevent “regression.” Very often, bugs in software come from features that used to work but that stop working for hard-to-predict reasons. Something that used to work might suddenly stop working because of a change in the code of a dependency, such as a software library written by someone else. Code may also stop working because changes you made elsewhere in your package have unanticipated long-distance effects.
Legal logic algorithms can also be “unit tested” using brief test
interviews that are separate from the main interview and exist only
for testing purposes. These test interviews could be operated by
subject matter experts manually, who could manually try out various
possibilities in to make sure the algorithm produces the legally
correct response. These same interviews could also be tested in an
automated fashion with Lettuce scripts. For example, a test
interview,
test-jurisdiction.yml, might look like this:
modules: - .massachusetts_law --- objects: - plaintiff: Plaintiff - cause_of_action: CauseOfAction --- mandatory: True code: | plaintiff.prior_address.appendObject() plaintiff.prior_address.gathered = True --- question: | Please provide the following information. fields: - Current state: plaintiff.address.state code: states_list() - Move-in date: plaintiff.address.move_in_date datatype: date - Prior address state: plaintiff.prior_address[0].state code: states_list() required: False - Prior address move-in date: plaintiff.prior_address[0].move_in_date datatype: date required: False - State in which cause of action arose: cause_of_action.state_arose_in code: states_list() --- mandatory: True question: | The state of jurisdiction is ${ state_name(plaintiff.jurisdiction_state(cause_of_action)) }. ---
The corresponding Lettuce script would look like this:
Feature: Determination of jurisdiction I want to see if the code determines jurisdiction correctly. Scenario: Test jurisdiction when the plaintiff has lived in Massachusetts for a long time. Given I start the interview "docassemble.massachusetts:data/questions/test-jurisdiction.yml" And I select "Massachusetts" as the "Current state" And I set "Move-in date" to "1/5/2017" And I select "New Hampshire" as the "Prior address state" And I set "Prior address move-in date" to "9/2/2015" And I select "New Hampshire" as the "State in which cause of action arose" And I click the button "Continue" Then I should see the phrase "The state of jurisdiction is New Hampshire." Scenario: Test jurisdiction when the plaintiff has lived in Massachusetts for a long time. Given I start the interview "docassemble.massachusetts:data/questions/test-jurisdiction.yml" And I select "Massachusetts" as the "Current address" And I set "Move-in date" to "10/5/2005" And I select "New Hampshire" as the "State in which cause of action arose" And I click the button "Continue" Then I should see the phrase "The state of jurisdiction is Massachusetts."
You could have a number of testing scripts like these, which you could run to ensure that the legal logic of your interview is proper. Unlike Lettuce scripts that test your actual interview, these scripts will not need to be changed whenever you make stylistic modifications to your interview. In that way, they are much easier to maintain.
You might think it is inefficient to write 40 lines of YAML and Gherkin to test an algorithm that is five lines long. But there is no logical basis for assuming that the the algorithm itself should take up less space than its testing code. Nor is there a logical basis for assuming that the task of writing the algorithm should take longer than testing the algorithm (or writing documentation for the algorithm). All of this work is important.
You do not need to develop a rigid habit of writing test scripts for
every piece of code you write. If you have a
code block that
capitalizes a word, for example, it is reasonable to “test” it by
“eyeballing” it or testing it incidentally as part of a
whole-interview Lettuce script. But if you have mission-critical
algorithms that do somewhat tricky things, spending a lot of time on
test code will yield a good return on investment.
The next section provides a practical explanation of how to use Lettuce to test docassemble interviews.
Using Lettuce
Lettuce is a Python program that runs on your local computer. It uses selenium to automate the behavior of a web browser such as Firefox or Chrome.
The way that Lettuce works is beyond the scope of this documentation. This section describes only a broad outline of how Lettuce can be used to test docassemble interviews.
pip install lettuce selenium
You will then need a “driver” that will control your web browser. If
you use Chrome, you need to install chromedriver first. Then you
will need to edit
terrain.py so that it contains the appropriate
reference to the location where the
chromedriver file can be found.
If your docassemble extension package is in the directory
/home/jsmith/docassemble-lt, then you would do:
$ cd /home/jsmith/docassemble-lt/tests $ lettuce
Of course, you first need to create a
tests directory and create the
appropriate directory structure within it,
This directory structure needs to be as follows:
docassemble-lt |-- docassemble |-- ... various files like README.md ... `-- tests `-- features |-- steps | `-- docassemble.py |-- terrain.py `-- MyTest.feature
The file
MyTest.feature can be called anything, and you can have
more than one
.feature file. When you run
lettuce, all of the
feature files will be used.
The
terrain.py and
docassemble.py files are the Python modules
that perform the web browser automation. Versions of these files are
available in the docassemble GitHub repository, but you may need
to edit these modules to get your tests to work.
A starting point for the
terrain.py module is available here:
A starting point for the
docassemble.py module (which is imported
into
terrain.py) is available here:
The test file itself, which is called
MyTest.feature above, would
look something like this:
Feature: Interview that works with actions In order to ensure my interview is running properly I want to see how it reacts to input. Scenario: Test the interview "Action with arguments" Given I start the interview "docassemble.base:data/questions/examples/actions-parameters.yml" And I click the link "Add blue fish" When I wait 1 second Then I should see the phrase "You have 3 blue fishes" And I click the button "Continue" Then I should see the phrase "You have 3 blue fishes"
One useful feature is the “step” invoked by “I wait forever.” If you run this step, the browser will stay open and you can use it. This can be helpful if you want to use Lettuce to bring you to a particular step in your interview, without you having to re-do all of the steps by hand.
For more information about how automated testing works, read the documentation for Lettuce. You may also wish to read about the Behavior-Driven Development concept in general before starting to use Lettuce.
Improving quality with non-technical staff
One barrier to involving non-programmers in the development of guided interviews is that guided interviews are technologically complex.
It is commonly believed that “code” is the barrier that locks out non-programmers from being involved in the development process, and if only we had a user friendly UI, non-programmers could develop applications just as well as programmers. However, this may not be the case. For example, a non-programmer can conceptually understand what a list is and what a dictionary is, but if you ask a non-programmer “what’s the optimal data structure for gathering information about witnesses, their current employer, and their past employers,” a non-programmer is going to struggle with that question. It can even be a difficult question for a programmer. The barrier for the non-programmer is not that they don’t know whether a semicolon goes at the end of the line or what brackets to use to specify a dictionary. The programmer’s advantage in answering the question is not that they have memorized the syntax of coding. Experience with coding leads to a way of thinking; it develops problem-solving skills in the technical domain.
Therefore, it is unlikely that you will be able to develop a maintainable, elegant software product without involving a skilled computer programmer to figure out issues of logic and data structure. However, there are ways that non-programmers can and should be deeply involved in the development of guided interviews.
Notice the popularity of the DevOps methodology in software development, which breaks down the silos of “operations” engineers and “development” engineers. Your non-technical people who know the subject matter of your interview may not think of themselves as “engineers,” but they are similar in many ways to the “operations” side of DevOps.
You can involve a non-technical person on the team who knows how to communicate in writing with succinct phrases, who knows when the text is too short and too long, knows when to hide information behind a hyperlink, and knows when to include it in the main page. A non-technical person may not know how to figure out tricky logic problems, but they can envision what the end result should be, and express that to the developers. When the developers implement it imperfectly, the non-technical person can see the imperfections and clean them up.
A non-technical person can be an advocate for the users against the developers, who may tend to make decisions in a way that makes life easier for themselves at the expense of the user. For example, the non-technical person could say, “we are asking the user if they lived outside the state in the last five years, but we already asked them when they moved to their current address, and if they gave a date that was before five years ago, we don’t need to ask them that question.” The developers might say, “well, that would be complicated for us because of x, y, and z.” And the non-technical person could say, “That’s nice, I am sure you can figure it out.” Then the developers will begrudgingly figure it out, and the interview will be improved.
When an application is live, non-technical people can provide customer service to users. They can learn about users’ difficulties, prioritize the changes that are most important, and communicate with the developers so that the difficulties are minimized in the future.
Non-technical people can also get involved in reading and writing code. They can express what they want to see in a guided interview by writing and editing Gherkin scripts, which the developers can clean up for syntax and use as a basis for implementing changes. Non-technical people can review Gherkin scripts to make sure they make sense from a substantive perspective. They can edit them to add additional conditions so that the Lettuce tests are more comprehensive.
It is possible to structure YAML interview files so that they are readable and editable by non-technical people. To facilitate this, developers can:
- Use the
includefeature and split up the YAML in such a way that complicated blocks are isolated in YAML files that non-technical people never see, while
questions and easy-to-read
codeblocks are put in files that non-technical people can review and edit.
- Keep
questions readable. While docassemble allows Python, HTML, CSS, and JavaScript to be sprinkled throughout a YAML file, a better practice is to hide away this complexity in other files. Developers can move Python into module files and other content into
templateblocks. That way, the YAML will primarily contain content that non-technical people can read and edit.
- Teach non-technical people to edit YAML using GitHub. Since it is possible that non-technical people will introduce errors when editing the content of YAML files, the developers should always review the changes and make corrections as necessary. But by having the power to read, search, and edit the YAML, non-technical people will be able to have a greater deal of control. Non-technical people should be about to figure out Markdown and much of Mako with enough confidence to draft questions and make edits.
- Insert
comments into the YAML to explain what the different blocks do, and arrange the blocks in a relatively sensible order. Non-technical people may not be able to learn the system sufficiently to write flawless code themselves, but they can at least understand the big picture.
If non-technical people are going to be effective members of the team, they need to adapt as well. They need to challenge themselves to learn new things every day. The process of learning is not difficult if they are willing to try. Learning how things works involves typing unusual words and phrases into Google (and the docassemble web site, and the GitHub web site) and reading what comes up.
Sometimes, the non-technical members of a team are viewed as “subject matter experts” because they have an expert knowledge of the subject matter of the guided interview. These experts can be important members of a team if they devote significant time to the work. But if their involvement in the work is in addition to a full time job, they will not be very helpful except as consultants to call for answers to specific questions. It is better to have a dedicated staff member who knows a little about the subject matter than to have a distracted staff member who knows a lot about the subject matter. | https://docassemble.com.br/docs/development.html | CC-MAIN-2020-45 | refinedweb | 12,366 | 50.97 |
In regards to Ruby and Python Compared:.
Python is not in any way a B&D language. At all. Even slightly. No resemblence. It takes nothing from Eiffel. It probably could take some good ideas, but right now it doesn't even take any of its good ideas.
Python attempts to build consistency with a carrot approach, not a stick. I say "attempts" because there are many places where the Python community doesn't agree on a solution, doesn't agree on the phrasing of the problem, or simply doesn't know the best way to do things. There will always be such places, until such time as all programming problems are solved. Despite the futility of this effort, we still pursue compelling, complete, and consistent solutions.
An important rule in the Python community is: we are all consenting adults. That is, it is not the responsibility of the language designer or library author to keep people from doing bad things. It is their responsibility to prevent people doing bad things accidentally. But if you really want to do something bad, who are we to say you are wrong? It's your program. Maybe you even have a good reason.
That said, it's unlikely you'll see language designers or library authors going out of their way to enable you to do bad things where it was previously impossible. So some feature suggestions that are likely to cause errors are unlikely to get much consideration.
Python usually seems to have one best way to perform a given task, and even prescribes how the code is to be laid out, since indentation is syntactically significant.
Of course you'd have to be nutty not to indent your code the way Python wants you to. Python is DRY (Don't Repeat Yourself) here.
Ruby's treatment of Booleans is much cleaner. In ruby, false and nil are considered false in boolean contexts, and everything else is considered true. Python follows the antimathematical convention of C and Perl where 0 is considered false. This nonsense really has no place in such a high-level language. But Python makes things worse: empty lists, empty dictionaries, and empty tuples are false. What about empty sets? Well, sets are not a built-in type, so it depends on how they are implemented. Python lacks true booleans: true and false.
I don't think this is a very meaningful comparison. If you want to test for nil/None, test for nil/None. I guess you could say that Ruby is like Scheme or Smalltalk, and Python more like Lisp. There's points for and against each technique, but smart people have and continue to go both ways; just get used to it.
That False == 0 and True == 1 is an artifact of a time when Python lacked true booleans (though now True and False are "true" booleans, even if they are also integers: False is not 0). While the underlying integer nature of True and False lacks elegance, I haven't had any problems with it in practice.
As for other things being false (I use a lower-case "false" to refer to all falsish items in Python), this is just how Python is. Falseness is a property of an object. Empty sets are false, because thats how they are implemented. Convention, not the language, enforces the greater concept of what is "false".
In C, 7/3 is 2. I'm really a mathematician rather than a programmer, so I feel that 7/3 should be the rational number 7/3. The earlier versions of Python followed the C convention. Happily, Python has finally switched. Ruby defaults to the C convention but also gives the ordinary convention for rationals when you require the mathn standard library. I always require the mathn standard library!. I assume in Ruby that means -- when the mathn library is loaded -- that division of all integers produces rationals...? But that seems so incredibly broken that I must assume it is not so.
Python's OO has become more extensive in recent versions, but it is still an OO bolt-on to a procedural language. Ruby is thoroughly OO. In Python, it is rather arbitrary whether some functionality is implemented by a function or a method (which have different syntaxes), and the programmer just has to remember how Python does it. Python has types and classes; in Ruby types are classes.
It's not "arbitrary," it's an aspect of whatever thing you are using. Not all libraries are designed the same, not all libraries are well designed, so sometimes a method is chosen when a function would do, or vice versa. You can make the same choices in Ruby. As a convention people in Ruby use methods far more often. Over time I personally have come to use functions more often than methods, only using methods if I see that a compelling object has emerged in my code. This is a difference of opinion. But Python isn't the only place where people are starting to feel more disaffected with class-based OO, though really it's an aside to the particulars of the language.
The distinction between classes (read: old-style classes) and types (read: built-in types, types written in C, new-style classes) is subtle and related to legacy. The distinction should disappear in 3.0, and you can mostly ignore it in current versions as well.
Until recently, Python's multiple inheritance had a critical design flaw which made it useless except as a way of implementing mixins. Whether the improved multiple inheritance will buy Python anything besides confusion has yet to be seen.
If it doesn't work for you, don't use it. In practice very few people use multiple inheritance anyway. Whatever.
But Ruby's thorough, dynamic OO gives the programmer incredible power. Methods can be easily added or removed from classes at run-time. They can easily added or removed from individual objects!
This can be done in Python as well, though it does not have the syntactic support that Ruby has. Some Python classes, including many built-in classes, are not possible to extend. Extending core classes is a highly questionable practice in my mind -- useful for clever hacks, but not for serious programming.
There is direct support for popular design patterns such as "Observer", "Delegator", "Singleton", "Visitor".
This is true; Python does not have any specific culture around these patterns. Though some patterns like "Singleton" are total nonsense anyway. But then, I don't really know what the support in Ruby looks like, so I don't know how I'd recognize it in Python..
Python's garbage collection is based on reference- counting. Ruby's is mark-and-sweep (scheduled to be replaced by a generation-based system). Python's system allows the programmer more direct control over garbage collection: the del operator tells Python to garbage-collect a specific object right now. But Python's reference-counting system can easily lead to memory leaks, especially when trying to interface with C-code. Little rings of co-referential dead objects can accumulate with a long-running Python program.
This is not true.
Ruby is capable of Perl-like one-liners that can be used on the command line for system administration. Python is unsuitable for this.
Hey, one liners work in Python too. Generally speaking, Python is a very popular system administration language; certainly Perl is still king, but at least in the Linux world Python is the clear up-and-coming system administration language.
Singleton is Total Nonsense? Hmmm...
- class _MasterRegistry(object):
- """ This singleton holds all the class registries. There can be multiple registries to hold different unrelated sets of classes that reside in the same process. These registries are named with strings, and are created on demand. The MasterRegistry module global holds the singleton. """
Where have I seen that...
You can, however, make a class that can provide a list of all living instances. That's what I did when I hacked Routes support into web.py:You can, however, make a class that can provide a list of all living instances. That's what I did when I hacked Routes support into web.py.class controller(object): registry = {} class __metaclass__(type): def __init__(cls, name, bases, dict): if not ('register' in dict): cls.register(cls) return @classmethod def register(cls, thecls): cls.registry[thecls.__name__] = thecls return @classmethod def subclasses(cls): return cls.registry.keys()Yeah, it's ugly. But it works.
That's to find all subclasses, not all instances. I remembered about the gc module, though, and this kind of works:def all_instances(a_class): return [obj for obj in gc.get_objects() if isinstance(obj, a_class)]
People use things like this to do reloading in Python. Once someone says "yes, I do reloading, and it works like a dream and never fails" then I'll be all over that. But it seems like there's some other tricks to do it right.
Whups, yeah.
A similar principle would work, though.
"Yeah, it's ugly. But it works."
That's the point. Ruby does it with elegance.
"As a convention people in Ruby use methods far more often."
Because there are no standalone functions in Ruby. Things like "puts" look like functions, but are actually instance methods of Kernel.
"This nonsense really has no place in such a high-level language. But Python makes things worse: empty lists, empty dictionaries, and empty tuples are false. "
This is one of my favorite python features, the fact that "if something:" will always do the right thing. Isn't this the whole point of using a high level language in the first place? :-)
I don't want to write "if lst.is_empty?" or "if len(lst)" - oh wait, 0 shouldn't be False so this should be "if len(lst)==0", right?
Hey, Ian, I already replied to this one on my blog too!
Ian, It was gracious of you to analyze and counter oinkoink's article point-by-point, rather than just summing it up as a steaming pile of crap. :-)
Re: one-liners on the command line. I published a little script at the Cookbook site (pyline) that lets you write ad-hoc CLI scripts in Python, suitable for piping. E.g. to print the md5 sum of all .py files in the current directory, you could (use md5sum, or you could) write:ls *.py | pyline -m md5 "'%s %s' % (md5.new(file(line).read()).hexdigest(), line)"
Prettier than Perl, though not by much. But Python is certainly suitable for CLI use.
>>> from __future__ import division >>> 7/3 2.3333333333333335
not exactly a library, but it's a provisional feature.
This program:
from __future__ import division
print 7/3
prints out 2.33333333 in Python 2.3 and newer. And 7//3 gives the old division behaviour which produces 2.
But it won't change the behaviour of / operator in other modules.
I guess you could say that Ruby is like Scheme or Smalltalk, and Python more like Lisp.
This is incorrect. Ruby's setup is similar to Scheme's, except that NIL is not false in Scheme. However, in Lisp, NIL is the only false value, and there is no boolean type, with T used to represent truth only by convention. This is not in any way similar to Python's behavior.
This article was thoroughly disappointing, especially given Mr. Bicking's involvement in the Python community. I wrote a full response to this article here. | http://www.ianbicking.org/re-ruby-and-python-compared.html | CC-MAIN-2015-32 | refinedweb | 1,928 | 66.94 |
What are the difference between While and Do While in Java Programming Language with a practical example?
Difference between While and Do While in Java
Although Do While loop and While loop in Java looks similar, they differ in the order of execution.
- In Java While loop, the condition is tested at the beginning of the loop, and if the condition is True, then only statements in that loop will be executed. So, the While loop executes the code block only if the condition is True.
- In Java Do While loop, the condition is tested at the end of the loop. So, the Do While executes the statements in the code block at least once even if the condition Fails.
Maybe you are confused, and I think you will understand it better when you see the example. Let us write the same program using Java While loop and Do While loop to understand the order of execution.
Java While loop example
In this Java program, we are declaring integer variable Number and assigned value zero to it. Next, We will check whether Number (value = 0) is greater than ten or not to fail the condition deliberately. There is one more System.out.println statement outside the While loop and this statement will execute after the while loop.
package Loops; public class WhileLoop { public static void main(String[] args) { int number = 0; while (number > 10) { System.out.println("Number is Greater Than 10"); } System.out.println("This Statement is Coming from Outside of while loop"); } }
OUTPUT
Java Do While Loop example
In this Java program, We are going to write the same example using Java Do while loop
package Loops; public class DoWhileDiff { public static void main(String[] args) { int number = 0; do { System.out.println("Number is Greater Than 10"); }while (number > 10); System.out.println("This Statement is Coming from Outside of while loop"); } }
OUTPUT
Although the condition fails, the statement inside the loop executed once. Because the do while loop condition tested after the execution of the statements.
We hope you understood the difference :) | https://www.tutorialgateway.org/difference-between-while-and-do-while-in-java/ | CC-MAIN-2020-16 | refinedweb | 346 | 62.27 |
First solution in Clear category for Caps Lock by dan_s
import re
def caps_lock(text: str) -> str:
index = [i.start() for i in re.finditer('a', text) if i.start() != 0] + [len(text)]
result = text[:index[0]]
for i in range(len(index) - 1):
result += text[index[i] + 1:index[i + 1]].upper() if i % 2 == 0 else text[index[i] + 1:index[i + 1]]
return result
if __name__ == '__main__':
print("Example:")
print(caps_lock("Why are you asking me that?"))
# These "asserts" are used for self-checking and not for an auto-testing
assert caps_lock("Why are you asking me that?") == "Why RE YOU sking me thT?"
assert caps_lock("Always wanted to visit Zambia.") == "AlwYS Wnted to visit ZMBI."
print("Coding complete? Click 'Check' to earn cool rewards!")
Oct. 15, 2020
Forum
Price
Global Activity
ClassRoom Manager
Leaderboard
Coding games
Python programming for beginners | https://py.checkio.org/mission/caps-lock/publications/dan_s/python-3/first/share/783f8e56c2e89cc71ccf9b5ac5df4ef4/ | CC-MAIN-2021-21 | refinedweb | 144 | 60.72 |
Overloaded record fields: a plan for implementation.
Design
SLPJ this section should be a careful design specfication.Id implicitly generated, corresponding to fields in datatype definitions, when the flag
-XOverloadedRecordFields is enabled.]).
If multiple constructors for a single datatype use the same field name, all occurrences must have exactly the same type, as at present.
A constraint
R { x :: t } is solved if
R is a datatype that has a field
x of type
t in scope. An error is generated if
R has no field called
x, it has the wrong type, or the field is not in scope.. in scope but the instance
Optionally, we could add a flag `-XNoMonoRecordFields` to disable the generation of the usual monomorphic record field selector functions. This is not essential, but would free up the namespace for other record systems (e.g.).
Even if the selector functions are suppressed, we still need to be able to mention the fields in import and export lists, to control access to them (as discussed in the representation hiding section).
AMG perhaps we should also have a flag to automatically generate the polymorphic record selectors? These are slightly odd: if two independent imported modules declare fields with the same label, only a single polymorphic record selector should be brought into scope.!. | https://ghc.haskell.org/trac/ghc/wiki/Records/OverloadedRecordFields/Plan?version=9 | CC-MAIN-2017-09 | refinedweb | 215 | 60.24 |
- Substitute Architectural Decision
- Refactor Architectural Structure
- Widespread Architectural Change
- Other Architectural Changes
- Migrating or upgrading (similar) APIs, frameworks or libraries
- Changing or unifying coding conventions
- Fixing compiler warnings and removing technical debt
- Consistently applying or changing aspects like logging or security
- Applying internationalization
- Migrate between languages, e.g. SQL vs. HQL
Options
I have been using some techniques since 2004 because as Code Cop I value code consistency. Two years ago I had the opportunity to discuss the topic with Alexandru Bolboaca and other experienced developers during a small unconference and we came up with even more options, as shown in the picture on the right. The goal of this and the next articles is to introduce you to these options, the power of each one and the cost of using it. A word of warning: This is a raw list. I have used some but not all of them and I have yet to explore many options in more detail.
Supporting Manual Changes With Fast Navigation
The main challenge of widespread changes is the high number of occurrences. If the change itself is small, finding all occurrences and navigating to them is a major effort. Support for fast navigation would make things easier. The most basic form of this is to modify or delete something and see all resulting compile errors. Of course this only works with static languages. In Eclipse this works very well because Eclipse is compiling the code all the time and you get red markers just in time. Often it is possible to create a list of all lines that need to be changed. In the past have created custom rules of static analysis tools like PMD to find all places I needed to change. Such a list can be used to open the file and jump to the proper line, one source file after another.
As example, here is a Ruby script that converts
pmd.xmlwhich is contains the PMD violations from the Apache Maven PMD Plugin to Java stack traces suitable for Eclipse.
#! ruby require 'rexml/document' xml_doc = REXML::Document.new(File.new('./target/site/pmd.xml')) xml_doc.elements.each('pmd/file/violation') do |violation| if violation.attributes['class'] class_name = violation.attributes['package'] + '.' + violation.attributes['class'] short_name = violation.attributes['class'].sub(/\$.*$/, '') line_number = violation.attributes['beginline'] rule = violation.attributes['rule'] puts "#{class_name}.m(#{short_name}.java:#{line_number}) #{rule}" end endThe script uses an XML parser to extract class names and line numbers from the violation report. After pasting the output into Eclipse's Stacktrace Console, you can click each line one by one and Eclipse opens each file in the editor with the cursor in the proper line. This is pretty neat. Another way is to script Vim to open each file and navigate to the proper line using
vi +<line number> <file name>. Many editors support similar navigation with the pattern
<file name>:<line number>.
Enabling fast navigation is a big help. The power this option is high (that is 4 out of 5 on my personal, totally subjective scale) and the effort to find the needed lines and script them might be medium.
Search and Replace (Across File System)
The most straight forward way to change similar code is by Search and Replace. Many tools offer to search and replace across the whole project, allowing to change many files at once. Even converting basic scenarios, which sometimes cover up to 80%, helps a lot. Unfortunately basic search is very limited. I rate its power low and the effort to use it is also low.
Scripted Search and Replace using Regular Expressions
Now Regular Expressions are much more powerful than basic search. Many editors allow Regular Expressions in Search and Replace. I recommend creating a little script. The traditional approach would be Bash with
sedand
awkbut I have used Ruby and Python (or even Perl) to automate lots of different changes. While the script adds extra work to traverse all the source directories and files, the extra flexibility is needed for conditional logic, e.g. adding an import to a new class if it was not imported before. Also in a script Regular Expressions can be nested, i.e. analysing the match of an expression further in a second step. This helps to keep the expressions simple.
For example I used a script to migrate Java's
clone()methods from version 1.4 to 5. Java 5 offers covariant return types which can be used for
clone(), removing the cast from client code. The following Ruby snippet is called with the name of the class and the full Java source as string:
shortName = shortClassNameFromClassName(className) if source =~ / Object clone\(\)/ # use covariant return type for method signature source = $` + " #{shortName} clone()" + $' end if source =~ /return super\.clone\(\);/ # add cast to make code compile again source = $` + "return (#{shortName}) super.clone();" + $' endIn the code base where I applied this widespread change, it fixed 90% of all occurrences as
clonemethods did not do anything else. It also created some broken code which I reverted. I always review automated changes, even large numbers, as jumping from diff to diff is pretty fast with modern tooling. Scripts using Regular Expressions helped me a lot in the past and I rate their power to high. Creating them is some effort, e.g. a medium amount of work.
Macros and Scripts
Many tools like Vim, Emacs, Visual Studio, Notepad++ and IntelliJ IDEA allow creation or recording Keyboard and or mouse macros or Application scripts. With them, frequently used or repetitive sequences of keystrokes and mouse movements can be automated, and that is exactly what we want to do. When using Macros the approach is the opposite as for navigation markers: We find the place of the needed change manually and let the Macro do its magic.
Most people I have talked to know Macros and used them earlier (e.g. 20 years ago) but not recently in modern IDEs. Alex has used Vim Scripts to automate repetitive coding tasks. I have not used it and relating to his experience. Here is a Vim script function which extracts a variable, taken from Gary Bernhardt's dotfiles:
function! ExtractVariable() let name = input("Variable name: ") if name == '' return endif " Enter visual mode normal! gv " Replace selected text with the variable name exec "normal c" . name " Define the variable on the line above exec "normal! O" . name . " = " " Paste the original selected text to be the variable value normal! $p endfunctionI guess large macros will not be very readable and hard to change but they will be able to do everything what Vim can do, which is everything. ;-) They are powerful and easy to create - as soon as you know Vim script of course.
Structural Search and Replace
IntelliJ IDEA offers Structural Search and Replace which performs search and replace across the whole project, taking advantage of IntelliJ IDEA's awareness of the syntax and code structure of the supported languages.. In other words it is Search and Replace on the Abstract Syntax Tree (AST). Additionally it is possible to apply semantic conditions to the search, for example locate the symbols that are read or written to. It is available for Java and C# (Resharper) and probably in other JetBrains products as well. I have not used it. People who use it tell me that it is useful and easy to use - or maybe not that easy to use. Some people say it is too complicated and they can not make it work.
Online help says that you can apply constraints described as Groovy scripts and make use of IntelliJ IDEA PSI (Program Structure Interface) API for the used programming language. As PSI is the IntelliJ version of the AST, this approach is very powerful but you need to work the PSI/AST which is (by its nature) complicated. This requires a higher effort.
To be continued
And there are many more options to be explored, e.g. scripting code changes inside IDEs or using Refactoring APIs as well as advanced tools outside of IDEs. I will continue my list in the next part. Stay tuned.
5 comments:
There is also a wonderful tool similar to Structural Search and Replace: Refaster, which allows to express the patterns in Java code. There is an analogue to SSR with PSI too: writing an ErrorProne check operating on the AST.
Thanks for the very useful article. On the macro part "...IntelliJ IDEA (by use of a plugin)..." - don't suppose you recall the plugin? Is it IdeaVim? TIA
kimptoc, sorry I do not know which plugin. I never used it, it just came up in the discussion. There seems to be native support for macros anyway.
Дмитрий, thank you. Refaster looks awesome. I will add it to my list in part two of the article where I will discuss tools working on the AST directly.
Thanks Peter. I’ve found the native macros a bit limited. | https://blog.code-cop.org/2018/08/options-architectural-change.html?showComment=1536574339892 | CC-MAIN-2019-35 | refinedweb | 1,485 | 64.81 |
Using the Zune Web API on Windows Phone 7
- Posted: Apr 07, 2011 at 11:48 AM
- 19,688 Views
- 6 Comments
Something went wrong getting user information from Channel 9
Something went wrong getting user information from MSDN
Something went wrong getting the Visual Studio Achievements
Fair Warning: You’re stepping in the undocumented land right now. Microsoft offers no support whatsoever for any of the endpoints mentioned below. Microsoft can also change any of these at any time without prior modification, so plan accordingly.
I use Zune a lot, having started with the 4GB player, and now it’s available on Windows Phone 7. Though the WP7 player is labeled as Music Hub, it appears under the Zune icon and incorporates Zune's organization, providing many of the same capabilities as the desktop client.
For quite a while, two public Zune endpoints have given out some very basic data (profile information and recent plays):
Both endpoints return plain XML-formatted data, and the information is pretty basic:
It is worth mentioning that Zune play count isn’t updated automatically as songs are played on the phone — it needs to be connected to the desktop Zune client to update the count.
That’s pretty much it. Now let’s look at the default XML result returned by the endpoints I mentioned above.
(Click to enlarge image)
Notice that I highlighted the user ID. For some strange reason, the ID returned isn’t compatible with the API endpoints I am going to describe below, so obtaining it for future reference is not something to rely on.
The default endpoints don’t give much information about the songs that were played (metadata-wise) and there is no information at all about existing friends.
NOTE: If your Zune account is linked to Xbox Live, your Xbox Live friends will be placed in the Zune list.
After taking a close look with WireShark when Zune desktop client was downloading profile information, I noticed that Microsoft uses a set of additional endpoints and the Zune card that is created locally does not use either of the two public URLs to retrieve data.
What triggered my curiosity was the fact that a friend list downloaded:
(Click to enlarge image)
Note that there is also a GUID associated with the user. This identifier is a bit different from what is returned by the default calls. So, the structure for the profile info endpoint appears as this:
I am not entirely sure exactly where this ID comes from, but the returned XML is pretty similar to the initial one, though it is formatted as an Atom feed (which is unrecognizable by browsers as a native feed—developers have to actually download the text contents and parse it).
If the user GUID is not known, it is possible to pass the Zune Tag (as pointed out by RoguePlanetoid), but for some reason in several cases it will be problematic because of a random redirect to the authentication page.
Here is a snapshot of its contents:
(Click to enlarge image)
Here's the line that most interested me when I reviewed the code:
<a:link rel=”related” type=”application/atom+xml”
href=”” title=”friends” />
There it was—the list of friends that is not available in the basic feeds. This feed is a valid Atom entity, and can therefore be opened in a browser. What surprised me is the fact that I don’t have to send any authentication data in order to view it, and it is nice to have it that way:
Going even further, the source of the page reveals some bonus details that are not displayed in the feed when it is rendered by a compatible web browser. Here is a snapshot:
This feed exposes the user GUIDs (and associated URLs) of my friends, so I can get profile information about them the same way I did it for me. Ultimately, you can search for friends of friends and so on to infinity (or, to be exact—to the extent of the Zune user base).
In my initial profile feed, there are links that represent recent songs. Though the basic feed only provides the names of tracks and the artist, by using the undocumented feed I can get some additional metadata associated with media content. Once again, the feed is viewable in a browser:
The necessary metadata is behind the curtain:
Additional available information includes play rank, disc number, track number, and an indicator that shows whether the song is explicit. Some songs, however, have more metadata than others.
Here is an example of an entity with more metadata associated with it:
(Click to enlarge image)
Notice that there are now song length details, the play rank is not empty, and there are actually disc and track numbers. Take a closer look at the rights tag—that’s where it’s possible to track current song offers on the Zune Marketplace, including the song encoding format (in this case 192kbps WMA), the type of purchase (Album), and the file size. For some offers also provide the price (which can be shown in both USD and Microsoft Points):
If a song is registered with enough additional metadata, the artist picture displays in the Zune window (if in play mode and not playlist) as the song plays.
Ultimately, this data significantly enhances my Zune experience on Windows Phone 7. I built a sample application that allows me to see my friends and generally keep up-to-date with my Zune stats.
(Click to enlarge an image)
To show a simple code snippet, here is how I am obtaining the data:
private void ParseXml(stringxmlDoc) { XDocument doc = XDocument.Parse(xmlDoc); txtZuneName.Text = doc.Root.Element("{}zunetag").Value.ToString(); txtRealName.Text = doc.Root.Element("{}displayname").Value.ToString(); txtLocation.Text = doc.Root.Element("{}location").Value.ToString(); txtPlayCount.Text = doc.Root.Element("{}playcount").Value.ToString(); txtLastUpdate.Text = doc.Root.Element("{}updated").Value.ToString(); XElement images = doc.Root.Element("{}images"); profileLocation = (from c in images.Elements() where c.Attribute("title").Value == "usertile" select c).First().Attribute("href").Value.ToString(); backgroundLocation = (from c in images.Elements() where c.Attribute("title").Value == "background" select c).First().Attribute("href").Value.ToString(); XElement playlists = doc.Root.Element("{}playlists"); recentPlaylist = (from c in playlists.Elements() where c.Attribute("title").Value == "BuiltIn-RecentTracks" select c).First().Attribute("href").Value.ToString(); mostPlayed = (from c in playlists.Elements() where c.Attribute("title").Value == "BuiltIn-MostPlayedArtists" select c).First().Attribute("href").Value.ToString(); }
Notice that I am directly passing the namespace. There is a way around this when using a regular Atom feed formatter, but I decided to go the simpler, XML way.
I’d love to see these features integrated with the mobile Zune client on Windows Phone 7. But for now, I have my own application that shows me the information.
I am pretty sure that this is just the surface of the actual Zune API – there is much more to it, like message exchange, badge assignment depending on the songs played and so on. Some of the more complex parts are less accessible due to existing protection mechanisms – for example, sending messages isn’t done directly through HTTP but rather through TCP in an encrypted manner. I am still looking into that.
In the meantime, the complete implementation of the project can be found on the Zune Data Viewer page you code an app that would force upload device (wp7) play counts of songs from the music+videos hub?
because play counts in my phone never uploads/updates whatever/however much i tried.
:(
Excellent article, thanks
@Jeffrey
Unfortunately, users cannot access the Zune hub by default, therefore there is no way I can integrate the play counter with that.
@IRB
Thanks!
i meant uploading to the ms servers so my zune social card play count moves forward.
Well since there is no hook to Zune itself (on the phone), there is no way you can send the play count from the phone. Also, as far as I know, the data about the playcount is not sent via the HTTP pipe, so you would need support for sockets.
opening thread.
Remove this comment
Remove this threadclose | http://channel9.msdn.com/coding4fun/articles/Using-the-Zune-Web-API-on-Windows-Phone-7 | CC-MAIN-2014-35 | refinedweb | 1,367 | 50.16 |
16 February 2010 18:25 [Source: ICIS news]
LONDON (ICIS news)--Around 7,000 workers will strike at all five of Total's French refineries for 48 hours from Wednesday in support of colleagues at the petrochemical giant’s Dunkirk site, which is likely to be closed down, a union spokesperson said on Tuesday.
The CGT spokesperson said around 2,000 direct employees of Total and 5,000 suppliers and subcontractors would join forces in order to send out a strong message.
It was not yet clear what impact the industrial action would have across the chemicals market, but ICIS news previously reported that the closure of the ?xml:namespace>
The refinery in
The union spokesperson said Total had delayed making a decision on the beginning of February on whether to close
The union want information on the strategy of Total, as it felt the refiner had plans to close all its plants in France and eventually Europe in order to raise demand and prices, especially as it had starting importing from the Middle East.
When asked if the strike would be successful, the union spokesperson said: “It will not be less negative, at least something will happen.”
A Total spokesperson said the company would hold an extraordinary meeting on March 29 to decide on the fate of the
The spokesperson added that no redundancies would take place if
For more on | http://www.icis.com/Articles/2010/02/16/9335235/7000-workers-to-strike-over-closure-of-totals-dunkirk.html | CC-MAIN-2014-49 | refinedweb | 232 | 50.54 |
On Tue, Jul 03, 2007 at 04:14:30PM +0100, Richard W.M. Jones wrote: > I'm not quite sure what the problem is (although the problem is in > xm_internal), but when you use xm_internal over remote, it sometimes > doesn't initialize its internal cache correctly, so it thinks that > there are no inactive domains. > > The fix is a one-liner which I hit upon by accident -- I don't really > understand why it works: Very peculiar - the nconnections stuff is incremented / decremented by the xenXMOpen & xenXMClose methods. So the change you show below should be identical to previous behaviour. Is something calling the xenXMClose method too many times maybe ? I guess some judicious use of syslog would show it up > > @@ -489,7 +487,7 @@ > xenXMOpen (virConnectPtr conn ATTRIBUTE_UNUSED, > const char *name ATTRIBUTE_UNUSED, int flags > ATTRIBUTE_UNUSED) > { > - if (nconnections == 0) { > + if (configCache == NULL) { > configCache = virHashCreate(50); > if (!configCache) > return (-1); > > But the attached patch also adds proper error messages to > xenXMConfigCacheRefresh -=| | https://www.redhat.com/archives/libvir-list/2007-July/msg00016.html | CC-MAIN-2015-22 | refinedweb | 160 | 58.21 |
Memory mapped files are used for three different purposes:
This article demonstrates a simple and generic disk file I/O using memory mapped files.
The class CWinMMFIO is a generic C++ class which can be used wherever file read and write operations are required. The class encapsulates the details of MMF I/O function calls. This class is ideal for reading bigger sized files spanning several giga bytes.
CWinMMFIO
It has been observed that read/write operations are much faster using MMF I/O than using either CFile or fstream objects.
CFile
fstream
Fundamentals of Windows memory management concepts is necessary to understand and modify the code.
Following is the public interface to the class:
/* Construction */
bool Open(const rstring& strfile, OPENFLAGS oflags);
bool Close();
/* I/O */
int Read(void* pBuf, quint nCount);
int Write(void* pBuf, quint nCount);
/* Position */
suint64 Seek(sint64 lOffset, SEEKPOS eseekpos);
suint64 GetPosition();
/* Length */
suint64 GetLength();
bool SetLength(const sint64& nLength);
/*error*/
void GetMMFLastError(rstring& strErr);scription
bool Open(const rstring& strfile, OPENFLAGS oflags);
Opens the file strfile in the access mode defined in the parameter oflags; the OPENFLAGS enumerator has two constants, OPN_READ and OPN_READWRITE. A zero byte file cannot be opened either for reading or writing.
strfile
oflags
OPENFLAGS
OPN_READ
OPN_READWRITE
bool Close();
Unmaps the view of the file, and closes open HANDLEs to the file mapping object and the opened file.
HANDLE
int Read(void* pBuf, quint nCount);
Reads nCount number of bytes into the buffer pBuf; if nCount number of bytes are not available, then Read reads as many bytes available from the current position to the end of the file.
nCount
pBuf
Read
The caller must ensure that the buffer pBuf is at least nCount number of bytes wide. The function returns the actual number of bytes read. If the current file pointer position is at the end of the file and nCount is greater than zero, then Read returns zero.
int Write(void* pBuf, quint nCount);
Writes nCount number of bytes from pBuf to the file starting from the current file pointer position. The file size is extended by a quantum of 64KB whenever an attempt is made to write past the end of file. This length is defined by a LONG internal variable m_lExtendOnWriteLength. The file will be restored to its actual length when necessary.
LONG
m_lExtendOnWriteLength
suint64 Seek(sint64 lOffset, SEEKPOS eseekpos);
Sets the current file pointer to the location specified by lOffset relative to SEEKPOS eseekpos. The SEEKPOS enumerator has three constants SP_BEGIN, SP_CUR, and SP_END. SP_BEGIN specifies that the seek is relative to file beginning. SP_CUR specifies that the seek is relative to the current file pointer. SP_END specifies that the seek is relative to the end of file.
lOffset
SEEKPOS eseekpos
SEEKPOS
SP_BEGIN
SP_CUR
SP_END
suint64 GetPosition();
Returns the current file pointer position:
suint64 GetLength();
Returns the actual length of the file in bytes:
bool SetLength(const sint64& nLength);
Sets the length of the file to nLength bytes. If the length cannot be set, the return value will be false. Call GetMMFLastError to get the error message.
nLength
false
GetMMFLastError
void GetMMFLastError(rstring& strErr);
Call GetMMFLastError to get the error message in the form of a string whenever a function fails.
The Windows SDK function WriteFile allows the caller to write beyond the EOF by extending the file size as necessary. This facility is not available directly in memory mapped I/O. In order to write and extend the file beyond the current EOF, the view needs to be unmapped and the mapping object must be closed. After this, extend the file size (say by 64K) using the SetEndOfFile function, recreate the mapping object, and remap the file. The file must be restored to its actual length whenever the write operation completes.
WriteFile
SetEndOfFile
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
m_qwFileSize
using namespace std
Namespace usings are for your convenience, not for you to inflict on others: Never write a using declaration or a using directive before an #include directive.
Corollary: In header files, don't write namespace-level using directives or using declarations; instead, explicitly namespace-qualify all names. (The second rule follows from the first, because headers can never know what other header #includes might appear after them.)
#ifdef UNICODE
typedef basic_string<wchar_t> sstring;
#else
typedef basic_string<char> sstring;
#endif
manju_soham wrote:I am sorry to not have followed strict coding convention
manju_soham wrote:1. As you have pointed out qint and quint may not be necessary, I was only influenced by the coding convention that we follow here inside the company
manju_soham wrote:2. I have observed that 64 bit int operations are generally slower on 32-bit systems because the 64-bit int doesnt fit into a 32 bit register and so it has be broken into two 32-bit parts and operated upon. On a 32-bit machine I had a plan (which did not materialize) to create a C++ class to deal with 64-bit int operations, somewhat like LARGE_INTEGER structure but with overloaded methods like ++, = etc.
manju_soham wrote:3. The 'sstring' typedef was used to make the code ready for both ANSI and UNICODE build by just typedef'ing as follows
General News Suggestion Question Bug Answer Joke Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | http://www.codeproject.com/Articles/37201/Simple-File-I-O-Using-Windows-Memory-Mapped-Files | CC-MAIN-2015-18 | refinedweb | 906 | 57.4 |
This change implements the C library dependent portions of P0482R6 (char8_t: A type for UTF-8 characters and strings (Revision 6)) by declaring std::c8rtomb() and std::mbrtoc8() in the <cuchar> header when implementations are provided by the C library as specified by WG14 N2653 (char8_t: A type for UTF-8 characters and strings (Revision 1)) as adopted for C23.
A _LIBCPP_HAS_NO_C8RTOMB_MBRTOC8 macro is defined by the libc++ __config header unless it is known that the C library provides these functions in the current compilation mode. This macro is used for testing purposes and may be of use to libc++ users. At present, the only C library known to implement these functions is GNU libc as of its 2.36 release.
Reverting to draft status to address CI failures.
Replaced the _LIBCPP_HAS_C8RTOMB_MBRTOC8 macro with a negated version, _LIBCPP_HAS_NO_C8RTOMB_MBRTOC8 to follow the existing patterns present for absent declarations of fgetpos(), fsetpos(), and fgets().
Conditioned the std namespace declarations in <cuchar> on _LIBCPP_HAS_NO_C8RTOMB_MBRTOC8. Though the declarations specify _LIBCPP_USING_IF_EXISTS, that magic only works with Clang; the declarations need to be appropriately conditioned for use/testing of libc++ with gcc.
Added test libcxx/test/std/strings/c.strings/no_c8rtomb_mbrtoc8.verify.cpp to validate that _LIBCPP_HAS_NO_C8RTOMB_MBRTOC8 is correctly set for the C library under test.
Introduced a TEST_HAS_NO_C8RTOMB_MBRTOC8 macro in libcxx/test/support/test_macros.h. Though not strictly necessary, this is consistent with the existence of _LIBCPP_HAS_NO_FGETPOS_FSETPOS.
Planning changes to address CI build failures.
Corrected formatting and checking for a definition of _LIBCPP_GLIBC_PREREQ before attempting to use it.
.
Marked test libcxx/test/std/strings/c.strings/no_c8rtomb_mbrtoc8.verify.cpp as XFAIL on AIX.
In D130946#3697908, @tahonermann wrote:
.
The issue is that uchar.h is not C++-friendly on the platform. The error is because it tries to define char16_t and char32_t as typedefs.
Ah, thanks, @hubert.reinterpretcast! I marked the test as XFAIL.
CI builds now pass; this is ready for review.
In D130946#3699345, @tahonermann wrote:
Ah, thanks, @hubert.reinterpretcast! I marked the test as XFAIL.
Ah, thanks, @hubert.reinterpretcast! I marked the test as XFAIL.
Thank you, Tom; sounds good.
@ldionne, could you or a suitable delegate review this when time permits? (I understand if you are busy finalizing the LLVM 15 release).
Any libc++ members available to review? @ldionne or @Mordante?
Thanks for working on this! Here are some comments, but this looks mostly good already.
Does this complete the implementation of P0482R6? If yes, please update the status page and feature test macros. Otherwise, what is still missing?
I think this should also be guarded with _LIBCPP_STD_VER >= 20.
As a C++ implementation we are interested in which C++ version something got added. So please use that version instead of in which C version something got added. Same for the rest of the synopsis.
Thank you for the review @philnik! I'll post an update addressing some of the comments shortly. Responses included for other comments.
I expect that this does complete P0482R6, but I'll double check, report back, and update the status page accordingly.
With regard to updating feature test macros, I don't think there is anything to be done. P0482R6 only specifies the single __cpp_lib_char8_t feature test macro for the library. libc++ already defines that macro based on the prior P0482R6 implementation efforts and the recent implementation of P1423 bumped its value. Though P0482R6 is not explicit about this (either in prose or wording), it can be inferred that the feature test macro is not applicable to these declarations as it is not required to be defined by the <cuchar> or uchar.h headers. Additionally, since c8rtomb() and mbrtoc8() are expected to be provided by the C library, entangling the macro definition with the availability of those declarations would get messy. This is consistent with the behavior of libstdcxx.
That is an option, but leads to scenarios where the declarations are available in the global namespace via uchar.h but not in the std namespace via <cuchar>. I thought it made more sense to keep these in sync.
At present, libc++ omits the other char8_t related declarations (e.g., u8string) in C++20 mode when char8_t support is disabled (of course) but likewise omits them in pre-C++20 modes when char8_t support is enabled. What I would prefer to do (in a separate patch) is to match the libstdcxx behavior of declaring all of the char8_t related declarations based on char8_t enablement rather than on the C++ standard version. This would give users more flexibility for evaluating and addressing`char8_t` related migration concerns before migrating to C++20.
Things get kind of messy here. The declarations in <cuchar> were added in C++20. Since C++20 depends on C17, no version of C++ will require the uchar.h declarations until a future C++ standard that is based on C23 (which will be required by ISO to happen for C++26). Our choices are:
I'm inclined toward option 2.
I audited the P0482R6 wording and found evidence of declarations for everything except the polymorphic allocator related declarations:
This appears to be expected given that P0220R1 is still listed as in-progress in libcxx/docs/Status/Cxx17Papers.csv and that is still awaiting revisions and approvals.
I think the current state plus this patch suffices to consider P0482R6 complete. I'll update the status page to mark it complete with a note that the missing declarations are pending completion of polymorphic allocator support.
Then we can't consider it complete yet. It would be great though if you could mark it as Partial and add a note that only the std::pmr::u8string alias and std::hash<std::pmr::u8string> are missing.
Hmm. Having the declarations in uchar.h but not in cuchar would indeed be quite weird. OTOH having the declarations pre-C++20 would be an extension in the C library, which we might not want to support. I also suspect that you will find quite strong opposition to enabling char8_t pre-C++20. We are quite anti-extensions and have even removed a number of them over the last years. @ldionne Do you have any thoughts here?
Yes, options 2 sounds like the right thing.
That works; will do.
Addressed code review comments.
This is again ready for review pending successful CI builds and a decision on whether the std namespace declarations should be protected by _LIBCPP_STD_VER >= 20.
@ldionne, could you please share your thoughts on whether the std::c8rtomb() and std::mbrtoc8() declarations should be restricted to C++20 and later or provided consistent with the corresponding C declarations in the global namespace?
My preference would be to be strict (and hence not include them before C++20). That being said, it seems like we have a strong precedent everywhere in our C compatibility headers to include functions inside std:: whenever they are provided by the underlying C library. So I think the current approach is OK.
Is there a reason why we even need _LIBCPP_HAS_NO_C8RTOMB_MBRTOC8 at all? We have _LIBCPP_USING_IF_EXIST to eliminate the need for exactly this sort of stuff. Of course GCC doesn't implement it, however it would still work when compiling using Clang on a platform that uses glibc.
My first patch relied solely on _LIBCPP_USING_IF_EXIST, but that lead to CI build failures as can be seen at. It seems that all such unconditional uses of _LIBCPP_USING_IF_EXIST are only exercised in CI builds where the dependent declarations are present. I followed the precedent that appears to be in place for other such problematic cases; see _LIBCPP_HAS_NO_FGETPOS_FSETPOS for example.
_LIBCPP_HAS_NO_FGETPOS_FSETPOS predates the existence of _LIBCPP_USING_IF_EXIST. is a failure on GCC, which I would indeed expect because GCC does not implement the using_if_exists attribute.
I guess my question is: would you see an issue with supporting <cuchar> only on Clang, or on GCC when a suitable Glibc is present? Glibc 2.36 is pretty recent, so that would mean only on Clang at least for some time. IMO this is acceptable since libc++'s primary compiler is Clang.
I don't have a sense of how many people use libc++ with gcc. Since libc++'s <cuchar> does work with gcc today, removing support for it could legitimately be considered a regression.
A solution that limits <cuchar> support depending on the presence of a suitable Glibc release would, I think, look quite similar to what is implemented in this patch, so I don't see that as being an improvement. I looked for existing cases where a libc++ header is explicitly not supported for use with gcc and didn't find one. Are there any such existing cases?
Let's go with this.
I'd normally fight against the _LIBCPP_HAS_NO_C8RTOMB_MBRTOC8, but in this case that will preclude libc++ from being usable on GCC with essentially all version of glibc, since c8rtomb was added to it less than a month ago.
But just for the record, our normal policy is that compilers that don't support using_if_exists are only supported on platforms that implement a full C standard library, which would mean (if taken at the letter) that GCC isn't supported on Glibc < 2.36. In practice, let's make this work, but we're not going to start adding carve-outs for ancient C libraries (that's what I want to avoid by giving this rationale).
Thank you! I'll proceed with landing the changes as-is.
Understood. Note that this same issue will arise if/when Microsoft adds support for these functions to their C library implementation. Unless I'm mistaken, Microsoft doesn't offer a __attribute__((__using_if_exists__)) equivalent for Visual C++.
Understood. It might be worth establishing a support policy for various C library implementations. If, for example, libc++ only promised support for glibc versions less than 4 years old, then we could remove the _LIBCPP_HAS_NO_C8RTOMB_MBRTOC8 and related conditionals in 4 years (subject to use with other C libraries).
This change was responsible for the failure of the sanitizer-ppc64be-linux5955 build. The build failed with the following error:
/home/buildbots/ppc64be-sanitizer/sanitizer-ppc64be/build/llvm_build64/include/c++/v1/__config:1222:67: error: function-like macro '__GLIBC_USE' is not defined
# if _LIBCPP_GLIBC_PREREQ(2, 36) && (defined(__cpp_char8_t) || __GLIBC_USE(ISOC2X))
^
It seems that this CI configuration is run with a relatively ancient glibc version earlier than 2.25 (2.25 was released on 2017-02-01 and is the version that introduced the __GLIBC_USE macro). For the short term, I'm going to commit the following trivial change to allow the build to pass.
diff --git a/libcxx/include/__config b/libcxx/include/__config
index a6f3b4e88aa1..681c10306420 100644
--- a/libcxx/include/__config
+++ b/libcxx/include/__config
@@ -1218,7 +1218,7 @@ _LIBCPP_BEGIN_NAMESPACE_STD _LIBCPP_END_NAMESPACE_STD
// determining the latter depends on internal GNU libc details. If the
// __cpp_char8_t feature test macro is not defined, then a char8_t typedef
// will be declared as well.
-# if defined(_LIBCPP_GLIBC_PREREQ)
+# if defined(_LIBCPP_GLIBC_PREREQ) && defined(__GLIBC_USE)
# if _LIBCPP_GLIBC_PREREQ(2, 36) && (defined(__cpp_char8_t) || __GLIBC_USE(ISOC2X))
# undef _LIBCPP_HAS_NO_C8RTOMB_MBRTOC8
# endif
However, investigating this lead me to realize that the check for __GLIBC_USE(ISOC2X) will not work long term. Eventually, ISOC2X will be renamed to ISOC23 and this check will stop working. We have a couple of options available:
I'm inclined toward option 1 for two reasons: 1) use of glibc internal details like this is inherently fragile, and 2) There is no need for the C++ library to expose the C23 char8_t related declarations when builtin char8_t support is disabled. | https://reviews.llvm.org/D130946 | CC-MAIN-2022-40 | refinedweb | 1,909 | 64.71 |
.xibfile
In XCode, go to
File > New > Project... and select “Cocoa Application”. Call it “Foo”, then uncheck all of the “Use Storyboards”, “Use Core Data”, and other nonsense. You get a project which, when you run it, displays a window with the title “Foo”. How does that window get there?
Turns out, even though you unchecked “Use Nonsense”, you still get a nonsense file: that
MainMenu.xib. What is it, and how do we get rid of it? Cocoa applications begin with a call to
NSApplicationMain. In C and Objective-C, you call
NSApplicationMain from your
main function. The call to
NSApplicationMain never returns; instead, it sets up the UI event loop which runs until the program exits with the
exit function.
It is the
NSApplicationMain call which “loads the main nib file from the application’s main bundle”. (For “nib”, read “xib”: the “nib” format is an older syntax which was replaced with the XML-based “xib” format.)
It is unclear how
NSApplicationMain finds the “main xib file” which it loads. One way is via the
NSMainNibFile in your
Info.plist file. However, if you remove this key in the
plist file, Cocoa still finds your xib file. It will even find your xib file if you rename it
Foo.xib. It is as if Cocoa falls back to a general search for files ending in
.xib.
If, like me, you’re using Swift, it will also be unclear how
NSApplicationMain is called. You will have seen the similarly named
@NSApplicationMain annotation on your
AppDelegate class. You can see it in the default
AppDelegate.swift, which looks like:
import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! }
The
@NSApplicationMain annotation can be seen a bit like a macro. Roughly, it will create a
main.swift file with these contents:
import AppKit let app: NSApplication = NSApplication.shared() let appDelegate = AppDelegate() // Instantiates the class the @NSApplicationMain was attached to app.delegate = appDelegate _ = NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv)
The
main.swift file is special: it can contain top-level statements. It’s a bit like the body of the
main function in C. Replace
@NSApplicationMain with this
main.swift, and then you can remove your
MainMenu.xib file.
I wrote this because Vidrio has some random .xib file which I want to get rid of. This post is my own, and not associated with my employer.Jim. Public speaking. Friends. Vidrio. | https://jameshfisher.github.io/2017/03/17/removing-xib-file.html | CC-MAIN-2019-18 | refinedweb | 403 | 68.47 |
Szayel wrote:It's not the missions I need help with. I, er, how do you put this? I don't need help with HTML( Got for that.) and I don't need help with the hacking missions. But, I feel like I could use a teacher or a guide who can really explain the depths of programs and hacking techniques and how they work. Or at least a website where I can read up on it...
#include <stdio.h>
#include <time.h>
int main()
{
long long LONG;
LONG = time(NULL);
printf("I'll be here for a %ld time ;P", LONG);
}
Szayel wrote:I'm going to spice this place up like no one has ever seen! (In a good way, lol.)
LoGiCaL__ wrote:Szayel wrote:I'm going to spice this place up like no one has ever seen! (In a good way, lol.)
pronz of the chick on your avatar?
Users browsing this forum: No registered users and 0 guests | http://www.hackthissite.org/forums/viewtopic.php?p=69022 | CC-MAIN-2016-44 | refinedweb | 163 | 93.64 |
SM. The semantics of the timing model and of the associated markup must remain consistent across all profiles. Any host language that includes SMIL Boston Timing and Synchronization markup (either via a hybrid DTD or schema, or via namespace qualified extensions) must preserve the semantics of the model defined in this specification.
Some SMIL 1.0 syntax has been changed or deprecated. Only SMIL document players must support the deprecated SMIL 1.0 attribute names as well as the new SMIL Boston names. A SMIL document player is an application that supports playback of SMIL Language documents (i.e. documents with the associated MIME type "application/smil"). time,.
The SMIL Timing and Synchronization syntax and precise semantics are described in the following section. A set of symbols are used in the semantic descriptions:
B
d
AD
AE. The formal definitions of presentation and document begin and end are left to the host language designer (see also "Required host language definitions").
This section defines the set of timing attributes that are common to all of the SMIL synchronization elements.
@@ Need to define "local time" or find a different term. length of the simple duration is
specified using the
dur attribute. The attribute syntax is described
below. The normative syntax rules for each attribute value variant are described
below (in Timing Attribute
Values); a syntax summary is provided here as an aid to the reader.
<seq>time container.
If no
begin is specified, the default timing is dependent upon
the time container. Children of a
<par> begin by default
when the
<par> begins (equivalent to
begin="0"). Children of a
<seq> begin by
default when the previous child ends its active duration (equivalent to
begin="0"). Restarting elements).
In general, the earliest time in the list determines the begin time of the element. In the case where an element can begin multiple times, the next begin time is the earliest begin time after the current time. There are additional constraints upon the evaluation of the begin time list, detailed in Evaluation of begin and end time lists.
If there is an error in any individual value in the list of begin values,
only the individual value will be ignored (as though it were not specified),
but the rest of the list will not be invalidated. If no legal value is specified
in the list of begin values, the default value for
begin will
be used. know as timespace conversion, and is detailed in the section Converting between local and global times.
If there is any error in the argument value syntax for
dur ,
the attribute will be ignored (as though it were not specified).
If the element does not have a (valid)
dur attribute, the simple
duration for the element is defined to be the implicit duration of the element.
The implicit duration depends upon the type of an element. The primary
distinction is between different types of media elements and time containers.
Note that if a media element has time children (e.g.
animate
or
area elements), then it is also a
<par> time container. If the media element has no time
children, it is described as a simple media element.
clipBeginand
clipEndattributes on a media element can override the intrinsic media duration, and will define the implicit duration. See also the Media Object module.
<seq>,
<par>and
<excl>time containers, including media elements that are also time containers, the implicit simple duration is a function of the children of the time container. For details see the section Time container durations.
If the author specifies a simple duration that is longer than the "intrinsic" defined duration for a continuous media element, the ending state of the media (e.g. the last frame of video) will be shown for the remainder of the simple duration. This only applies to visual media - aural media will simply stop playing.
Note that when the simple duration is "indefinite", some simple use cases can yield surprising results. See the related example #4." ... />
In the syntax specifications that follow, allowed white space is indicated as "S", defined as follows (taken from the [XML10] definition for "S"):
S ::= (#x20 | #x9 | #xD | #xA)*
A begin-value-list is a semi-colon separated list of timing specifiers:
begin-value-list ::= begin-value (
S";"
Sbegin-value-list )? begin-value ::= (offset-value | syncbase-value | syncToPrev-value | event-value | media-marker-value | wallclock-sync-value)
An end-value-list is a semi-colon separated list of timing specifiers:
end-value-list ::= end-value (
S";"
Send-value-list )? end-value ::= (clock-value | syncbase-value | syncToPrev-value | event-value | media-marker-value | wallclock-sync-value).
Clock values have the following syntax:
An offset value has the following syntax:
offset-value ::= ( "+" | "-" )?( Clock-value )
An offset value allows an optional sign on a clock value, and is used to indicate a positive or negative offset. The offset is measured in local time on the parent time container.
The implicit syncbase for an offset value is dependent upon the time container:
<par>or an
<excl>, the offset is relative to the begin of the parent
<par>or
<excl>.
<seq>, the offset is relative to the active end of the previous child. If there is no previous child, the offset is relative to the begin of the parent
<seq>. See also The seq time container.
Note, only compliant SMIL document players are required to support the SMIL 1.0 syncbase-value syntax. Language designers integrating SMIL Boston Timing and Synchronization into other languages should not support this syntax.
smil-1-syncbase-value ::= "id(" id-ref ")" ( "(" ( "begin" | "end" | clock-value) ")" )?
ID reference values are references to the value of an "id" attribute of another element in the document.
Id-value ::= IDREF
The IDREF is a legal XML identifier.
A syncbase value has the following syntax:
Syncbase-value ::= ( Syncbase-element "." Time-symbol
)
( S ("+"|"-") S Clock-value )?
Syncbase-element ::= Id-value
Time-symbol ::= "begin" | "end"
A syncbase value starts with a Syncbase-element term defining the value of an "id" attribute of another element referred to as the syncbase element. The syncbase element must be another timed element contained in the host document. In addition, the syncbase element may not be a descendent of the current element. If the syncbase element specification refers to an illegal element, the syncbase-value description is ignored (although the entire time value list is not invalidated - only the particular syncbase value).
The syncbase element is qualified with one of the following time symbols:
The time symbol can be followed by an offset value. The offset value specifies an offset from the time (i.e. the begin or active end) specified by the syncbase and time symbol. The offset is measured in local time on the parent time container. If the clock value is omitted, it defaults to "0".
No embedded white space is allowed between a syncbase element and a time-symbol. White space will be ignored before and after a "+" or "-" for a clock value. Leading and trailing white space characters (i.e. before and after the entire syncbase value) will be ignored.
Examples:
begin="x.end-5s" : Begin
5 seconds before "x" ends
begin=" x.begin " : Begin when
"x" begins
begin="x.begin + 1m" : End 1 minute after
"x" begins
A sync-to-prev value has the following syntax:
SyncToPrev-value ::= ( "prev." Time-symbol )
( S ("+"|"-") S Clock-value )?
A sync-to-prev value is much like a syncbase value, except that the reserved token "prev" is used in place of the Syncbase-element term. The Time-symbol and optional Clock-value offset are as defined for syncbase values.
The previous element is the (timed) element that precedes this element within the parent time container (as reflected in the DOM). Note that the parent time container may not be the immediate parent of the current node, in some host documents.
If there is no previous element (i.e. if the current element is the first timed child of the parent time container), then the begin of the parent time container is used as the syncbase (note that the Time-symbol is ignored in this case). attribute is specified (the current element).
If this element has no associated layout (e.g. a time container in a SMIL
document), then some UI events may not be defined (e.g. mouse events). Note
that certain elements may specify a different default eventbase. E.g. the
SMIL Animation elements (
animate,
animateMotion,
etc.) specify that the default eventbase is the target element of
the animation. See also [[SMIL Animation]].
The event value must specify an Event-symbol. This term specifies the name of the event that is raised on the Event-base element. The host language designer must specify which types of events can be used. If an integrating language specifies no supported events, the event-base time value is effectively unsupported for that language.
The last term specifies an optional offset-value that is an offset from the time of the event. The offset is measured in local time on the parent time container. If this term is omitted, the offset is 0.
No embedded white space is allowed between an eventbase element and an event-symbol. White space will be ignored before and after a "+" or "-" for a clock value. Leading and trailing white space characters (i.e. before and after the entire eventbase value) will be ignored.
Note that it is not considered an error to specify an event that cannot be raised on the Event-base element (such as click for audio or other non-visual elements). Since the event will never be raised on the specified element, the event-base value is effectively ignored. Similarly, if the host language allows dynamically created events (as supported by DOM-Level2-Events [DOM2Events]), all possible Event-symbol names cannot be specified, and so unrecognized names may not be considered errors. Host language specifications must include a description of legal event names, and/or allow any name to be used.
The semantics of event-based timing are detailed in the section Unifying Scheduling and Interactive Timing.
Examples:
begin=" x.load " : Begin when "load" is observed
on "x"
begin="x.focus+3s" : Begin 3 seconds after an "focus"
event on "x"-symbol S ")" )
The marker symbol is a string that must conform to the definition of marker names for the media associated with the Id-value.
Wallclock-sync values have the following syntax. The values allowed are based upon several of the "profiles" described in [DATETIME], which is based upon [ISO8601]. Exactly the components shown here must be present, with exactly this punctuation. Note that the "T" appears literally in the string, to indicate the beginning of the time element, as specified in [ISO8601].
wallclock-val ::= "wallclock(" S (DateTime | WallTime):
No embedded white space is allowed in wallclock values, although leading and trailing white space characters will be ignored.
The presentation engine must be able to convert wallclock-values to a time
within the document. When the document begins, the current wallclock time
must be noted - this is the document wallclock begin. Wallclock
values are then converted to a document time by subtracting the document
wallclock begin, and then converting the time to the element's parent time
space as for any syncbase value, as though the syncbase were the document
body. )"
New element controls for element time behavior are under discussion. Note that an Accessibility requirement for control of the playback speed is related to (but may end up with different syntax different from) the speed control. In general, these time manipulations are suited to animation and non-linear or discrete media, rather than linear continuous media. Not all continuous media types will support time manipulations, e.g. streaming MPEG 1 video playing backwards. A fallback mechanism is described for these cases.
Three new attributes add support for timing manipulations to SMIL Timing, including control over the speed of an element, and support for acceleration and deceleration. The impact on overall timing and synchronization is described. A definition is provided for reasonable fallback mechanisms for media players that cannot support the time manipulations.
A common with duplicate this support. This makes the framework more difficult to extend and customize. In addition, this model allows any animation behavior to introduce individual syntax and semantics for these mechanisms. This makes the authoring model much harder to learn, and complicates the job of any authoring tool designer as well. Finally, this model precludes the use of these mechanisms on structured animations (e.g. a time container with a series of synchronized animation behaviors).
A much simpler model for providing the necessary support centralizes the needed functionality in the timing framework. This allows all timed elements to support this functionality, and provides a consistent model for authors basic time manipulations are proposed:
speed
accelerateand
decelerate
autoReverse
This support is often represented to authors as "Play Forwards, then
Backwards". Because so many common use-cases apply repeat to the modified
local time (as in the examples above), this function is modeled as modifying
the simple duration. As such,
autoReverse effectively. Speed
rotate
element itself can be very simple, for example interpolating. Note that. This is useful for animation, motion paths, etc. The values are expressed as a proportion of the simple duration (i.e. between 0 and 1), and are defined such that the simple duration is not affected (although the normal play speed is increased to compensate for the periods of acceleration and deceleration). Note that these attributes apply to the simple duration; if these attributes are combined with repeating behavior, the acceleration and/or deceleration occurs within each repeat iteration.
The sum of
accelerate and
decelerate must not exceed
1. If it does, the deceleration value will be reduced to make the sum legal
(i.e. the value of
accelerate will be clamped to 1, and then
the value of
decelerate will be clamped to
1-
accelerate ).
The details of the accelerate and decelerate modifications are described in Details of the time manipulations.-screen>
This defines "play forwards then backwards" functionality. The use of autoReverse effectively doubles the simple duration. When combined with repeating behavior, each repeat iteration will play once forwards, and once backwards. This is useful for animation, especially for mechanical and pendulum motion.>.
If the simple duration is indefinite, the element cannot repeat. In this
case, any
repeatCount attribute is ignored, although a
repeatDur attribute value can still constrain the active duration.
See also Computing the Active
Duration.
At most one of
repeatCount or
repeatDur should
be specified. If both are specified (and the simple duration is not indefinite),
the active duration is defined as the minimum of the specified
repeatDur, and the simple duration multiplied by
repeatCount. For the purposes of this comparison, a defined
value is considered to be "less than" a value of "indefinite".
If the simple duration is indefinite, any
repeatCount attribute
will be ignored. Any
repeatDur attribute value (other than
"indefinite") will be used to constrain the indefinite simple duration. See
also the examples below describing
repeatDur and an indefinite
simple duration.
If the simple duration is 0, any
repeatCount attribute will
be ignored. Any
repeatDur attribute value will be used to define
the active duration by showing the state of the element for the specified
duration (this may be constrained by an
end value - see
Controlling active duration). See also the
examples below describing
repeatDur and a simple duration of
0).
@@ If simple duration is 0 and repeatCount is "indefinite" is the active duration 0 or indefinite?
If an element specifying audio media has a simple duration of 0 (e,g, because
of
clipBegin and
clipEnd values), nothing should
played even if the repeatDur specifies an active duration. The time model
behaves according to the description, but no audio should be played.
These rules are included.
<seq>element with the stated number of copies of the element without the "repeat" attribute as children. All other attributes of the element, including any begin delay, are included in the copies..
SMIL Boston provides an additional control over the active duration. The
end attribute allows the author to constrain the active duration
of the animation by specifying an end value using a simple offset, a time
base, an event-base or DOM methods calls. The
end attribute
generally constrains the active duration that is otherwise defined
by
dur and any repeat behavior, although it will extend an
implicit simple duration (see examples below). The rules for combining
the attributes to compute the active duration are presented in the next section,
Computing the active duration.
The normative syntax rules for each attribute value variant are described in the section Timing Attribute Values; a syntax summary is provided here as an aid to the reader.
endElement()method call.
If
end specifies an event-value or syncbase-value that is not
resolved, the value of
end is considered to be "indefinite"
until resolved. Restarting elements).
In general, the earliest time in the.
The end value generally constrains all other values, and does not extend
the active duration. However it will extend an implicit simple
duration. In the following example, the
dur attribute is
not specified, and so the simple duration is defined to be the implicit media
duration. In this case (and this case only) the value of
end
will extend the active duration if it specifies a duration greater than the
implicit (media) duration. For the difference between the implicit
simple duration and the active duration, the ending state of the media (e.g.
the last frame of video) will be shown. This only applies to visual media
- aural media will simply stop playing, or will not play at all if the implicit
simple duration is 0 (e,g, because of
clipBegin and
clipEnd values).
In the following example, the video will be shown for 8 seconds, and then the last frame will be shown for 2 seconds.
<video end="10s" src="8-SecondVideo.mpg" .../>. These cases arise from
the use of negative offsets in the sync-base and event-base forms, and authors
should be aware of the complexities this can introduce. See also
Handling negative offsets. clicks on the "gobtn" element. The active duration will end 30 seconds after the parent time container begins. Note that if the user has not clicked on the target element before 30 seconds elapse, the element will never begin.
<par> <audio src="music.au" begin="gobtn.click" repeatDur="indefinite" end="30s" ... /> </par>
The defaults for the event syntax make it easy to define simple interactive behavior. The following example stops the image when the user clicks on the element.
.
This section still needs work - and will change in the next day or two.
The table in Figure 3 defines a set of "forms" for the simple duration. These forms are used in the table in Figure 4 to delineate the possible combinations of attributes that can contribute to the active duration.
Figure 3 - Describing the simple duration
@@There are two forms of table 4 presented. We are trying to decide which presents the information more effectively. You be the judge which makes more sense, which is clearer, and which we should include. Both use essentially the same terminology, and present the same semantics (i.e. there should be no discrepancy in the semantics described, but rather only differences in how the information is presented).
The table in Figure 4 shows the semantics of all possible combinations of
simple duration,
repeatCount and
repeatDur, and
end. The following conventions are used in the table:
repeatCountand
repeatDurattributes are specified as either:
endattribute column specifies the end value obtained by evaluating the the attribute value according to the rules described in Controlling active duration and Evaluation of begin and end time lists. Note that a list of values yields a single end value at any given point of evaluation.
Note in particular that where a value specifies "unresolved", that the table will be reevaluated (generally using a different row) if and when the associated value becomes resolved. For example if the element specifies:
<audio src="5-second.au" end="foo.click" />
The active duration is initially defined as equal to the (implicit finite) simple duration. If the user clicks on "foo" before 5 seconds, the end value becomes resolved and the active duration table is re-evaluated to be MIN( d, end-B) which causes the element to end at the time of the click.
Some of the rules and results that are implicit in the table, and that should be noted in particular are:
endand
durare specified but neither of
repeatCountor
repeatDurare specified, then the active duration
ADis defined as the minimum of the simple duration and the duration defined by
end.
endis specified (i.e. none of
dur,
repeatCountor
repeatDurare specified), then the active duration
ADis defined as the duration defined by
end(in this case
endoverrides any implicit simple duration).
endand either (or both) of
repeatCountor
repeatDurare specified, the active duration
ADis defined by the minimum duration defined by the respective attributes.
ADdivided by the simple duration
d(this may yield partial repeat iterations, just as
repeatCountcan specify).
Note that while the active duration is computed according to the rules in the table, the parent time container places constraints upon the active duration of all children. These constraints may cut short the active duration of any child, and so override the definition described here. For more information, see the section Time Container constraints on child durations.
The following symbols are used in the table as a shorthand:
@@This is a form of the table that has more rows, but may be clearer in delineating the different cases. It uses the term "unresolved indefinite" for end values, which is semantically equivalent to "unresolved" in the second table.
@@Note that in both table the handling of explicit 0 is a bit messy. This is only needed if we want to say that simple Dur of 0 and repeatCount of "indefinite" yields a 0 active duration, rather than an indefinite AD. The tables would simplify if we went with the latter.
Where the Active duration has a "+" suffix, the value may be reevaluated at some point. The footnotes within the row indicate when the value will be reevaluated. Note that when a value is re-evaluated, a different row in the table may apply.
Figure. 4a: Computing the active duration for different combinations
of the simple duration,
repeatDur and
repeatCount,
and
end.
1 reevaluate if/when
end becomes resolved by event
2 reevaluate if/when
end becomes resolved by DOM
3 reevaluate when simple duration is resolved
@@This is a form of the table that has fewer rows, and does not call out the values that may be re-evaluated.
Note that any row that includes an "unresolved" value may be re-evaluated at some point (i.e. if the value becomes resolved). Note that when a value is re-evaluated, a different row in the table may apply.
Figure. 4b: Computing the active duration for different combinations
of the simple duration,
repeatDur and
repeatCount,
and
end.
It is possible to combine scheduled and interactive timing, e.g.:
duration
of the actual audio media "audio.au").
It is possible to declare both a scheduled duration, as well as an event-based active end. This facilitates what are sometimes called "lazy interaction" use-cases, such as a slideshow that will advance on its own, or in response to user clicks:
.
By default when an element's active duration ends, it is no longer presented (or its effect is removed from the presentation, depending upon the type of element). Freezing an element extends it, using the last state. For discrete media, the media is simply displayed as
it would be during the active duration. For continuous media, the "frame"
that corresponds to the end of the active duration is shown. For algorithmic
media like animation, the value defined for the end of the active duration
should be used. The syntax of the fill attribute is the same as in
SMIL 1.0, with two extensions:
This attribute only has an effect on visual media elements. Non-visual media elements (audio) should ignore this.
Note that
<a> and
<area> elements are
still sensitive to user activation (e.g. clicks) when frozen. See also the
SMIL 1.0 specification [SMIL10].
The default value of the
fill attribute depends on the element
type, and whether the element specifies any of the attributes that define
the simple or active duration.
<par>,
<seq>and
<excl>), the default value is "remove".
dur,
end,
repeatCountor
repeatDurare specified on the element, then the default value of
fillis "freeze".
An element with
fill="freeze" is extended according to the parent
time container:
<par>, the element is frozen to extend to the end of the simple duration of the
<par>. In this case,
fill="freeze"is equivalent to
fill="hold".
<seq>, the element is frozen to extend to the begin of the next element in the
<seq>. This will fill any gap in the presentation (although it may have no effect if the next element begins immediately).
<excl>, the element is frozen to extend to the begin of the next element to be activated in the
<excl>. This will fill any gap in the presentation (although it may have no effect if the next element interrupts the current element). Note that if an element is paused, the active duration has not ended, and so the
fillattribute does not (yet) apply. See also the section The
excltime container..
@@Need a good example of freeze on a time container, showing both how it extends any frozen children, as well as how it cuts off and freezes any children that were active at the end..
restart= "always | whenNotActive | never" there are several ways that an element element restarts, other elements defined to begin relative to the begin or active end of the restarting element may also restart (subject to the value of
restarton these elements).
When an element restarts, the primary semantic is that it behaves as though this were the first time the element had begun, independent of any earlier behavior. Any effect of an element playing earlier is no longer applied, and only the current begin "instance" of the element is reflected in the presentation.
The synchronization relationship between an element and its parent time container is re-established when the element restarts. A new synchronization relationship may be defined. See also Controlling runtime synchronization behavior.
As with any begin time, if an element is scheduled to restart after the end of the parent time container simple duration, the element will not restart.
Note that if the parent time container (or any ascendant time container)
repeats or restarts, any state associated with
restart="never"
will be reset, and the element can begin again normally. See also
Resetting element state.
The restart setting for an animation is evaluated when the syncbase element
restarts, when the eventbase event happens, or when the DOM method call (e.g.>
See also "The SMIL Integration Module" for details of language profiles.:
.
SMIL Boston specifies three time containers: <par>, <seq>, and <excl>.
<par>container defines a simple parallel time grouping in which multiple elements can play back at the same time.
The default syncbase of the child elements of a
<par>
is the begin of the
<par>. This is the same element
introduced with SMIL 1.0.
The
<par> element supports all element timing.
<seq>container defines a sequence of elements in which elements play one after the other.
This is the same element introduced with SMIL 1.0, but the semantics (and allowed syntax) for child elements of a <seq> are clarified. The default syncbase of a child element is the active end of the previous element. Previous means the element that occurs before this element in the sequence time container. For the first child of a sequence (i.e. where no previous sibling exists), the default syncbase is the begin of the sequence time container.
Child elements may define an offset from the syncbase, but may not define
a different syncbase (i.e. they may not define a begin time relative to another
element, or to an event). Thus, the syncbase of child elements of a sequence
is always the same as the default syncbase. Note however that child elements
may define an
end that references other syncbases,
event-bases, etc.
For children of a sequence, only the offset begin values are legal. None of the following begin values may be used:
No constraints are placed upon the
end argument values.
The
<seq> element itself supports all element timing.
When a hyperlink traversal targets a child of a
<seq>, and the target child is not currently active, part
of the seek action must be to enforce the basic semantic of a
<seq> that only one child may be active a given time.
For details, see Hyperlinks and timing
and specifically Implications
of beginElement() and hyperlinking for seq and excl time containers.
SMIL Boston defines a new time container,
<excl>.
<excl>are grouped into categories, and the pause/interruption behavior of each category can be controlled using the new grouping element
<priorityClass>.
The default syncbase of the child elements of the
<excl> is indefinite (i.e. equivalent to
begin=>.
The
<priorityClass> element is transparent to timing,
and does not participate in or otherwise affect the normal timing behavior
of its children (i.e. it only defines how elements interrupt one another).
Child elements of the
<priorityClass> elements are
time-children of the
<excl> element (i.e. the parent
<excl> of the
<priorityClass> elements).
Each
<priorityClass> element describes a group of children,
and the behavior of those children when interrupted by other time-children
of the
<excl>. The behavior is described in terms of
peers, and higher and lower priority elements.
Peers are those elements within the same
<priorityClass> element. The
priorityClass
elements are assigned priority levels based upon the order in which they
are declared within the
excl. The first
<priorityClass> element has highest priority, and the
last has lowest priority.
When one element within the
<excl> begins (or would normally
begin) while another is already active, several behaviors may result. The
active element may be paused or stopped, or the interrupting element may
be deferred, or simply blocked from beginning. When elements are paused or
deferred, they are added to a queue of pending elements. When an active element
completes its active duration, the first element (if any) in the queue of
pending elements is made active. The queue is ordered according to rules
described in Pause queue semantics.
The careful choice of defaults makes common use cases very simple. See the examples below.
<excl>time-children, and the pause/interrupt behavior of the children. If a
<priorityClass>element appears as the child of an
<excl>, then the
<excl>can only contain
<priorityClass>elements (i.e. the author cannot mix timed children and
<priorityClass>elements within an
<excl>).' >
If no
<priorityClass> element is used, all the children
of the
<excl> are considered to be peers, with
the default
peers
behavior "stop".
Note that the rules define the behavior of the currently active element and the interrupting element. Any elements in the pause queue are not affected (except that their position in the queue may be altered by new queue insertions).
peers= " stop | pause | defer | never "
<priorityClass>will interrupt one another.
peers.
excltime container). The paused element is added to the pause queue.
higher= " stop | pause "
<priorityClass>.
<priorityClass>is active, the active child element is simply stopped.
<priorityClass>is active, the active child element is paused and will resume when the new (interrupting) element completes its active duration (subject to the constraints of the
excltime container). The paused element is added to the pause queue.
higherattribute.
lower= " defer | never "
<priorityClass>.
<priorityClass>is active, the new (interrupting) element is deferred until the active element completes its active duration. This can also be thought of as placing the new element in the pause queue, paused at its very beginning. The rules for adding the element to the queue are described below.
lowerattribute.
<priorityClass>is active, the new (interrupting) element is prevented from beginning. The begin of the new (interrupting) element is ignored, and it is not added to the queue.
When an element begin is blocked (ignored) because of the "never" attribute
value, the blocked element does not begin in the time model. The time model
should not propagate begin or end activations to time dependents, nor should
it raise
begin or
end events. similiar.
exclends normally (i.e. not when it is stopped by another, interrupting element), the element on the front of the queue is pulled off the queue, and resumed or begun (according to rule 2 or 3).
Note that if an element is active and restarts (subject to the
restart rule), it does not interrupt itself in the sense of
a peer interrupting it. Rather, it simply restarts and the queue is unaffected.
@.
<excl>).
To specify that a child of the
<excl> should begin playing
by default (i.e., when the
<excl> begins), specify
begin="0" on that child element. If children of an
<excl> are scheduled to begin at the same time, the evaluation
proceeds in document order. For each element in turn, the priorityClass semantics
are considered, and elements may be paused, deferred or stopped. For example:
<excl> <img src="image1.jpg" begin="0s" dur="5s"/> <img src="image2.jpg" begin="0s" dur="5s"/> <img src="image3.jpg" begin="0s" dur="5s"/> </excl>
Given the default 3rd:
<excl> <img src="image1.jpg" begin="0s".../> <img src="image2.jpg" begin="10s; image1.click".../> <img src="image3.jpg" begin="20s; image2.click".../> </excl>.
The
endSync attribute is only valid for
<par> and
<excl> time containers, and
media elements with timed children (e.g.
animate or
area elements). The
endSync attribute controls
the end of the simple duration of these containers, as a function of the
children. This is particularly useful with children that have "unknown" duration,
e.g. an mpeg movie, that must be played through to determine the duration.
@@ Add more info to the effect that: Note that paused children of an <excl> container have not ended their active duration. Moreover (something to explain the "Elements do not have to play to completion, but must have played at least once") (i try ...) elements with multiple activation due to multiple begin and end value has only to play once to be considered as having ended their active duration.
endSync= " first | last | all | id-ref "
<par>,
<excl>, or media element simple duration ends with the earliest active end of all the child elements. This does not refer to the lexical first child, or to the first child to start, but rather refers to the first child to end its active duration.
<par>,
<excl>, or media element simple duration ends with the last active end of the child elements. This does not refer to the lexical last child, or to the last child to start, but rather refers to the last active end of all children that have a resolved begin time.
<par>,
<excl>, or media element simple duration ends when all of the child elements have ended their respective active durations. Elements with indefinite or unresolved begin times will keep the simple duration of the time container from ending.
<par>,
<excl>, or media element simple duration ends with the specified child. The id must correspond to one of the immediate children of the
<par>time container.
<par ... endSync="movie1" ...>
Semantics of
endSync and indeterminate children:
endSync="first"means that the time container must wait for any element to actually end its active duration. It does not matter whether the the first element to end was scheduled or interactive.
endSync="last"means that the time container must wait for all elements that have a resolved begin, to end the respective active durations. Note that elements that had an interactive begin, but that became resolved before all scheduled elements ended, are added to the set of children that must end their active durations before the parent can end. This can chain, so that only one element is running at one point, but before it ends its active duration another interactive element is resolved. It may even yield "dead time" (where nothing is playing), if the resolved begin is after the other elements active end.
<excl>that are currently paused and waiting to resume will keep the simple duration of the time container from ending.
endSync="all"means that every child element of the time container must end the active duration. In the case of element with multiple begin times, or restarting elements, note that elements do not have to play to completion; they just must have played at least once (here "once" refers to an instance of an active duration, and not to one repeat iteration of a repeating element). When all elements have completed the active duration one or more times, the parent can end.
<excl>that are currently paused and waiting to resume (and have not already completed the active duration at least once) will keep the simple duration of the time container from ending.
endSync=[id-ref]means that the time container must wait for the referenced element to actually end its active duration. The id-ref must refer to a child of the time container. If the referenced child has an indefinite active duration, then the simple duration of the time container is also indefinite.
@@ Do we need a note to call out that in some cases, endSync may define an indefinite simple duration for the time container. This would flow "through the computing the active duration" table accordingly, using "implicit indefinite" as the simple()
The implicit duration of a time container is defined in terms of the children of the container. The children can be thought of as the "media" that is "played" by the time container element. The semantics are specific to each of the defined time container variants.
By default, the simple duration of a
<par> is defined
by the
endSync=last semantics. The simple duration will end
when all scheduled children have ended their respective active durations.
The simple duration of a
<par> container can be controlled
with the
dur and
endSync attributes. If the
dur attribute is specified, the
endSync attribute
is ignored. Using
endSync, the end of the simple duration can
be tied to the active end of the first child that finishes, or to the active
end of the last child to finish (the default), or to the active end of a
particular child element.
By default, the simple duration of a
<seq> ends with
the active end of the last child of the
<seq>.
If any child of a
<seq> has an indefinite active duration,
the simple duration of the
<seq> is also indefinite.
The implicit simple duration of an
<excl> container is
defined the same as for a
<par> container, using the
endSync=last semantics. However, since the default timing for
children of
<excl> is interactive, it will be common for
<excl> time containers to have indefinite simple duration.
For
endSync={last or all}: The time children and the intrinsic
media duration define the simple duration of the media element time container.
If a continuous media duration is longer than the extent of all the time
children, the continuous media duration defines the implicit simple duration
for the media element time container. If the media is discrete, this is defined
as for
<par> elements.
For
endSync={first}: The time children and the intrinsic media
duration define the simple duration of the media element time container.
The element ends when the first active duration ends, as defined above for
endSync on a
<par>, but no sooner than the
end of the intrinsic media duration of continuous media. If the media is
discrete, this is defined as for
<par> elements.
For
endSync={ID}: This is defined as for
<par> elements..
This semantic is similar to the case in which the author specifies a simple duration that is longer than the intrinsic duration for a continuous media element. Note that for both cases, although the media element is effectively frozen for the remainder of the simple duration, the time container local time is not frozen during this period, and any children will run normally without being affected by the media intrinsic duration.
Time containers place certain overriding constraints upon the child elements. These constraints can cut short the active duration of any child element.
All time containers share the basic overriding constraint: begin="5s" dur="indefinite" .../> <audio begin="prev on the video will be seen, but
it will not be seen to repeat, and the last second of the video will be cut
off.
Note the time container is itself subject to the same constraints, and so may be cut short by some ascendant time container. When this happens, the children of the time container are also cut off, in the same manner as for the last partial repeat in the example above.
In addition,
<excl> time containers allow only one child
to play at once. Subject to the
priorityClass semantics, the
active duration of an element may be cut short when another element in the
time container begins.
We need a few good examples to illustrate these concepts.
SMIL 1.0 defined constraints on sync-arc definition (e.g., begin=). If the defined sync would place the resolved element. See also Negative begin delays..
@@ If we allowed events on begin in children of sequence, we would have to refine this language to say that an element is sensitive after the active end of the previous element, and until its own active end.
The parent time container must be active for the child element to receive events.
Sequence children are only sensitive to events during their active duration. In the following example, all children listen to the same end event and it works as expected:
<seq> <img src="img1.jpg" end="foo.click" /> <img src="img2.jpg" end="foo.click" /> <img src="img3.jpg" end="foo.click" /> </seq>.
@@This 6 shows the legal transitions between the states of an element:
Figure 6: Basic - begin and
dur. Freezing elements).
In this specification, elements are described as having local "time". In particular, many offsets are computed in the local time of a parent time container. However, simple durations can be repeated, and elements can begin and restart in many ways. As such, there is no direct relationship between the local "time" for an element, and the real world concept of time as reflected on a clock. simple duration and "local time" should not be construed as real world clock time. For the purposes of SMIL Timing and Synchronization, "time" can behave quite differently from real world clock time.
The SMIL timing model assumes the most common model for interval timing. This describes intervals of time (i.e. durations) in which the begin time of the interval is included in the interval, but the end time is excluded from the interval. value sampled during the "frozen" state.
When repeating an element. However, the appropriate way to map time on the active duration to time on the simple duration is to use the remainder of division by the simple duration: handling the frozen state.
The effect of this semantic upon animation functions is detailed in the [SMIL-ANIMATION] module. describes extensions to SMIL 1.0 to support interactive timing of elements. These extensions allow the author to specify that an element should begin or end in response to an event (such as a user-input event like
active end time. The element still exists within the constraints of
the document, but the begin or active can be thought of as unresolved.
The event-activation support provides a means of associating an event with the begin or active:
<par begin="10s" dur="5s"> <audio src="song1.au" begin="btn1.click" /> </par>
If the user..
beginspecifies the event, the element begins and any specification of the event in
endis ignored for this event instance.
beginspecifies the event, then the behavior depends upon the value of restart:
restart="always", then a new begin time is resolved for the element based on the event time. Any specification of the event in
endis ignored for this event instance.
restart="never"or
restart="whenNotActive", then any
beginspecification of the event is ignored for this instance of the event. If
endspecifies.
These:
<audio src="bounce.wav" begin="foo.click" end="foo.click+3s" restart="whenNotActive"/>:
<audio src="bounce.wav" begin="foo.click" dur="3s" restart="whenNotActive"/>
Related to event-activation is link-activation. Hyperlinking has defined semantics in SMIL 1.0 to seek a document to a point in time. When combined with indeterminate timing, hyperlinking yields a variant on interactive content. A hyperlink can be targeted at an element that does not have a scheduled begin time. When the link is traversed, the element begins. Note that unlike event activation, the hyperlink activation is not subject to the constraints of the parent time container. The details of when hyperlinks activate an element, and when they seek the document timeline are presented in the section Hyperlinks and timing.
Speed, although it can make authoring somewhat more complex.clocks)> <animation begin="2s" dur="9s" speed=0.75 .../> </par>
The observed rate of play of the animation element is 1.5 times the normal play speed. The element begins 1 second after the par begins (the begin offset is scaled by the parent speed), and ends 6 seconds later (9/1.5).
The following example shows how an event based end combines with time filters:
<par speed=2.0> <animation begin="2s" dur="9s" speed=0.75 repeatCount="4" end="click" .../> </par>
This behaves as in the first example, but the animation element will repeat 4 times for a total of 24 seconds (in real time), unless a click happens before that. Whenever the click happens, the element ends. A variant on this demonstrates syncbase timing:
<par speed=2.0> <img id="foo" dur="30s" .../> <animation begin="2s" dur="9s" speed=0.75 repeatCount="4" end="click, foo.end" .../> </par>
The image will display for 15 seconds. The animation" .../> <animation begin="2s" dur="9s" speed=0.75 repeatCount="4" end="foo.end+6s" .../> </par>
The image will display for 15 seconds. The animation> <animation begin="2s" dur="9s" speed=0.75 repeatCount="4" end="foo.end+6s" .../> </par>
The video ignores the acceleration and the speed value, and plays at normal speed for 15 seconds. The simple (and active) duration are still constrained by the speed. The area element reflects what the video is playing, and so the area becomes active after 2 seconds and remains active for 4 seconds. The animation )screen>
A simple example is provided in the syntax description above..
Note that
repeatDur and
end are not affected by
the
autoReverse attribute (although
repeatCount
is).
<img ...> <animateMotion by="20, 0" dur="5s" autoReverse="true" repeatDur="15" end="click" fill="freeze"/> </img>
Accelerate and decelerate.
Speed..
In evaluating the list of begin values, one of two questions is asked:
The earliest time is used for example when an element is the target of a hyperlink activation (see also Hyperlinks and timing). The next begin time may be used by a scheduler when an element can begin more than once.
By the same token, a list of end values is evaluated for two cases:
The earliest time is used for example to calculate the simple duration of
a time container defined with
endSync. The next end time may
be used by a scheduler when an element can begin more than once.
Begin and end time lists are considered in tandem. Begin times can be constrained by an end specification, as well as by the parent time container. Note that if an end time is not resolved, or is specified as "indefinite", then it is considered to be "after" al begin times. The constraint rules are:
endlist are resolved and occur before a begin time, then the element does not begin.
Thus, for a given point when an element is not active, the next begin and
end time are derived from the
begin and
end lists
as follows:
If both Steps 1 and 2 fail, then the begin list only specifies resolved times in the past, or after the end of the parent time container. In this case, there is no (valid) begin time after the current time (although for the purposes of a hyperlink that targets the element, even an "invalid" time may be used with additional constraints - see Hyperlinks and timing).
If a begin time is found, then it must be checked against the list of end
times. If no
end attribute is specified, the end is "indefinite",
and any begin found above is valid. If any end values are specified, the
list is evaluated as follows:
If a valid begin and end value are found, the end value found with the rules above is the value used in Computing the Active Duration.
When it is specified that the element does not begin, begin and end events will not be raised in the DOM, and time dependents defined relative to the begin or end of this element will not be activated.
In contrast to the rules above, if a
beginElement() or a
beginElementAt() call specifies a begin time after the last
end time (with no unresolved end times), the active duration is indefinite,
as though end had been defined as "indefinite". Note that if
beginElement() or
beginElementAt() is called when
the parent time container is not active, the method call will have no
effect. If
beginElementAt() is called and specifies a
time after the end of the parent simple duration, the method call will have
no effect. See also Supported methods.
Hyperlinking semantics must be specifically defined within the time model elements with indeterminate timing,::.
After seeking a document forward, the document should be in the same state as if the user had allowed the presentation to run normally from the current time until reaching the element begin time (but had otherwise not interacted with the document). In particular, seeking the presentation time forward should also begin any other elements that have resolved begin times between the current time and the seeked-to time. The elements that are begun in this manner may still be active, may be frozen, or may already have ended at the seeked-to time. If an element has ended, it logically begins and ends during the seek. The associated DOM events are raised, and all time dependents are updated. Also any elements currently active at the time of hyperlinking should "fast-forward" over the seek interval. These elements may also be active, frozen or already ended at the seeked-to time. The net effect is that seeking forward to a presentation time puts the document into a state identical to that as if the document presentation time advanced undisturbed to reach the seek time.
If the resolved activation time for an element that is the target of a hyperlink traversal occurs in the past, the presentation time must seek backwards. Seeking backwards will rewind any elements active during the seek interval and will turn off any elements that are resolved to begin at a time after the seeked-to time. Note that resolved begin times (e.g. a begin associated with an event) are not cleared or lost by seeking to an earlier time. Note further that seeking to a time before a resolved begin time does not affect the interpretation of a "restart=never" setting for an element; once the begin time is resolved, it cannot be changed or restarted. Subject to the rules above for hyperlinks that target timed elements, hyperlinking to elements with resolved begin times will function normally, advancing the presentation time forward to the previously resolved time. When the document seeks backwards before a resolved begin for an element time, this does not reset the element
These hyperlinking semantics assume that a record is kept of the resolved begin time for all elements, and this record is available to be used for determining the correct presentation time to seek to. Once resolved, begin times are not cleared by hyperlinking. However, they can be overwritten by subsequent resolutions driven by multiple occurrences of an event (i.e. by restarting). For example:
<par begin="0"> <img id="A" begin="10s" .../> <img id="B" begin="A.begin+5s" .../> <img id="C" begin="click" .../> <img id="D" begin="C.begin+5s" .../> ... <a href="#D">Click here!</a> <.
If the time container were defined to repeat, or could restart, then all indeterminate times for children of the time container are cleared (reset to "indefinite") when the parent time container repeats or restarts. See also Resetting element state.
For a child of a sequence time container, if a hyperlink targeted to the child is traversed, this seeks the sequence to the beginning of the child. If the seek is forward in time and the child does not have a resolved begin time, the document time must seek past any scheduled active end on preceding elements, and then activate the referenced child. In such a seek, if the currently active element does not have a resolved active end, it should be ended at the current time. If there are other intervening siblings (between the currently playing element and the targeted element), the document time must seek past all scheduled times, and resolve any unresolved times as seek proceeds (time will resolve to intermediate values of "now" as this process proceeds). As times are resolved, all associated time dependents get notified as the intervening elements are activated and deactivated.).
@?
Note that the presentation agent need not actually prepare any media for elements that are seeked over, but it does need to propagate the sync behavior to all time dependents so that the effect of the seek is correct.". The effect of the changes depends upon the state of "foo" when the change happens.:
<img id="foo" begin="0" end="bar.end" .../> <img id="bar" begin="btn.click" dur="5s" .../>
Element "foo" will end when "bar" ends, however "bar" can restart on another click. When "bar" restarts, a new end is calculated, and "foo" is notified. However, as "foo" will not restart, the change is ignored. A variant on this illustrates a case when the time change does propagate through:
<img id="foo" begin="0" end="bar.end+10s" .../> <img id="bar" begin="btn.click" dur="5s" .../>
Element "foo" will end 10 seconds after "bar" ends. If "bar" is restarted within 10 seconds of when it first ended, "foo" will still be active, and the changed end time will propagate through. Using example times, if the user clicks on the "btn" element 8 seconds after the parent time container begins, "bar" begins at 8 seconds.
The rule is that once an element has ended its active duration, changes that affect its end time are ignored (within the current simple duration of the parent time container).
When an element restarts (or when an ascendant time container repeats or restarts), all child times are recalculated, and may again become indefinite. For example:
<img id="foo" begin="btn.click" end="mouseout" .../> <img id="bar" begin="btn.click" end="foo.end" .../>
Both elements will start when the "btn" element is first clicked. Element "foo" will end when "mouseout" is raised on the img. At this point, the active duration of "bar" will become defined (resolved), and "bar" will end the active duration. If the user clicks on the target element again, both elements will restart, and "bar" will once again have an indefinite active duration.
@@Add additional example with explanation. Note that if user clicks at 4s, image1 is never seen. The resolution of image end happens and sticks when image1 begin is evaluated.
<par> <img id="image3" dur = "24s" end="user.click"/> <img id="image1" begin ="10s" end="image3.end"/> </par>
The use of negative offsets to define begin times merely defines the synchronization relationship of the element. If </par>
The
video element cannot begin before the
par begins.
The begin is simply defined to occur "in the past" when the
par begins.
A begin or end time may be specified with a negative offset relative to an event or to a syncbase that is not initially resolved. When the syncbase or eventbase time is (eventually) resolved, the dependent time that is computed with a negative offset may occur in the past. The computed time defines the scheduled synchronization relationship of the element, even if it is not possible to begin or end the element at the computed time.
When a begin time is defined to be in the past, the element begins immediately,
but acts as though it had begun at the specified time (playing from an offset
into the media). The behavior can be thought of as a
clipBegin
value applied to the element, that only applies to the first iteration of
repeating elements. The media will actually begin at the time computed according
to the following equation:.
Media elements with an active duration of zero or with the same begin and end time trigger begin and end events, and propagate to time dependents. If an element's end time is before its begin time, no events are triggered (see also Evaluation of begin and end time lists).
Whether or not media is retrieved and/or rendered is implementation dependent.
When a time container repeats or restarts, all descendent children are "reset" with respect to certain state:
restartsemantics is reset. Thus, for example if an element specifies
restart="never", the element can begin again after a reset. The
restart="never"setting is only defined for the extent of the parent time container simple duration.
When an element restarts, the rules 1 and 2 are also applied to the element itself, although the rule or paused children, the pause queue
for the
<excl> is cleared..
The syncBehavior attribute is subordinate to any sync relationships defined by time containers, sync arcs, event arcs, etc. The syncBehavior attribute has no bearing on the formation of the time graph, only the enforcement of it.
@@..
@@ We need to move the general definition of the SMIL Default stuff elsewhere, and just specify the possible arg values here. Ideas where it should go?
The value of the syncBehavior and syncTolerance attributes are not inherited, but it is possible to set default behavior for elements or time containers using the SMILdefault syntax below.
The default value for syncTolerance is implementation dependent, but should be no greater than two seconds.
syncBehavior="locked". This allows a locked sync relationship to ignore a given amount of slew without forcing resynchronization. resolution.
syncBehavior:canSlip
syncBehavior:locked
syncTolerance: Clock-value
An additional.
The syncMaster attribute interacts with the syncBehavior attribute. An element with syncMaster set to true will define sync for the "scope" of the time container's synchronization behavior. That is, if the syncMaster element's parent time container has syncBehavior="locked", the syncMaster will also define sync for the ancestor time container. The syncMaster will define sync for everything within the closest ancestor time container that is defined with syncBehavior="canSlip". >
@@When this settles down, fill in subsections in TOC.
The host language designer must define what "presenting a document" means. A typical example is that the document is displayed on a screen.
The host language designer must define the document begin. Possible definitions are that the document begins when the complete document has been received by a client over a network, or that the document begins when certain document parts have been received.
The host language designer must define the document end. This is typically when the associated application exits or switches context to another document.
@@ Check to see if we really have issues with this, e.g. for specifying floating point values. Can we use this in our definitions of offset value?
The host language must specify the formats supported for numeric attribute
values. This includes integer values and especially floating point values
for attributes such as
keyTimes and
keySplines.
As a reasonable minimum, host language designers are encouraged to support
the format described in [CSS2]. The specific reference within the CSS
specification for these data types is
4.3.1 Integers and
real numbers.
@@ Need to talk about specifying which elements can be timed, and what it means to time them.
The set of elements that may have timing includes ??? elements defined in host languages...
@@Broken link to Handling errors - Do we need a section on this?
Host language designers may not relax the error handling specifications,
or the error handling response (as described in "Handling syntax errors").
For example, host language designers may not define error recovery semantics
for missing or erroneous values in the
begin or
end
attribute values.
Language designers can choose to integrate SMIL Timing and Synchronization as an independent namespace, or can integrate SMIL Timing and Synchronization names into a new namespace defined as part of the host language. Language designers that wish to put the SMIL Timing and Synchronization functionality in an isolated namespace should use the following namespace:
@@ URI to be confirmed by W3C webmaster.
Much of the related SMIL-DOM functionality is proposed in the [SMIL-DOM] section. We may need to go into further detail on the specific semantics of the interfaces - the sections below are placeholders.
Define rules on element and attribute access (inherit from and point to Core DOM docs for this). Define mutation constraints. This is currently covered in the [SMIL-DOM] section..
The [SMIL-DOM] section defines the initial set of time-related events that have been proposed.. The effective begin
time is the current presentation time at the time of the DOM method call.
Note that
beginElement() is subject to the
restart
attribute in the same manner that event-based begin timing is. If an element
is specified to disallow restarting at a given point,
beginElement() methods calls must fail. Refer also to the section
Restarting elements.
Calling
beginElementAt() causes the element to begin in the
same way that an element begins with event-based begin timing that includes
an offset.
beginElementAt()is positive, then the element will be restarted (subject to the
restartattribute.
Calling
endElement() causes an element to end the active duration,
just as
end does. Depending upon the value of the
fill attribute, the element effect may no longer be applied,
or it may be frozen at the current effect. Refer also to the section
Freezing elements. If an element is not currently
active (i.e. if it has not yet begun or if it is frozen), the
endElement() method will fail.
Interfaces are currently defined in the [SMIL-DOM] section.:
An element is considered to have scheduled timing if the element's start time is given relative to the begin or active end of another element. A scheduled element can be inserted directly into the time graph.
Begin and active end times in SMIL Boston.
More information on the supported events and the underlying mechanism is described in the DOM section of this draft [SMIL-DOM]. Boston.
Time manipulations allow the element's time (within the simple duration) to be filtered or modified. For example the speed of time can be varied to make the element play faster or slower than normal. The filtered time affects all descendents of the element. Several time manipulations are proposed for SMIL Boston. Time manipulation is primarily intended to be used with animation [SMIL-ANIMATION] (W3C members only).
Note that any time manipulation that changes the effective play speed of an element's time may conflict with the basic capabilities of some media players. The use of these manipulations is not recommended with linear media players, or with time containers that contain linear media elements, such as streaming video.
There are a number of unresolved issues with this kind of time manipulation, including issues related to event-based timing and negative play speeds, as well as many media-related issues. in the section Unifying Scheduling and Interactive Timing. time such as the end of a streaming MPEG movie (the duration of an MPEG movie is not known until the entire file is downloaded). When the movie finishes, determinate times defined relative to the end of the movie are resolved..
An image that illustrated the timeline might be useful here.>.
Insert illustration.
<par> <excl> <par id="p1"> ... </par> <par id="p2"> ... </par> </excl> <a href="p1"><img src="Button1.jpg"/></a> <a href="p2"><img src="Button2.jpg"/></a> </par>
This example models jukebox-like behavior. Clicking on the first image activates the media items of parallel container "p1". If the link on the second image is traversed, "p2" is started (thereby deactivating "p1" if it would still be active).?
Note that the specific syntax for beginEvent argument values is still under discussion.
<par> <excl> <par begin="btn1.click"> ... </par> <par begin="btn2.click"> ... </par> </excl> <img id="btn1" src=... /> <img id="btn2" src=... /> </par>.
Issue - should we preclude the use of determinate timing on children of
excl? Other proposals would declare one child (possibly the first)
to begin playing by default. Proposals include an attribute on the
<excl> container that indicate one child to begin playing by default.
For simple media elements (i.e. media elements that are not time containers) that reference discrete media, the implicit duration is defined to be indefinite. This can lead to surprising results, as in this example:
<seq> <img src="img1.jpg" /> <video src="vid2.mpg" /> <video src="vid3.mpg" /> </seq>
The default syncbase of a sequence is defined to be the effective active end of the previous element in the sequence, unless the active duration is indefinite in which case the default syncbase is the begin of the previous element.:
<seq repeat="10" end="stopBtn.click"> SMIL-DOM
beginElement()
method is called.
This is a placeholder for a set of authoring guidelines intended to help authors avoid potential mistakes and confusion, and to suggest best practices as intended by the authors.. | http://www.w3.org/TR/2000/WD-smil-boston-20000225/timing.html | CC-MAIN-2014-52 | refinedweb | 11,020 | 55.13 |
read Stanford University PLY polygonal file format More...
#include <vtkPLYReader.h>
read Stanford University PLY polygonal file format
vtkPLYReader is a source object that reads polygonal data in Stanford University PLY file format (see). It requires that the elements "vertex" and "face" are defined. The "vertex" element must have the properties "x", "y", and "z". The "face" element must have the property "vertex_indices" defined. Optionally, if the "face" element has the properties "intensity" and/or the triplet "red", "green", "blue", and optionally "alpha"; these are read and added as scalars to the output data.
Definition at line 42 of file vtkPLYReader.h.
Definition at line 45 of file vtkPLY.
A simple, non-exhaustive check to see if a file is a valid ply file.
This is called by the superclass.
This is the method you should override.
Reimplemented from vtkPolyDataAlgorithm. | https://www.vtk.org/doc/nightly/html/classvtkPLYReader.html | CC-MAIN-2017-51 | refinedweb | 140 | 60.01 |
Why aren’t VC firms focused on slow/modest growth startups?): ]
The number one job of a venture capitalist is to stay a venture capitalist.
This might sound cynical but, as a VC, if you don’t return enough money to your LPs (limited partners, a VC’s investors) you will not be able to raise your next fund. If you don’t raise your next fund, you’re not collecting management fees to pay yourself and your team, and you don’t have a chip stack to play in “the big game.”
If you want to STAY a venture capitalist you need to land these “dragon egg” investments — the ones that create enough value to give your LPs their money back. Dragon eggs are typically 20–40x your money back. So, you invest $7 million and get back $140–280 million.
That means, if you bought 20% of a startup for $7m, that startup was worth ~$35m, and then has to become a ~$700m to ~$1.4b exit for you to BREAK EVEN. Everyone makes money AFTER that investment, not before.
That is not easy.
VCs need to have double-digit returns every year (look up IRR for more on this) and essentially match stock market returns, with the chance of crushing them. If you match the stock market consistently, the thinking is you will eventually hit a Google or Facebook or Amazon.
“Stay in the game, stay in the game,” is the mantra.
The binary outcomes are just so yum yum, that you want to keep seeing flops (to use a poker analogy) and STAY. IN. THE. GAME.
So, the logical follow-up question is, why don’t LPs want to invest in VC funds that target slow growth startups?
That answer is even simpler, they have better options. If you want to return low single-digit returns, you can simply put your money in bonds, REITs or dividend-paying stocks — and not pay the significant fees associated with venture capital.
What about you, Jason?
For background, I’m an angel and seed investor, so my job is much different than a VC’s. I invest in 50+ startups a year and 24 of 25 investments do not result in a meaningful return (i.e., zero to 5x).
I’m banking on hitting a serious return every 25 investments, with serious being defined as greater than 50x, cash on cash (REALLY HARD TO DO).
So far, after 200+ investments, I’ve got Uber, Thumbtack, Wealthfront, Robinhood, Desktop Metal, Datastax, and Calm.com as outliers, with a couple of dozen startups doing well to very well. I would expect one or two more of those to break out, putting me at eight or 10 outlier investments (one every 20 to 25 investments).
Bottom line: there are zero LPs interested in funding startups with modest to normal growth prospects, and candidly, I don’t meet many founders who don’t want to build large businesses (obviously some selection bias there, as a Mount Rushmore-level angel investor, people don’t come to me with dry cleaners and pizzerias that often).
PS — I am blogging everyday this month! Check out my other blog posts below:
Day Eleven: “Why aren’t VC firms focused on slow/modest growth startups?”
Day Ten: “Podcast Recommendation: Cafe Insider & Stay Tuned with Preet”
Day Nine: “Podcast Recommendation: Bret Easton Ellis”
Day Eight: Day Eight: “Lean Management: The Power of the EOD Report”
Day Seven: “The Ultimate Outsider’s Hack: Read All The Biographies”
Day Six: “The Three Vendor Rule”
Day Five: “Should I move my #startup to Silicon Valley: the 2009 & 2019 answers compared”
Day Four: “How can I do an #MVP for a delivery service I want to start?”
Day Three: “As an #angel investor should I invest in a founder working on two projects (or working half time on one)?”
Day Two: “Chrome OS is the ultimate productivity hack & will exceed Mac OS marketshare — but can it challenge Windows?”
Day One: “How do you get an angel investor’s attention? | https://medium.com/@jason/why-arent-vc-firms-focused-on-slow-modest-growth-startups-11044c0a0c6e?source=email-f48f01afb31d-1547474604135-digest.reader------2-2------------------ba9951a4_8b0c_4c2c_9d34_0372e41001b6-3§ionName=author | CC-MAIN-2019-09 | refinedweb | 676 | 68.5 |
.
Help:Code Syntax Highlighting
For more information see: Extension:SyntaxHighlight_GeSHi (Extension Help). Note that this is a "new plugin" and its native syntax differs from that used on the wiki - which we have maintained for backwards compatability.
Inline code
Use {{Icode|your inline code fragment}} to markup up code fragments within the body of text. For example: "Class CActive is the base class of all Active Objects". This maps to the HTML <tt> tag.
Note: Replace the equals (=) and pipe (|) characters with the = and | codes respectively or this will not work.
Code blocks
The wiki allows you to specify code blocks syntax formatted for a large number of programming languages. You can also specify the initial line number of the block (if any) and a line that should be highlighted.
For example
- <code csharp> your code</code> - markup code as C#
- <code xml 5> your code</code> - markup code as XML and start line numbering from line 5
- <code cpp 6 your code</code> - markup code as C++, start line numbering from line 6, and highlight the 3rd line:
int main(int argc,char *argv){
int d;
d = argc + 1;
}
Syntax
<code [language] [n] [highlight="linenumber"] >source code here</code>
Parameters
- language: Code for any of the supported languages, including C# (csharp), C++ (cpp), XML (xml), Java (java) - see full list here.
- n: Line number to start with. A non numeric value (ie "n") will start the list at 001. NOTE that the numbering cycles back to 001 for line numbers greater than 1000.
- highlight="linenumber" : Marks the specified linenumber in highlight (line of the code sample, irrespective of "n" value)
The "default syntax" without parameters is the same as the pre tag: <code>
public class MyClass extends SomeOtherClass
{
public MyClass()
{
System.exit(); // surprise, you're dead!
}
}
Examples
Specify language (java)
<code java>
Line numbers
<code cpp 5>
int main(int argc,char *argv){
int d;
d = argc + 1;
}
Highlighting (with line numbers)
<code cpp 6
int main(int argc,char *argv){
int d;
d = argc + 1;
} | http://developer.nokia.com/community/wiki/Help:Code_Syntax_Highlighting | CC-MAIN-2015-11 | refinedweb | 337 | 66.78 |
A while loop is another kind of loop control structure. The loop has initial condition and a test condition to pass before the actual loop body starts. The loop is incremented or decremented inside of the loop body.
The general structure of while loop is given below.
initial expression; while( test condition) { do something; increment or decrement loop; }
The initial expression is a simple assignment where a loop starts with 0 or 1. The test condition can be an expression, return from a function, or a constant. The loop is incremented or decremented inside the body of the loop.
You can note the similarity between while loop and for loop, both contains 3 expressions. However, with while loop the initialization happens before the loop body starts.
Graphical Representation of while loop
A graphical representation is helpful when you create a flowchart of your C++ program. Here is the graphical representation of while loop.
Example Program:
//While loop #include <cstdlib> #include <iostream> using namespace std; int main() { //variable declaration and initialization int number,i; int sum = 0; //read values and computing total for(i = 0;i<5; i++) { cout << "Enter Number:"; cin >> number; sum = sum + number; } //printing output cout << "Sum = " << " " << sum << endl; system("PAUSE"); return EXIT_SUCCESS; }
Output:
Enter Number:23 Enter Number:55 Enter Number:66 Enter Number:67 Enter Number:76 Sum = 287 | https://notesformsc.org/c-plus-plus-while-loop/ | CC-MAIN-2021-04 | refinedweb | 223 | 53.41 |
A couple of days ago I was in the need of automating simple browsing on the internet. To be more specific I needed to visit my company website, click on a couple of specific links and then repeat this operation every few minutes.
You are probably thinking that there is software that can perform what is called «automation test» but I am just too lazy to surf the web looking for a free program and writing code is really more fun so there was just one thing in my mind…
For this project, we’ll use Splinter.
According to the official website,
Splinter is an open source tool for testing web applications using Python. It lets you automate browser actions, such as visiting URLs and interacting with their items.
Splinter is just an abstraction layer on top of Selenium and makes easy to write automation tests for web applications.
So, let’s pretend that we want to automate research on bing.com.
First of all, we need to install Splinter. To do it, open a terminal and do a
pip install splinter
Once Splinter’s been installed we need to choose the browser to use.
By default, the system would use Firefox, but you can choose to use Chrome or IE as well.
Today we’ll use Chrome, so you will need to install both the Chrome browser and the Chrome web driver that you can find here.
If you use Windows or Linux the driver is just a standalone executable that you have to put in a directory listed in your PATH environment variable, if you use macOS you can get it through homebrew with
$ brew install chromedriver
Please note that if you prefer to use Firefox you will need to install Gekodriver.
Now, if you have installed both Splinter and a web driver, you can start coding:
from splinter import Browser with Browser('chrome') as browser: # Visit URL url = "" browser.visit(url) # fill the query form with our search term browser.fill('sb_form_q', 'mastro35 twitter') # find the search button on the page and click it button = browser.find_by_id('sb_form_go') button.click()
Once run, this script will let you achieve three major results:
- You will see how easy it is to automate a simple search on Bing
- You will have the access to my Twitter profile in case you want to follow me 🙂
- You will have probably doubled the statistic about the daily Bing.com visits :))
However, this is just a small example of what you can do with Splinter. It also allows you to find elements in page by their CSS, XPath, tag, name, text, id or value and if you want a more accurate control of the page or you need to do something more (like interacting with the old «frameset» tags) it expose also the web driver that allows you to use the Selenium low-level methods. There’s no need to say that you can obviously get also the HTTP status code of the page you visited (using browser.status_code) and the HTML of the page (using browser.html).
Besides, the Splinter project is super well documented and that’s really important when you have to deal with third-party libraries.
One last thing: if you want to create an automation test that runs without the browser window, you can try PhantomJS. According to their website,
PhantomJS is a headless WebKit scriptable with a JavaScript API. It has fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG.
PhantomJS is simply amazing and works great with Splinter.
Enjoy! | https://www.thepythoncorner.com/2016/11/web-test-automation-in-python/ | CC-MAIN-2020-05 | refinedweb | 599 | 64.85 |
NOTE: jQuery Templates is a deprecated technology. If you are looking for a traditional approach to managing cascading dropdown lists with jQuery in Razor web pages, please see this article: WebMatrix - jQuery Cascading Dropdown Lists.
jQuery Templates are an official jQuery plugin. That means that they are maintained as part of the jQuery Project. They are still in Beta at the moment, but will be included as part of the core jQuery library in the next major release, which will be jQuery 1.5. In much the same way as the WebMatrix WebGrid helper is used to generate html (in this case a <table>) on the server, jQuery Templates allow you to generate html using client side script. Where they differ from the WebGrid helper is that you can define the html that they generate. You are not restricted to outputting a <table>. On the other hand, they share a major similarity with the WebGrid helper. As part of the template you define, you can add binding expressions which act as placeholders for data. It's probably a good idea at this point to have a look at a typical template.
Since I intend to illustrate cascading dropdown lists later, I'm going to re-use the data source I created for my original Cascading Dropdown Lists article from a couple of years ago. The data relates to cars, and each car has a number of properties:
- Make
- Model
- Year
- Colour
- Number of Doors
- Mileage
- Price
A typical template for displaying cars might look like this:
<script id="carTmpl" type="text/x-jQuery-tmpl"> <div class="carListing"> <h4>${Make} ${Model}</h4> <p>Year: ${Year}</p> <p>Doors: ${Doors}</p> <p>Colour: ${Colour}</p> <p>Mileage: ${Mileage}</p> <p>Price: ${Price}</p> </div> </script>
The template appears in a <script> block, which has two attributes. One is an id, and the other is a type. You don't normally see an id attribute being applied to a <script> tag, but in this case, it is used to identify the specific template later in JavaScript code. The second attribute, type, is given a value of "text/x-jQuery-tmpl". This value is actually a MIME type which the browser won't understand. Consequently, it will not try to execute the contents of the <script> tag and most likely throw JavaScript errors in doing so. You could provide other values for type, such as "text/html", but "text/x-jQuery-tmpl" gives a clearer indication as to the purpose of the <script> block.
The content of the <script> block is a snippet of html. When you pass data to a template, the template is used as a basis for the html to be generated. The templating engine will attempt to find items in the data that match the binding expressions, which take the form of ${...}. In the example above, you can see a binding expression for each of the properties of the Car objects I am going to use. The templating engine will repeat the creation of html, using the template, for each of the individual items in the data being passed. Before I show how to use this template to display a list of cars, I will explain a little about the data, and how it is generated. Take a look at the following site structure:
There are two files in the App_Code folder. They are both C# class files. One, Car.cs defines a Car object and its properties. The other, CarService.cs, builds a list of Car objects, and provides methods that external code can call to obtain some or all of the data. Some of the methods are illustrated below:
public static List<Car> GetAllCars() { return Cars.ToList(); } public static List<Car> GetCarMakes() { return (Cars.OrderBy(c => c.Make) .Select(c => new Car { Make = c.Make })) .GroupBy(c=> c.Make) .Select(c => c.First()).ToList(); } public static List<Car> GetModelsByMake(string make) { return (Cars.Where(c => c.Make == make) .OrderBy(c => c.Model) .Select(c => new Car{ Model = c.Model })) .GroupBy(c => c.Model) .Select(c => c.First()).ToList(); }
The first method returns a List<Car> containing all the cars. The second returns a list of all the Makes (Audi, BMW, Citroen etc) and the third method returns a list of all the Models for each Make, so for BMW, for example, the data might be "1 Series", "3 Series", "5 Series" etc. You can view the accompanying download for the other methods. Ideally, the data needs to be exposed as JSON for jQuery Templates to work nicely. The Services folder contains five files, each of which contains a call to a single method in the the CarService class, and converts the List<Car> that gets returned from the CarService to JSON using the Web Pages JSON helper. As an example, here's the content of GetAllCars.cshtml:
@{ var data = CarService.GetAllCars(); Json.Write(data, Response.Output); }
The CarList.cshtml file contains a basic example of how to use jQuery Templates. Here's the full code for that file:
@{ $(function(){ $.getJSON( "Services/GetAllCars/", function(data) { $("#carTmpl").tmpl(data).appendTo("#carList"); }); }); function formatPrice(price) { return "£" + price.toFixed(0); } </script> <script id="carTmpl" type="text/x-jQuery-tmpl"> <div class="carListing"> <h4>${Make} ${Model}</h4> <p>Year: ${Year}</p> <p>Doors: ${Doors}</p> <p>Colour: ${Doors}</p> <p>Mileage: ${Mileage}</p> <p>Price: ${formatPrice(Price)}</p> </div> </script> <h2>Basic Template</h2> <div id="carList"></div>
The file defines its Layout page, which includes references to two JavaScript files hosted on Microsoft's AJAX Content Delivery Network (CDN):
<script type="text/javascript" src=""></script> <script type="text/javascript" src=""></script>
Following that, there are two <script> blocks. The second of these contains the template that will be applied to the data, and is mostly the same as the previous template example you saw. The first block is actual JavaScript to be executed. When the browser is ready, an AJAX call is made to the GetAllCars.cshtml file in the Services folder (taking advantage of Web Pages built-in support for Routing) which returns the data as JSON. This can clearly be seen in the following illustration which shows the response captured using the FireBug addon in Firefox:
This is passed to the data parameter of the next function, which takes care of binding the data to the template and rendering it:
$("#carTmpl").tmpl(data).appendTo("#carList");
Or in other words - "take the element with the id of carTmpl (our script block) and use it as a template (the .tmpl command), binding the contents of the data variable (the JSON string) and append the resulting html to the element with the id of carList". The result looks like this:
There is one other thing to note, and that is that the binding expression within a template can contain a call to a function. You can see this in the way that the price property of each Car object has been formatted using a function to prefix the data with a £ sign.
Cascading Select Lists From jQuery Templates
Select lists are just a bunch of html with a bit of data, aren't they? So it should be feasible to create fully functioning Cascading Select Lists (DropDowns) with jQuery Templates, right? And indeed it is quite straightforward as you will see. The following example presents three select lists in total. The first one lists all Makes of car within the data. Once a Make has been selected, all the Models associated with that Make populate the second select list, and once a Model has been selected, all available colours are presented in the third select list. Finally, when the user chooses their preferred colour from the available options, all cars meeting the selected Make, Model and Colour criteria are displayed. The end result will look like this:
To start with, here's the entire HTML for the CascadingDropDowns.cshtml file:
<h2>Cascading DropDowns</h2> <p>Please choose a Make:</p> <select id="makeList"><option value="0"> -- Select Make -- </option></select> <p>Please choose a Model:</p> <select id="modelList"><option value="0"> -- Select Model -- </option></select> <p>Please choose a Colour:</p> <select id="colourList"><option value="0"> -- Select Colour -- </option></select> <div id="results"></div>
Yep - that's it. A heading, three <select> elements and an empty, but named <div> element. Next, here are the definitions for the Templates:
<script id="makeTmpl" type="text/x-jQuery-tmpl"> <option value="${Make}">${Make}</option> </script> <script id="modelTmpl" type="text/x-jQuery-tmpl"> <option value="${Model}">${Model}</option> </script> <script id="colourTmpl" type="text/x-jQuery-tmpl"> <option value="${Colour}">${Colour}</option> </script> <script id="detailsTmpl" type="text/x-jQuery-tmpl"> <div class="carListing"> <h4>${Make} ${Model} - ${Year}</h4> <p>Doors: ${Doors}</p> <p>Colour: ${Colour}</p> <p>Mileage: ${Mileage}</p> <p>Price: ${formatPrice(Price)}</p> </div> </script>
The first three template definitions cater for the select lists: one for the Make, one for the Model and the final one for the Colour selector. The final template is the one that was used in the previous example to display the car details. the JavaScript block is where the action happens:
<script type="text/javascript"> $(function(){ $('#modelList').attr('disabled', true); $('#colourList').attr('disabled', true); $('#makeList').bind('change', function(){getModels()}); $.getJSON( "Services/GetCarMakes/", function(data){ $('#makeTmpl').tmpl(data).appendTo('#makeList'); }); }); function getModels(){ if($('#makeList').val() != "0"){ $.getJSON( "Services/GetModelsByMake/"+ $('#makeList').val(), function(data) { $('#modelList').attr('disabled', false); $('#modelList').html('<option value="0"> -- Select Model -- </option>'); $('#modelList').unbind('change').bind('change', function(){getColours()}); $('#modelTmpl').tmpl(data).appendTo('#modelList'); }); }else{ $('#modelList').attr('disabled', true); } } function getColours(){ if($('#modelList').val() != "0"){ $.getJSON( "Services/GetColoursByModel/"+ $('#modelList').val(), function(data) { $('#colourList').attr('disabled', false); $('#colourList').html('<option value="0"> -- Select Colour -- </option>'); $('#colourList').unbind('change').bind('change', function(){getDetails()}); $('#colourTmpl').tmpl(data).appendTo('#colourList'); }); }else{ $('#colourList').attr('disabled', true); } } function getDetails(){ if($('#colourList').val() != "0"){ var make = $('#makeList').val(); var model = $('#modelList').val(); var colour = $('#colourList').val(); $.getJSON( "Services/GetCarListByColour/" + make + "/" + model + "/" + colour, function(data) { $('#results').empty(); $('#detailsTmpl').tmpl(data).appendTo('#results'); }); }else{ $('#colourList').attr('disabled', true); } } function formatPrice(price) { return "£" + price.toFixed(2); } </script>
When the page loads, the second and third select lists are disabled so that they can't be used. But the first select list is populated with data retrieved by a jQuery getJSON call to the GetCarMakes method in CarService.cs. The getJSON call is actually routed to the GetCarMakes file which calls the CarService and converts the data to JSON in exactly the same way as the earlier GetAllCars method:
@{ var data = CarService.GetCarMakes(); Json.Write(data, Response.Output); }
At the same time, an event handler is bound to the onchange event of the select list, which calls another JavaScript method - getModels(). This function is executed when a Make is selected, and enables the Models select list prior to fetching the data for it. Then the data is bound to the template and the resulting <option> elements are added to the select list. Finally, another event handler handler is bound to the onchange event that fetches the colour data based on the selected Model, which is passed as UrlData:
@{ var data = CarService.GetColoursByModel(UrlData[0]); Json.Write(data, Response.Output); }
And once a colour is selected, all three values: Make, Model and Colour are passed in the URL to the GetCarsByColour method:
The code for the GetCarsByColour method:
@{ var data = CarService.GetCarListByColour(UrlData[0], UrlData[1], UrlData[2]); Json.Write(data, Response.Output); }
Finally, the resulting data is bound to the final template, providing the listing of selected cars as seen in the previous image.
I included the word "Razor" in the title of this post, and in truth, the only line of Razor code in the CascadingDropDowns.cshtml file is that which references the Layout page. The file could just as easily have been a plain .html file, and it would have still worked in just the same way - given access to a source of JSON data. So where would you get such a source - apart from creating your own service that uses the JSONHelper? Well, one source could well be an OData feed, such as that provided by Netflix.com.
jQuery Templates provide an extraordinarily versatile client-side html generation mechanism, especially when combined with data binding. Although the cascading select lists paradigm has a number of tried and tested solutions, jQuery Templates provides a neat new twist.
You can download the sample Web Pages site from here. | https://www.mikesdotnetting.com/article/166/razor-cascading-select-lists-and-jquery-templates-a-new-twist | CC-MAIN-2021-43 | refinedweb | 2,075 | 55.34 |
A class modifier that specifies that the class must be derived from to be instantiated.
A binary operator type that casts the left operand to the type specified by the right operand and that returns null rather than throwing an exception if the cast fails.
A variable with the same meaning as this, except that it accesses a base-class implementation of a member.
A logical datatype that can be true or false.
A jump statement that exits a loop or switch statement block.
A one-byte, unsigned integral data type.
A selection statement that defines a particular choice in a switch statement.
The part of a try statement that catches exceptions of a specific type defined in the catch clause.
A two-byte, Unicode character data type.
A statement or operator that enforces arithmetic bounds checking on an expression or statement block.
An extendable reference type that combines data and functionality into one unit.
A modifier for a local variable or field declaration that indicates that the value is a constant. A const is evaluated at compile time and can be only a predefined type.
A jump statement that skips the remaining statements in a statement block and continues to the next iteration in a loop.
A 16-byte precise decimal datatype.
A marker in a switch statement specifying the action to take when no case statements match the switch expression.
A type for defining a method signature so delegate instances can hold and invoke a method or list of methods that match its signature.
A loop statement to iterate a statement block until an expression at the end of the loop evaluates to false.
An 8-byte, floating-point data type.
A conditional statement that defines the action to take when a preceding if expression evaluates to false.
A value type that defines a group of named numeric constants.
A member modifier for a delegate field or property that indicates that only the += and -= methods of the delegate can be accessed.
An operator that defines an explicit conversion.
A method modifier that indicates that the method is implemented with unmanaged code.
A Boolean literal.
The part of a try statement to execute whenever control leaves the scope of the try block.
A statement to pin down a reference type so the garbage collector won't move it during pointer arithmetic operations.
A four-byte floating-point data type.
A loop statement that combines an initialization statement, continuation condition, and iterative statement into one statement.
A loop statement that iterates over collections that implement IEnumerable.
The name of the accessor that returns the value of a property.
A jump statement that jumps to a label within the same method and same scope as the jump point.
A conditional statement that executes its statement block if its expression evaluates to true.
An operator that defines an implicit conversion.
The operator between a type and an IEnumerable in a foreach statement.
A four-byte, signed integral data type.
A contract that specifies the members that a class or struct may implement to receive generic services for that type.
An access modifier that indicates that a type or type member is accessible only to other types in the same assembly.
A relational operator that evaluates to true if the left operand's type matches, is derived from, or implements the type specified by the right operand.
A statement that acquires a lock on a reference-type object to help multiple threads cooperate.
An eight-byte, signed integral data type.
A keyword that maps a set of types to a common name.
An operator that calls a constructor on a type, allocating a new object on the heap if the type is a reference type, or initializing the object if the type is a value type. The keyword is overloaded to hide an inherited member.
A reference-type literal that indicates that no object is referenced.
The type all other types derive from.
A method modifier that overloads operators.
A parameter modifier that specifies that the parameter is passed by reference and must be assigned by the method being called.
A method modifier that indicates that a method of a class overrides a virtual method of a class or interface.
A parameter modifier that specifies that the last parameter of a method may accept multiple parameters of the same type.
An access modifier that indicates that only the containing type can access the member.
An access modifier that indicates that only the containing type or derived types can access the member.
An access modifier that indicates that a type or type member is accessible to all other types.
A field modifier specifying that a field can be assigned only once, either in its declaration or in its containing type's constructor.
A parameter modifier that specifies that the parameter is passed by reference and is assigned before being passed to the method.
A jump statement that exits a method, specifying a return value when the method is nonvoid.
A one-byte, signed integral data type.
A class modifier that indicates a class cannot be derived from.
The name of the accessor that sets the value of a property.
A two-byte, signed integral data type.
An operator that returns the size in bytes of a struct.
An operator that returns a pointer to a specified number of value types allocated on the stack.
A type member modifier that indicates that the member applies to the type rather than to an instance of the type.
A predefined reference type that represents an immutable sequence of Unicode characters.
A value type that combines data and functionality in one unit.
A selection statement that allows a selection of choices to be made based on the value of a predefined type.
A variable that references the current instance of a class or struct.
A jump statement that throws an exception when an abnormal condition has occurred.
A boolean literal.
A statement that provides a way to handle an exception or a premature exit in a statement block.
An operator that returns the type of an object as a System.Type object.
A four-byte, unsigned integral data type.
An eight-byte, unsigned integral data type.
A statement or operator that prevents arithmetic bounds checking on an expression.
A method modifier or statement that permits pointer arithmetic to be performed within a particular block.
A two-byte, unsigned integral data type.
A directive that specifies that types in a particular namespace can be referred to without requiring their fully qualified type names. The keyword is overloaded as a statement that allows an object that implements IDisposable to be disposed of at the end of the statement's scope.
The name of the implicit variable set by the set accessor of a property.
A class method modifier that indicates that a method can be overridden by a derived class.
A keyword used in place of a type for methods that don't have a return value.
A field modifier indicating that a field's value may be modified in a multithreaded scenario; neither the compiler nor runtime should perform optimizations with that field.
A loop statement to iterate a statement block while an expression at the start of each iteration evaluates to false. | http://etutorials.org/Programming/C+in+a+nutshell+tutorial/Part+V+Appendixes/Appendix+D.+C+Keywords/ | CC-MAIN-2016-40 | refinedweb | 1,214 | 56.96 |
While this is not something I personally would want to do, we (for whatever reason...) are to use MSTest at work (I think it is due to the whole "Its Microsoft, so it's supported" argument).
Now as no one else on the team does any kind of unit testing (serious), the only test projects we have are written by me, on the quiet before being told if I wanted to unit test then use MSTest. So onto the point of this article.
When you create a project for tests with nunit, you just create a
Class Library, add a reference to nunit (and Rhino.Mocks of course), build it and run with your preferred method (I like TDD.Net, but that involves paying for at work...so no go there).
When you want to do tests with MSTest, you just create a Test Project and start writing tests. On closer inspection, it's just a
Class Library with a reference to
Microsoft.VisualStudio.QualityTools.UnitTestFramework. So converting one to the other should be easy, right?
Well not quite. While there is nothing in the GUI to suggest so, you need to modify the csproj/vbproj file to get it to work. This post on MSDN, had all the details, but in the interest of having things in more than one place (not very DRY I will admit, but there), here are the steps:
- Remove Reference to Nunit.Core & Nunit.Framework
- Add Reference to Microsoft.VisualStudio.QualityTools.UnitTestFramework
- Find and Replace:
using NUnit.Framework;with
using Microsoft.VisualStudio.TestTools.UnitTesting;(I actually use a project level import, so I skip this)
- [TestFixture] -> [TestClass]
- [Test] -> [TestMethod]
- [SetUp] -> [TestInitialize]
- [TearDown] -> [TestCleanup]
- [TestFixtureSetUp] -> [ClassInitialize]
- [TestFixtureTearDown] -> [ClassCleanup]
- Change your Asserts:
- Assert.Greater(x, y) -> Assert.IsTrue(x > y)
- Assert.AreEqual(x, Is.EqualTo(y).IgnoreCase) -> Assert.AreEqual(x, y, True)
- The 'hidden' part. In your project file, locate
<PropertyGroup>(not the one specifying debug|release settings), and add the following to it:
512
- *.csproj files add:
>
- *.vbproj files add:
>
This was all I had to do to get our (my) tests running again under MSTest. Except they didn't run, with the lovely error of:
The location of the file or directory 'D:\Projects\Dev\SDK\Rhino.Mocks.dll' is not trusted.
That's odd, the file is on my hard disk, its not a network share, so what's the problem? Right click on Rhino.Mocks.dll and:
Click the Unblock button, hit Apply, re-run the tests. All Working now :)
There are a few other points mentioned on the MSDN post too which you may run into:
If you have relied on NUnit TestFixtureSetup and TestFixtureTearDown methods to do non-static things, will have to move functions in the former to a constructor and the latter to a destructor. In MSTest, both of these methods must be declared as static.
If you are relying on AppDomain.CurrentDomain.BaseDirectory to get the root directory, your test will break. The fix is explained at.
Basically, you need to set your BaseDirectory in your MSTest TestClass constructor like this:
string currDir = Environment.CurrentDirectory.Substring(0, Environment.CurrentDirectory.IndexOf("TestResults")); AppDomain.CurrentDomain.SetData("APPBASE", currDir);
MSTest launches each test method in a separate STA thread instead of the MTA thread you may be expecting. This probably won't give you any problems.
Hope that helps everyone who has to do this kind of conversion. | http://stormbase.net/2010/01/12/converting-from-nunit-to-mstest/ | CC-MAIN-2017-17 | refinedweb | 568 | 57.87 |
visa支付—Springboot2019-11-15 14:49:36) ...-- visa支付 --> <depe...
)
流利说 Level 3 全文2019-05-22 10:51:17Bus number 38 was supposed to come at 8:40, but it was 5 minutes late. It didn’t come until 8:45. Bus number 60 was supposed to come at 8:30. But yesterday it didn’t come until 8:40. ...
Lesson 3 Activities &Food
Lesson 4 Spatial Relations
Lesson 5 Meeting at the Airport
Lesson 2 Kim’s Movie Star Dream
Lesson 3 Action & Comparisons
Lesson 4 Seasons & Weather
Lesson 5 Missing the Flight
Lesson 6 A Going Away Party
Lesson 1 Buying a New Car 1-2
Lesson 3 Spatial Relations & Needs
Lesson 4 Places of Business
Lesson 5 Ordering Food from Home
Lesson 6 Are Selfies Good or Bad?
Lesson 1 Christina’s Future Plans 1-2
Lesson 6 Discussing Eating out
Lesson 5 Ready for the Meeting
Lesson 6 Discussing Test Results
Lesson 1 Paul’s Trip Plan 1-2
Lesson 1 Paul’s Overseas Trip 1-2
Lesson 3 Emergency Vehicles
Lesson 4 Weather & Activities
Lesson 5 Checking up on Ada
Lesson 1 Overview of Earth
Lesson 3 Things We Enjoy Doing
Lesson 5 A Driverless Car
Lesson 6 Calling Customer Service
Lesson 1 Life & Conditions 1-2
Lesson 5 Dating Anniversary
Lesson 6 Life and the Universe
Lesson 1 Harry’s Business Trip 1-2
Lesson 3 Sources of Energy
Lesson 5 Good News & Bad News
Lesson 1 Leonardo da Vinci 1-2
Lesson 3 Sources of Pollution
Lesson 4 Historical Figures
Lesson 6 Setting the Bill
Level 3
Unit1
1/4
Listening
Kathy usually gets up at 6:30, but this morning, she didn’t hear her alarm.
As a result, she overslept.
She didn’t get up until 7:00, 30 minutes later than usual.
As a result, she didn’t have time to cook breakfast for her children.
-Why did she oversleep? –She didn’t hear her alarm.
-Why didn’t she cook breakfast? –She didn’t have time.
Today Kathy and her kids left home early.
They usually leave home at 7:30, but today they left at 7:15.
They left early because they had to buy breakfast on their way to school.
-Why did they leave home early? –They had to buy breakfast on their way to school.
-What did they have to buy on their way to school? –their breakfast.
It usually takes 45 minutes to drive her kids to school, but today it took longer.
It took them longer because they stopped for breakfast along the way.
It took 15 minutes for them to have breakfast.
They ate at a little coffee shop along the side of the road.
-How long does it usually take to drive her kids to school? –It usually takes 45 minutes.
-How long did it take them to have breakfast? –It took 15 minutes.
After eating breakfast, they got back into their car.
On most days the traffic isn’t too bad in the morning.
But this morning, it was much worse than usual.
The cars were moving very slowly.
As a result it took them longer than usual to get to school.
-What did they do after eating breakfast? –They got back into their car.
One of her children got to school on time, but the other two were late.
They were late because their schools are farther away.
They were both about 10 minutes late to school.
-How late were two of her children? –They were about 10 minutes late.
When Kathy finally got home she cleaned her house as usual.
She vacuumed the living room and cleaned the bathroom.
Then she talked with her friend on the phone as usual.
When she finished talking with her friend she got into her car.
She put the key into the ignition, and tried to start the engine.
But the car’s engine didn’t start.
Her car battery was dead, so she had to call for help.
-What happened when she tried to start her car? –The car’s engine didn’t start.
-Why did she have to call for help? –to get a new battery.
After getting a new battery for her car, the engine started.
Then Kathy drove to the mall to meet her friend.
She arrived to the mall an hour late but her friend was waiting for her.
They had lunch together and then they went shopping.
They both bought new shoes and some things for their kids.
Kathy bought a new tie for her husband.
-What did Kathy buy for her husband? –a new tie.
-Who was waiting for her at the mall? –Her friend was waiting for her.
It’s now 3:00 and everything is going as usual.
Kathy doesn’t want anything else to go wrong.
She wants the rest of the day to go as usual.
She doesn’t want any more surprises.
And tomorrow she won’t oversleep.
She never wants to oversleep again.
-What doesn’t Kathy want? –more surprises.
Here is a bus schedule at a bus stop.
On most days the buses come on schedule but sometimes they don’t.
Yesterday for example, several buses were late.
This is because the traffic yesterday was much heavier than usual.
-How was the traffic yesterday? –It was much heavier than usual.
-Why were several buses late? –The traffic was heavier than usual.
Bus number 38 was supposed to come at 8:40, but it was 5 minutes late.
It didn’t come until 8:45.
Bus number 60 was supposed to come at 8:30.
But yesterday it didn’t come until 8:40.
It was 10 minutes late.
Not one bus come early.
-How many buses came early? –Not one bus came early.
As a result of the delays one man got on the wrong bus.
He wanted to go to the airport so he wanted to get on bus number 38.
He expected it to come at 8:40.
Instead he got on bus number 60, which came at 8:40.
He didn’t notice that it was the wrong bus.
It didn’t go to the airport.
As a result he missed his flight.
-What time was bus number 38 supposed to come? -8:40.
-Why did the man miss his flight? –He got on the wrong bus.
Vocabulary
Lesson 3 Activities &Food
Weddings are where two people get married.
This man and woman are getting married.
The building in the middle is an office building.
Many people come to work here during the week.
These people are at a dance party.
The woman in the green dress is dancing with her boyfriend.
These two people are meeting for the first time.
They are shaking hands.
This young boy is brushing his teeth.
He brushes his teeth several times a day.
-Who are shaking hands? –They are shaking hands.
Candies and cakes are sweet because they are made with lots of sugar.
Eating too many sweets is not good for your teeth.
Lemons and great food take a little sour so some people don’t like them.
Some sour tasting foods have a lot of vitamin C.
These red peppers are very hot and spicy.
Eating hot or spicy food rises body temperature so don’t eat them before going into bed.
These foods are deep-fried and greasy.
Greasy foods have a lot of calories, so don’t eat them if you want to lose weight.
Healthy foods are usually nature and don’t include dangerous chemical. Fruits and vegetables are examples of healthy foods.
-How do lemons and great food taste? –a little sour.
Lesson 4 Spatial Relations
The triangle is inside the square.
The square is around the triangle.
The triangle is inside the circle.
The circle is around the triangle.
The square is inside the triangle.
The triangle is around the square.
The circle is between two small squares.
There is a square on either side of the circle.
The circle is on the left of the rectangle.
The rectangle is on the right of the circle.
Dialogue
Lesson 5 Meeting at the Airport
W: Hey, where are you? I don’t see you anywhere.
M: I’m on the subway.
W: My flight arrived early and I’m tired.
M: I’m sorry to be late. I’ll be there as fast as I can.
-Where is she? –She is at the airport.
W: Where are you now?
M: There are three more stops. I’ll be there in ten minutes.
W: I’ll meet you at the bus stop in front of terminal 2. Then we can get a taxi.
M: OK. I’ll look for you in front of terminal 2. See you soon.
-What are they going to do after they meet? –Take a taxi.
Lisa: What’s the matter, Tom?
Tom: I don’t feel well.
Lisa: Are you sick?
Tom: No, I don’t think so. I’m just tired.
Lisa: Didn’t you get enough sleep?
Tom: No, I didn’t. I went to bed later than usual last night.
-Why didn’t he get enough sleep? –He went to bed later than usual.
Lisa: What time did you go to bed?
Tom: I didn’t go to bed until 12:00.
Lisa: Why did you stay up so late?
Tom: I was watching some videos on line.
-He didn’t go to bed until when? - He didn’t go to bed until 12:00.
Lisa: What kind of videos?
Tom: Music videos from all over the world.
Lisa: Really?
Tom: Sure, I’ll send you some links if you like.
Lisa: Thanks, I like music videos too. They are really fun.
Tom: Just don’t stay up too late.
Lisa: Don’t worry, I won’t stay up too late. I need my sleep.
-Why won’t she stay up too late? –She needs enough sleep.
He was watching videos.
He didn’t go to bed until 12:00.
2/4
Listening
Our planet, the earth, is the third planet from the sun.
It is a beautiful, rotating sphere.
The side facing the sun is in daylight.
The side facing away from the sun is in darkness.
For example, when it’s daytime in the US, it’s nighttime in China.
In fact, there’s a 12-hour time difference between Boston and Shanghai.
When it’s midnight in Shanghai,it’s noon in Boston.
-Which side of the earth is in daylight? –the side facing the sun.
-What is the shape of our planet? –a sphere.
-What time of the day is noon? –It’s 12:00 pm.
-Which side of the earth is in darkness? –the side facing away from the sun.
The earth rotates from west to east.
To know which direction is east or west, watch the sun.
The sun travels through the sky from east to west.
The sun comes up in the east and goes down in the west.
Again, this is because the earth rotates.
It takes 24 hours for the earth to make a complete rotation.
And that is the length of one day.
-The sun comes up in which direction? –It comes up in the east.
Because of the earth’s rotation, the earth is divided into time zones.
Some countries, such as the US, have several time zones.
When it’s 10 am in New York, it’s 7 am in San Francisco.
Europe and the US are separated by several time zones.
When it’s 5 pm in Paris, it’s 11 am in Boston.
So there is a 6-hour difference between Paris and Boston.
One large country, China, has just one time zone for the whole country.
As a result, at the same time, some parts of the country can be dark and other parts can be light.
-Which large country has only one time zone? –China.
-Why is the earth divided into time zones? –It rotates.
As you travel around the earth, the time changes.
The time of day depends on your location on the planet.
When you travel east or west, you may cross several time zones.
For example, if you travel from Beijing to Los Angeles, you cross 8 time zones.
That means, when it’s noon on Sunday in China, it’s 8 pm on Saturday in Los Angeles.
For travelers, this means it can be very difficult to sleep after a long flight.
The clock may say 8 pm, but for your body, it’s noon.
This is called jet lag.
-What causes jet lag? –crossing several time zones.
-What happens if you travel east or west? –You may cross several time zones.
-What changes as you travel around the earth? –the time.
-What happens if you travel from Beijing to Los Angeles? –You will cross several time zones.
It depends on how far east or west you travel.
Crossing several time zones causes jet lag.
Lesson 2 Kim’s Movie Star Dream
Kim is a popular Korea actress.
She’s 28 years old, slim, and beautiful.
She has a large fan club, and her movies are very popular.
Everywhere she goes, her fans want her autograph.
But Kim wants more.
She wants to be popular all over the world.
-What does Kim do? –She is an actress.
-What does Kim want? –She wants to be more popular.
-What do her fans want? –Her autograph.
Tomorrow is a special day for her.
She’s leaving for Hollywood.
She’s going to Hollywood to meet with some top movie executives.
The meeting is scheduled the day after tomorrow.
If the meeting goes well, she’ll be in a Hollywood movie.
This is her chance to become a star.
-When is she leaving for Holly Wood? –tomorrow.
-What will happen if the meeting goes well? –She’ll be in a Hollywood movie.
-When is she going to meet with executives? –the day after tomorrow.
She met the movie’s director last year.
He came to Korea and saw her latest movie.
After that he decided to use her in his new movie.
Fortunately, Kim’s English is excellent, so she can play the role.
-Who did she meet in Korea last year? –the movie’s director.
-What did the movie director decide to do? -He decided to use her in his new movie.
The director wants her to play a major role in the movie.
The movie story will take place in the future.
At that time the world will be a very different place.
Unfortunately, much of world will be polluted.
Robots will do much of the work, and only the very rich can have a good life.
-In the movie, who can have a good life? –the very rich.
-What are robots? –machines.
The ending of the movie is still a secret.
Even Kim doesn’t know how it will end.
But she hopes it will have a happy ending.
She wants people to have hope for a better future.
-What doesn’t Kim know? –the ending of the movie.
Vocabulary
Lesson 3 Action & Comparisons
These people are having a meeting.
The woman is giving a presentation.
This person is having a scary dream.
In his dream, something is chasing him, so he is running as fast as he can.
This old man is a tourist.
He is looking out the window of his tour bus.
This young couple is in an art museum.
They are looking at a famous painting.
The sun is setting behind the mountains.
The sky is turning red.
Some buses, like this one, take tourists to places like the Great Wall.
She’s giving a presentation at a meeting.
The longest line is the one on the top.
The top line is the longest of the three lines.
The shortest line is the one in the middle.
The line in the middle is shorter than the other two.
The bottom line is the shortest.
The shortest of these three lines is the one on the bottom.
The shirt on the left is more expensive than the shirt on the right.
The shirt on the right is less expensive than the shirt on the left.
The shirt on the left isn’t as expensive as the one on the right.
The shirt on the left costs less than the one on the right.
The shirt on the left is more expensive than the shirt on the right.
Lesson 4 Seasons & Weather
Winter is the coldest season because the sun is at its lowest point in the sky.
Winter sports include skiing and ice skating.
Summer is the hottest season because the sun is at its highest point in the sky.
Many people like to go swimming in the summer because of the hot weather.
Spring is the season when the weather gets warmer each day.
For many animals new life begins in the spring.
Autumn is the season when the weather begins to cool and the days begin to shorten.
Autumn is when trees turn many colors and leaves fall to the ground.
Rainy season is the season when some countries get most of the rainfall.
Rainy season usually lasts for one or two months.
Dialogue
Lesson 5 Missing the Flight
M: Hi, I’m sorry to be late.
W: What happened? You were supposed to be here an hour ago.
M: Yes, I know, but I missed my flight.
-How late is he? –H’s an hour late.
W: You missed your flight? How did that happen?
M: I got on the wrong bus this morning, so I was late to the airport.
By the time I arrived, the gate was closed.
W: What did you do then?
M: I had to rebook my flight and get on the waiting list.
-Why was he late to the airport? –He got on the wrong bus.
-What did he do when he got to the airport? –He rebooked his flight.
He had to get on a waiting list because other people were also trying to get on the flight.
W: Oh, that’s too bad. At least you got here.
M: Yes, it wasn’t easy getting on the next flight. I had to run to the gate.
W: This kind of thing happens a lot lately. Last week I missed a flight, too.
-What wasn’t easy? –It wasn’t easy getting on the next flight.
M: What happened?
W: There was a traffic accident near the airport.
M: You were driving?
W: No, I wasn’t. I was in a taxi. But it took a long time to get to the airport.
The traffic was stopped for nearly 15 minutes.
-Why did it take a long time to get to the airport? –The traffic was stopped because of an accident.
W: By the time I got there, it was too late to get on the flight.
The next flight wasn’t for another 3 hours, so it was a long wait.
From now on, I’ll try to get to the airport much earlier.
M: Me too.
-How long did she have to wait for the next flight? –She had to wait three hours. She had to wait three hours for the next flight.
Lesson 6 A Going Away Party
M: What’s the matter? Why do you look so sad?
W: Ada has a new job. She’s going to Beijing.
M: Really? When is she leaving?
W: She’s leaving at the end of next week.
M: That soon?
W: Yes, she just told me.
M: That’s too bad. I really enjoy working with her.
W: Me too, I’m going to miss her.
-When is Ada leaving? –She is leaving at the end of next week.
W: Let’s have a going-away party for her.
M: Good idea. How about this weekend?
W: Friday evening would be better. We can have it after work.
M: Yes, Friday is better.
-When are they going to have the party? –They’re going to have it on Friday evening.
-Why is Friday evening better than the weekend? –They can have the party after work.
W: Let’s go to her favorite restaurant, okay?
M: Which one? The Italian one, or the German one?
W: The Italian one has better food, so let’s go there. Their pizzas are awesome.
-How good are the pizzas at the Italian restaurant? –They are awesome.
-Why did they decide on the Italian restaurant? –They think it has better food.
M: OK, I’ll make the reservations.
W: Let me check with Ada first. We don’t want her to miss her party.
M: Yeah, that’s for sure. And could you please invite everyone in the office?
W: Sure, no problem. Nobody will want to miss it.
-What are they going to check with Ada? –They need to confirm that she can come to the party.
3/4
Listening
Lesson 1 Buying a New Car 1-2
Paul is a very successful businessman.
He owns several restaurants.
All of them are doing well.
In fact, they are very profitable.
To be profitable means that their income is more than their expenses.
As a result, he is making a lot of money.
-What does Paul do? –He is a businessman.
-Why is he making a lot of money? –His restaurants are profitable.
He is making money because his restaurants are profitable.
Paul wants to buy a new car.
He’s trying to decide which car to buy.
He has plenty of money.
As a result, he isn’t worried about the cost.
He can afford an expensive car.
-Why isn’t he worry about the cost? –He has plenty of money.
-As a result is the same as saying… -so
On the other hand, he doesn’t want to waste money.
He wants a car he can rely on.
It has to be safe and reliable, especially in cold winter weather.
If a car breaks down in bad weather, it can be very dangerous.
-What kinds of car does he want? –a safe, reliable car.
Paul wants to help reduce pollution and smog.
He would like to buy a clean car, something good for the environment.
He is thinking about buying a Tesla.
The Tesla is an all-electric car.
It used batteries instead of gasoline.
There is no exhaust so it doesn’t pollute the air.
-What kind of car is Tesla? –It is a clean, electric car.
-Why doesn’t the Tesla pollute the air? –It doesn’t exhaust.
However, the car can’t go very far without recharging the battery.
To charge the battery you can plug it in to an electrical outlet.
Recharging the battery takes time.
-What takes time? –Recharging the battery.
One of Paul’s friends has one and he is quite happy with it.
He says it’s reliable and well-engineered.
There’re also several charging station near Paul’s office.
So he isn’t worried about that.
The cost for charging the battery is low.
It’s less expensive than buying gasoline.
His wife, Kathy, also likes the idea of buying an electric car.
She likes the idea of driving a clean car.
So it makes sense.
-What’s less expensive than buying gasoline? –charging the battery.
-Why isn’t Paul worried about finding charging stations? –There’re several charging stations near Paul’s office.
In the future there may be driverless cars.
This may be very safe, but Paul doesn’t like them.
He enjoys driving.
He likes to be in control of his car.
-What does Paul enjoy doing? –He enjoys driving.
Vocabulary
Lesson 3 Spatial Relations & Needs
The man in the middle is the heaviest.
The man in the middle is heavier than the other two.
The woman on the left is smarter than the man on the right.
The man isn’t as smart as the woman is.
The woman is standing under a bridge.
The bridge is above the woman.
There is a bridge over the river.
The river is flowing beneath the bridge. The water is flowing over a waterfall.
The waterfall is very high and beautiful.
People need passports to travel internationally.
Without a passport, you cannot leave your country or enter another country.
You need a driver’s license to drive a car.
It is against the law to drive without a driver’s license.
Many people use credit cards to buy things on credit.
When you have a credit card, you don’t need to carry cash.
Smart phones are very useful and can do many things.
You can use them to make phone calls, play games, or go shopping on the internet.
We need to buy tickets in order to take a train, or watch a sport event.
You can often buy tickets on line and sometimes you can get a discount.
Lesson 4 Places of Business
Banks are where people can deposit or withdraw money.
You can also use online bank to pay bills, such as your credit card bill.
Hotels are where travelers can stay overnight or for several days.
If you plan to stay at a hotel you should make a reservation.
Restaurants are where people go to eat with friends and family.
There are many different kinds of restaurants, such as Indian, Italian, or Chinese restaurants.
Repair shops are where people go to fix things which are broken or not working right.
This repair shop fixes cars and can check to see if it’s safe to drive.
Coffee shops are favorite place to meet new people or take a break from the office. They are usually less expensive than restaurants.
Dialogue
Lesson 5 Ordering Food from Home
M: I’m tired of going out to eat. Let’s eat at home tonight.
W: OK, are you going to cook?
M: No, it’s too late, you know I’m not a good cook. Let’s order something.
-What are they going to do? –They are going to order food.
-Why does he want to eat at home? –He’s tired of going out to eat.
W: What do you have in mind?
M: I was thinking about a nice big pizza.
W: Again? I had pizza last night. So, please, no pizza.
-What was he thinking about ordering? –He was thinking about ordering a pizza.
-Why doesn’t she want pizza? –She’s tired of eating pizza.
M: OK, no pizza. Let’s order Chinese food, okay?
W: Sweet and sour? You always like sweet and sour. I feel like eating something hot and spicy.
M: OK, you order something hot and spicy, and I order sweet and sour. I don’t want anything spicy.
My stomach doesn’t feel good. It’s a bit upset.
-What does she feel like eating? –something hot and spicy.
-Why doesn’t he want something hot and spicy? –His stomach doesn’t feel good.
W: OK, if you want sweet and sour then I’ll have that too. And I’ll make a salad with lots of tomatoes.
How long will it take for the food to get here.
M: I don’t know. I’ll call and find out.
W: Thanks. Hopefully it won’t take longer than an hour. I’m getting hungry.
-What do they finally decide to order? –They decide to order sweet and sour.
-How long will it take for the food to be delivered? –They don’t know.
Lesson 6 Are Selfies Good or Bad?
M: Hey, what did you do last night?
W: I took a long walk from my hotel.
M: You didn’t get lost?
W: No, I didn’t.
-What did she do last night? –She took a long walk.
-What is she staying? –She is staying at a hotel.
M: Where did you go, anywhere interesting?
W: I walked to river. There were thousands of people there.
M: You went to the river? How long did it take you to walk there.
W: It took around 20 minutes.
M: Did you see anything interesting?
W: I was really surprised by how many people were there.
-How did she get to the river? –She walked to the river.
-What did she see at the river? –She saw thousands of people there.
W: Many of them were taking pictures and selfies, Lots of selfies.
M: Do you take selfies?
W: Sure, don’t you?
M: Sometimes, but my girlfriend takes a lot of selfies. Then she shares them with her friends on line.
I don’t understand why people like to take so many pictures of themselves.
W: That’s because you are old-fashioned.
-What does his girlfriend put on line? –She puts her selfies on line.
-What does it mean to take a selfies? –It means to take a picture of yourself with your smart phone.
M: Hmm, I guess you are right. There are too many social media for me.
When I go to a restaurant, I see many people looking at their smart phones.
They don’t even look at the people they are with.
W: Times are changing, my friend, whether you like it or not.
-What are the people doing in the restaurant? –They are looking at their smart phones.
4/4
Listening
Lesson 1 Christina’s Future Plans 1-2
Christina sells women’s clothing in a department store.
She usually works six days a week, but this week she’s going to take three days off.
She’s taking time off so that she can visit her parents.
Her parents live in the mountains, about three hours away by train.
They are looking forward to seeing her.
They haven’t seen her for almost a year.
Christina is their only child.
-What does Christina sell? –Women’s clothing.
-When was the last time Christina saw her parents? –It was almost a year ago.
-Why is she taking time off? –She is taking time off to visit her parents.
Christina isn’t going on the trip by herself.
Her boyfriend is going with her.
She is going to introduce him to her parents.
She and her boyfriend want to get married.
If everything goes well, they plan to get married in 6 months.
-What is the purpose of the trip? –To introduce her boyfriend to her parents.
-When do they plan to get married? –In 6 months.
After they get married, Christina plans to quit her job.
She wants to spend more time designing clothes.
She wants to set up her own business.
This will take time.
Her boyfriend thinks it’s a good idea.
He is also thinking about starting his own business.
-What does Christina plan to do after she gets married? –She plans to quit her job.
-What does her boyfriend think it’s a good idea? –Start her own business.
They don’t plan to have children right away.
In fact, they may decide not to have children.
They don’t know yet.
It’s going to be a big decision.
-What’s going to be a big decision? –To have children or not.
-What may they decide not to do? –They may decide not to have children.
Christina’s parents want her to marry and have children.
They are looking forward to have grandchildren.
They don’t want her to start her own business.
They think it’s more important to have children.
In fact, they would like her to live closer to them.
They want to be close to their grandchildren.
-What do Christina’s parents want? –They want her to marry and have children.
-Where would Christina’s parents like her to live? –They would like her to live nearby.
So Christina doesn’t plan to tell her parents everything.
For now, she just wants them to meet her boyfriend.
She wants them to be happy that she is going to get married.
She wants them to like him and see her happiness.
She wants her parents to accept her way of life.
Life isn’t the same now as it used to be.
Times are changing.
-What does Christina want her parents to do for now? –She just wants them to meet her boyfriend.
Vocabulary
Mechanics, like this one, fix cars.
He is working in a repair shop.
A delivery person delivers things, such as pizzas.
This person works for a restaurant.
A pharmacist sells medicines.
Pharmacists, like this woman, work in a pharmacy.
Thieves, like this one, steal things.
This thief is stealing a television from a home.
A musician, like this one, plays music.
This musician is playing a guitar.
Stealing things is against the law.
These people are wearing masks because of the smog.
One cause of smog is automobile exhaust.
It’s raining hard so you need an umbrella.
Heavy rain like this can cause flooding and mud slides.
When the sky is overcast we can’t see the sun because of the clouds.
A cloudy sky means that it might rain.
We need to wear a coat when it’s cold and windy.
In a very strong wind, it’s difficult to use an umbrella.
We need to drink water or other liquids when it’s hot outside.
When it’s really hot most people turn on the air conditioning.
Here are some different types of things to read.
Works or fictions include novels, short stories and plays, such as Shakespeare.
We read fiction to enjoy stories of imagination and adventure.
People read the news to learn about what’s happening in the world.
We can get the news in newspapers and online.
When we buy something, we often need to read an instruction manual.
Instruction manuals show us how to put together or install things.
Non-fiction works include biographies and books about science and history.
We read non-fiction to learn about different subjects and real people.
We can learn about the latest scientific research in journals and academic papers.
Many online universities courses give a list of research papers to read.
Dialogue
M1: What’s wrong?
M2: I can’t walk. My left foot hurts.
M1: Is it broken?
M2: I don’t know if it’s broken, but it sure hurts.
-What hurts? –His left foot hurts.
M1: There’s one way to find out if it’s broken.
M2: How?
M1: You need to see a doctor. The doctor can X-ray your foot.
-How can they find out if his foot is broken? –They need to see a doctor.
-Who can X-ray his foot? –a doctor.
M2: OK, let’s go. I can’t walk by myself. Can you help me into a taxi?
M1: Sure, I’ll call a taxi. I’ll get you to a hospital as soon as possible.
M2: Thanks. I sure hope it isn’t broken.
M1: We’ll find out soon enough.
-Where do they want to go? –They want to go to a hospital.
Lesson 6 Discussing Eating out
W: I don’t feel like cooking tonight. Let’s go out.
M: Where would you like to go?
W: I feel like eating some great Italian food.
M: How about AI’s Italian, it’s always good.
-What doesn’t she feel like doing? –cooking.
W: We went there last week. Let’s try something new. You have no imagination.
You always want to go to the same place.
M: Right, I don’t like unpleasant surprises. I just want things to be simple.
-What does she want to do? –She wants to try something new.
-Why doesn’t she want to go to AI’s Italian? –They went there last week.
W: OK, let’s compromise.
M: What does that mean? What do you mean by compromise?
W: Let’s go 50-50.
This time we’ll go someplace new and new and next time we can go to one of your favorites.
M: OK, I’ll compromise and make you halfway.
W: Good, I’ll look for something new and make reservations.
-What does she suggest? –She suggests that they compromise.
M: Great, let’s not go too late.
W: I’ll make reservations for 8. Is that okay?
M: Yes, perfect.
He doesn’t like unpleasant surprises.
Unit2
1/4
Listening
Matter is made of atoms and molecules.
Water, for example, is the H2O molecule.
This means that a molecule of water has 3 atoms.
A water molecule has 2 hydrogen atoms and one oxygen atom.
Substances like sugar have many atoms in their molecules.
A molecule of sugar has many atoms, including carbine, hydrogen and oxygen.
-What is H2O? –The water molecule.
-What is matter made of? –Atoms and molecules.
Matter is made of molecules such as the H2O which is the water molecule.
Matter can be in one of 3 states, solid, liquid or gas.
Water and ice are the same substance, but they are in different states.
These states depend on the temperature of the molecules.
When we heat a substance, the molecules move faster and try to take up more space.
When we cool a substance, the molecules move more slowly.
When we cool a substance to its freezing point, it becomes a solid.
-How many states of matter are there? –Three.
-What happens when we heat a substance? –the molecules move faster and try to take up more space.
-What happens if we cool a liquid to its freezing point? –It becomes a solid.
In a solid, the molecules move very little.
Their positions are almost fixed.
To be fixed means that their positions don’t change.
If we heat the molecules, they move faster and away from each other.
The solid begins to melt, like ice cream on a hot day.
-How can we change a solid into a liquid? –heat it up.
-How can we change a liquid into a solid? –cool it down.
At a certain temperature, a solid begins to change into a liquid.
The temperature at which a solid changes into a liquid depends on the substances.
For water, the solid begins to change into a liquid when its temperature rises to above 100 degrees Celsius.
For some substances, such as steel, the temperature at which it becomes a liquid is much higher.
Steel often melts at around 1370 degrees Celsius.
-At what temperature does ice begin to melt? –Above 0 degree Celsius.
-What does the temperature at which a substance begins to melt depend on? –The substances.
If we continue to heat a liquid, the molecules move even faster.
At a certain temperature, the liquid begins to change into a gas.
For water, the liquid begins to change into a gas at 100 degrees Celsius. This is the boiling point of water.
-What happens if we continue to heat a liquid? –Molecules move even faster.
Inside a star, such as our sun, the temperature is very high.
Everything inside the sun is a gas.
According to scientists, there are over 65 elements inside the sun.
These include oxygen and iron.
Over 90% of the sun is hydrogen gas.
-How many elements are inside the sun? –More than 65.
Yesterday there was an important science test.
Lisa, Tom and 20 other classmates took the test.
The test was about the states of matter and how they are different.
There were 25 questions on the test, and they had 45 minutes to take it.
Here are some of the test results.
Two students got perfect scores.
The lowest score was 68 out of a hundred.
The average score was 86.3
Eleven students scored higher than average.
Eleven students had below average scores.
Tom missed two questions on the test, so his score was 92.
His score was the eighth highest in the class.
Lisa missed two and a half questions, so her score was 90.
Her score was the tenth highest score.
Her score was 4 points higher than the average score.
Lisa was disappointed with her test results.
She studied hard for the test, but she still didn’t do well.
As a result, she plans to study harder for the next test.
The next test will be in about two weeks.
Tom was surprised and happy with his test results.
He didn’t study hard, so his result was better than he expected.
He was also happy that he did better than Lisa did.
Vocabulary
She is screaming because she is really scared.
Something is chasing her so she is screaming for help.
He is shouting because he is angry.
When he’s really angry he often shouts like this.
She is sleeping because she’s tired.
Last night she didn’t get enough sleep, so today she has no energy.
She’s crying because she’s sad.
She got some bad news a few minutes ago.
She’s smiling because she’s happy.
Her boyfriend just called and he’s returning from a long trip.
Who is smiling because she got some good news?
This man is hiking up a mountain trail.
He is wearing hiking boots and is carrying a pack on his back.
This man enjoys cooking.
He attends a cooking class once a week.
This woman enjoys gardening.
She grows flowers, such as roses, and vegetables, such as tomatoes, in her garden.
This boy loves playing games.
He likes all kinds of games, including this video games on his computer.
This old couple enjoys travelling.
They take several trips a year, often to different countries.
Dialogue
Lesson 5 Ready for the Meeting
W: Oh, there you are, finally.
M: Yeah, I’m sorry.
W: Why are you so late? You were supposed to be here 30 minutes ago.
M: I got on the wrong subway by mistake.
-When was he supposed to be there? -30 minutes ago.
-Why was he late? –He took the wrong subway.
W: Why didn’t you call? I was really worried.
M: I don’t have my phone. I left it in the office because I was in such a hurry to get here.
W: OK, well, you’re here now. We don’t have much time.
M: Yes, we’ll have to hurry. The meeting starts in 15 minutes, right?
W: Yes, it’s supposed to, if everyone gets here on time.
-When is the meeting supposed to start? –in 15 minutes.
-To hurry means.. –To go fast.
W: Did you read my presentation?
M: Yes, I do. It’s good, but it’s a bit too long. I’m afraid there won’t be enough time for questions.
W: Do you have any suggestions?
M: Yes, I do. I think the company introduction can be cut in half. They know what we do.
W: OK, I won’t show the video. It’s about 2 minutes long.
M: That’s a good idea. The video is on our website and is not that good any way.
-What is she going to cut from her presentation? –the video.
-Why is the presentation a bit too long? –There isn’t enough time for questions.
W: Do you have any other suggestions?
M: No, I don’t. I’m sure you’re doing a great job. Are you ready?
W: Yes, I’m ready. The meeting room is on the 21st floor.
M: OK, let’s go.
-Where is the meeting going to be? –in a meeting room.
She’s ready to give her presentation at the meeting.
Lesson 6 Discussing Test Results
Lisa: How did you do on yesterday’s science test?
Tom: I did better than expected. How about you?
Lisa: I didn’t do very well. I expected to do better than I did.
Tom: What was your score?
Lisa: I got a 90. What about you?
Tom: I got a 92. I only missed two questions.
-How well did he do on the test? –He did better than expected.
She didn’t do as well as she expected.
Lisa: So you did better than I did. And I really study for it too.
Tom: That is a surprise. You usually do better than I do.
Lisa: Yes, I wasn’t careful. I made one really stupid mistake.
Tom: What was it?
Lisa: I said 90% of the sun is Helium instead of Hydrogen.
Tom: Wow. That was a stupid mistake.
-Why was he surprised by the result? –He did better than she did.
Tom: What was the average score for the class, do you know?
Lisa: The average score was 86.3 and the lowest was 68.
Tom: Do you know who got the lowest test score?
Lisa: No, I don’t. I don’t know who got the lowest score.
Tom: It’s probably a secret. Did anyone get a perfect score?
Lisa: I think Ada and Sandi both got perfect score.
Tom: Yes, they always do well. I wish I were as smart as they are.
-What was the average test score? -86.3.
2/4
Listening
Lesson 1 Paul’s Trip Plan 1-2
In six weeks Paul is going on a trip.
He is going to Japan and China.
There are a couple of reasons for the trip.
One reason is for business.
He is thinking about starting restaurants in both countries.
The other reason is for pleasure.
He enjoys travelling and he’d like to visit some friends.
-What’s going to happen in six weeks? –He is going on a trip.
-What is he thinking about starting in both countries? –He is thinking about starting restaurants.
Yesterday he went online and made airline reservations.
There were plenty of seats on the plane, so it was easy.
He also got a good discount.
Unfortunately, he needs a new passport.
His old passport is expiring next week.
This is something he didn’t expect.
Getting a new passport will take at least a week.
He needs to apply for one right away.
-Why did he need to get a new passport? –His old one is expiring soon.
-What did he need to do right away? –apply for a new passport.
-How long will it take to get a new passport? –At least a week.
Paul also needs a visa to enter China.
The last time he went to China was 3 years ago.
Getting a visa may also take a week or even two.
So he doesn’t have much time.
He needs to hurry.
He can’t get the visa until he gets his new passport.
He’ll have to go to the Chinese consulate in Toronto.
Hopefully there won’t be any delays.
-What may take a week or two? –getting a visa.
-When was the last time he went to China? -3 years ago.
Paul has several friends in each country.
One of his best friends lives near Mountain Fuji.
His friend lives near a beautiful lake about 3 hours from Tokyo.
His friend is a great cook and owns a little restaurant.
The restaurant is located on a hill above the lake.
It has a wonderful view and the food is wonderful.
Paul is looking forward to eating there.
Then he will spend the night at his friend’s house.
-Where is Paul going to stay? –He’ll stay at his friend’s house.
-What does his friend do? –He owns a restaurant.
One way to get to his friend’s house is to go by train.
If he takes a train his friend will meet him at the train station.
There’s a train station about half an hour from his friend’s house.
On the other hand he may decide to go by car.
He can rent a car for a few days and see more of the country.
He can use a GPS to help him with directions.
He doesn’t speak Japanese so the directions need to be in English.
-Why do the directions need to be in English? –He doesn’t speak Japanese.
-If he takes a train, who will meet him? –His friend.
In China Paul has a good friend who lives in Beijing.
They studied at the same university in Canada more than 15 years ago.
His Chinese friend wants to help Paul with his business.
His friend has lots of business experiences.
His friend can help Paul learn about doing business in China.
Paul knows there is a lot to learn.
He will certainly need his friend’s help.
-Where did Paul meet his Chinese friend? –At a university in Canada.
-What does Paul want to learn? –About doing business in China.
While in Beijing, they plan to visit several Italian restaurants.
They may meet with some of the owners too, but it isn’t certain yet.
Most of the owners are Chinese.
One or two of them may want to do business with Paul.
If he has time he may go to the Great Wall of China.
It’s a few hours outside Beijing by car.
-Who may want to do business with Paul? –One or two restaurant owners.
Altogether, the trip may take three or more weeks.
Paul still isn’t sure how long he will stay in each country.
He may spend a week in Japan and two weeks in China.
He may decide to stay longer.
Everything depends on his friends.
He expects to get more information from them in the next day or two.
-When does he expect to hear from his friends? –In a couple of days.
-What do his plans depend on? –His friends.
Vocabulary
In basketball, players score points by shooting a basketball through a hoop.
Each side has 5 players and the game is played on a basketball court.
Football is probably the world’s most popular sport.
Each team tries to score a goal by kicking the ball into a net.
Baseball is a team sport where each side has 9 players.
Baseball players use a bat to try to hit the ball and get on base.
Golf is an individual sport where players try to hit the ball into a hole in the ground.
The game is played on a golf course with 18 holes.
In boxing the two boxers stand in a boxing ring and hit each other.
Sometimes a boxer, like this one, knocks the other one out.
When people fall down, they can break a bone.
A broken bone can be very painful.
If someone is cut, they will bleed.
A knife or sharp object can cut someone and cause bleeding.
Poisons are very dangerous and cause death.
Some snakes and spiders are poisonous, so be careful.
A heart attack can happen very suddenly.
If someone has a heart attack, call for an ambulance right away.
If you catch on fire, fall to the ground and roll.
Getting too close to a fire can be very dangerous.
Dialogue
M: What’s the matter? You look really tired today.
W: I am tired. I didn’t sleep well last night.
M: Bad dream.
W: Yes, exactly. I had a terrible dream, a really nightmare.
M: So it woke you up.
W: Yes, it woke me up. I was really scared.
M: I’ve had those kinds of dreams too.
W: It was so scary that I was afraid to go back to sleep.
-Why didn’t she sleep well last night? –She had a terrible dream.
M: Was something chasing you?
W: No, nothing was chasing me, but I was falling.
I was falling faster and faster, and it was dark. I couldn’t see or hear anything.
M: Can you remember anything else?
W: Yes, I remember now. In my dream I was screaming, but there was no sound.
I thought I was going to die at any second.
M: Wow. That is scary.
-What was she doing in her dream? –falling and screaming.
M: So what did you do when you woke up?
W: I didn’t want to go back to sleep, so I checked the news online. Then I played the game.
M: You didn’t go back to sleep?
W: Actually I got too tired playing the game than I fell asleep.
M: Well, at least you got some sleep. Some sleep is better than no sleep.
W: I guess so. But I’m still tired. I hope I can get through the day.
-What did she do when she woke up? –She went online.
-What was she doing when she fell asleep? –She was playing a game online.
M: Have a good lunch and then work out in the afternoon.
W: Thanks, I’m already feeling a bit better.
M: Hey, look, the boss is coming. Look like you’re working hard.
-How is she feeling now? –She’s feeling a bit better.
She had a terrible dream, and it woke her up.
M: Hey, what’s that awful smell?
W: The toilet is broken in the men’s bathroom.
M: Wow. I can’t work when it smells this bad. I need some fresh air.
-What’s causing the awful smell? –a broken toilet.
-Why can’t he work? –He can’t work because of the bad smell.
W: OK, let’s take a break and go out for a walk. Get your computer and we can work at a coffee shop.
M: Good idea. When do you think it will be cleaned up?
W: A plumber is coming and he should be here soon. By the time we get back, the smell should be gone.
-Who is coming to fix the toilet? –a plumber.
-To take a break means… -To stop working for a while.
M: That’s one job that I wouldn’t want. I hate to be around bad smells. What about you?
W: Me too. I wouldn’t want to be a plumber.
M: There are lots of jobs that I wouldn’t want.
W: We can talk about that later. Get your computer and let’s get out of here.
-What job wouldn’t they want to have? –They wouldn’t want to be a plumber.
3/4
Listening
Lesson 1 Paul’s Overseas Trip 1-2
Last month Paul went on a trip.
He went to Japan and China.
There were a couple of reasons for the trip.
One reason for the trip was for business.
He wanted to start some restaurants in both countries.
The other reason was for pleasure.
Paul enjoys travelling and he wanted to visit some friends.
-What was he thinking about starting in both countries? –some restaurants.
Before leaving on the trip Paul had several problems.
First his passport was going to expire.
As a result he needed to apply for a new passport.
Second he needed to get a visa to enter China.
In order to apply for a visa, he needed his new passport.
He had 6 weeks to get everything done.
-Why did he need a visa? –He needed a visa to enter China.
After applying for a new passport it took 2 weeks to get it.
Once he got the passport he went to the Chinese consulate in Toronto and applied for a visa.
He filled out an application form and stood in a long line.
He was surprised by how many people were applying for visas. It took more than an hour to submit his application.
-How long did it take to submit the application? –It took more than an hour to submit it.
-Why did he go to the Chinese consulate? –To apply for a visa.
He submitted his application for the visa on a Friday.
A week later he went back to the consulate to pick up his visa.
To his surprise, when he got there, the consulate was closed.
The consulate was closed because it was a Chinese holiday.
Paul was angry at himself for not checking the consulate’s website.
On its website the consulate’s schedule was posted.
There was a notice saying that the consulate would be closed that day.
-Why was the consulate closed? –It was a Chinese holiday.
As a result, Paul had to come back the next Monday.
This was because the consulate was closed on weekends.
Finally on Monday, he got the visa and he was ready to go.
-Why did he have to wait until Monday to come back? –The consulate was closed on weekends.
Another problem with the trip was his travel schedule.
He needed to extend his stay in Japan.
One week in Japan wasn’t enough.
3 Japanese restaurant owners wanted to meet with him.
He needed more time for the meetings than a couple of days.
And he didn’t want to miss staying with the good friend of his.
-What did he need to do his schedule? –He needed to extend his stay in Japan.
-What didn’t he want to miss? –Staying with a good friend of his.
His friend lives near Mountain (Mt. for short) Fuji and owns a great restaurant.
This was one thing Paul didn’t want to miss.
As a result he extended his stay in Japan.
Instead of staying for just a week, he decided to stay for 10 days.
-What does his friend own? –He owns a great restaurant.
As a result he had to change the dates for staying in China.
The meetings in China were delayed by 3 days.
Instead of arriving on the 1st of the month, he arrived on the 4th.
Fortunately, there were no problems with his new schedule in China.
-What problems were caused by his new schedule in China? –It didn’t cause any problems.
However there were fewer meetings than he expected.
There wasn’t much interest in opening new Italian restaurants. Still, he had one very good meeting.
He met a young Chinese restaurant owner who was interested.
The young man already has a restaurant, but he wants to improve it.
He and Paul liked each other right away.
They met twice in Beijing and are planning to meet again.
-How much interest was there in opening new Italian restaurants? –not much.
-How many times did Paul meet the young man? –They met twice.
The young Chinese man’s name is G.
He is planning to come to see Paul.
They’re going to meet lately next week in Toronto.
Together they will work on a business plan.
Paul is glad that he took the trip.
He thinks it was a successful and enjoyable trip.
-What are they going to work on? –a business plan.
Vocabulary
Lesson 3 Emergency Vehicles
Ambulances are used to transport injured or sick people to a hospital.
An ambulance is trained medical personal who can treat injured or sick people.
A wheel chair is for people who can’t walk.
Wheel chairs have 4 wheels and are often pushed by people from behind.
Fire engines are used to fight fires.
Firefighters like this one often rescue people from burning buildings.
Tow trucks are used to tow cars, this tow truck is towing a car to a repair shop.
Helicopters are used to rescue people from dangerous places.
This helicopter is lifting someone from a sinking boat.
If your car won’t start, you should call for a tow truck.
Lesson 4 Weather & Activities
This tree is bending over because of the strong wind.
It’s going to be windy for the next few days.
It’s a very clear night, so they can look up and see many stars.
There isn’t a single cloud in the sky.
It’s very cold today, so they are wearing very warm clothes.
Without warm clothes, they would freeze to death.
It’s nice to eat ice cream on a hot day.
This mother is buying ice cream for her daughter.
This old man has to wear glasses to read.
Without reading glasses, he can’t see clearly enough to read.
Dialogue
Lesson 5 Checking up on Ada
M: How was Ada’s new job in Beijing?
W: It seems to be going well. I talked with her last night.
M: How much is she getting paid?
W: I’m not sure. She said she’s earning more, but I don’t know she’s getting.
M: Where is she living? Has she found a flat?
W: No, not yet. She’s living with a friend, until she can find one of her own.
Flats are more expensive there, and the quality isn’t good.
-Who is Ada living with? –She’s living with a friend.
-How long will Ada be living with her friend? –She’s going to stay until she can find a flat of her own.
M: Did she say anything else?
W: Her biggest complaint is the air quality. She hates the pollution.
On some days the pollution is so bad that she is afraid to breathe.
M: Yeah, I won’t want to live there.
W: She’s hoping it will get better.
M: I’m sure we will, but it’ll take time, especially with all the cars.
-What is Ada’s biggest complaint? –the poor air quality.
W: She also said she is still looking for a new boyfriend.
M: That shouldn’t be difficult. She’s nice and she’s good-looking. Has she met anyone?
W: No, I don’t think so. She’s looking for someone on the internet.
M: Maybe she’ll be lucky.
W: I think I’m going to try that too.
M: Really?
W: What other choices do we have? It’s so difficult to meet someone new. I never have any time.
M: Me too. I’m always working. Maybe I’ll try online dating too.
-Where is she looking for a new boyfriend? –She is looking for someone on the internet.
M: If I’m lucky I may meet someone new, like Steve’s girlfriend.
W: Oh, come one, you’re joking, right? I hope you can find someone better than her.
M: Steve seems happy enough.
W: Yes, but he is blind by love, you know that. I’m sure you won’t last for long.
As soon as she gets bored, she’ll find someone else.
M: You may be right. Let’s wait and see.
-What is blinding Steve? –He is blinded by love.
M: Hey, what about dinner?
W: Sure, it’s getting late and maybe I’ll be the woman of your dreams.
M: Well, let’s take one night at a time. Let’s have some Indian food, okay?
W: OK, tend and chicken for me. And I’m hungry.
-What kind of food are they going to eat? –They are going to have Indian food. She’s earning more, but we don’t know how much she’s being paid.
4/4
Listening
Lesson 1 Overview of Earth
Earth is where we all live.
It is our home in the solar system.
There is no other place for us to live.
Earth isn’t just any planet.
It’s a very special place.
It’s special because we depend on it for many things.
Because of its importance we need to take care of it.
-Why is earth so specially? –We depend on it for many things.
We depend on the earth for its air, its water and many of its nature resources.
Nature resources such as coal and oil give us energy.
Other nature resources we depend on include forests and soil.
Forests provide clean air and wood for building houses.
Soil is needed to grow plants and keep them healthy.
We need to take care of these resources and not to waste them.
-What are examples of nature resources? –Coal and oil.
-What don’t we want to do with nature resources? –We don’t want to waste them.
The earth is a large, rotating sphere, about 4.5 billion years old.
The equator, which divides the earth into two hemispheres, is about 40 thousand kilometers long.
The earth’s diameter is 12756 kilometers.
Its radius is half that, or 6378 kilometers.
The radius is the distance from the earth center to its surface.
Most of the earth’s surface is covered by water.
About 75% of the earth’s surface is covered by water.
The rest of the earth’s surface is land.
-What divides the earth into two hemispheres? –The equator.
-Besides water, what is the rest of the earth’s surface? –The rest of the earth’s surface is land.
Just above the earth’s surface is the atmosphere.
The atmosphere is a layer of gases about 500 kilometers thick.
These gases include oxygen, nitrogen and carbon dioxide.
This mixture of gases is the air that we breathe.
As we move about the earth’s surface, the air gets thinner.
At high altitudes, the air is too thin to breathe.
At the edge of the atmosphere is space.
There is no air at all in space.
-Why can’t we breathe at very high altitudes? –The air is too thin.
-What is at the upper edge of the atmosphere? –Space.
-About how thick is the atmosphere? –It’s about 500 kilometer thick.
Most of the earth’s water is in the oceans.
The two largest oceans are the Pacific and Atlantic Oceans.
Unfortunately, we can’t drink ocean water.
This is because ocean water has too much salt.
Fortunately there is also water in lakes and rivers. These water isn’t salty so we can drink it.
Only about 2% of the world’s water is fresh water.
Without fresh drinking water we can’t live.
A person can’t live for more than a few days without water.
-How is fresh water different from ocean water? –Fresh water isn’t salty.
-Why can’t we drink ocean water? –It has too much salt.
One problem with ocean water is that we cannot drink it.
Rivers are important.
Most rivers begin in mountains and end in the oceans.
The water flows from high ground to low ground.
At first rivers are small and are called creeks or streams.
As water enters from other streams, a river grows.
-Where do most rivers end? –In the oceans.
-In which diction do rivers flow? –It flows from high ground to low ground.
Some rivers become very large and long.
The longest river in the world is the Nile River, in Africa.
It’s almost 6500 kilometers long.
As for water volume, the Amazon is the largest river.
The volume of water flowing through it per second is more than in any other river.
-What is the world’s largest river by volume? –The Amazon, in South America.
Another use of rivers is for energy.
The energy of falling water is used to produce electricity.
This use of water supplies over 20% of the world’s electricity.
Rivers are also important for agriculture.
Without water, farmers cannot grow food.
And of course rivers can be used for transportation.
Riverboats are used to carry things to inland cities or lakes.
-How do farmers depend on rivers? –They are needed to grow food.
Vocabulary
Lesson 3 Things We Enjoy Doing
This man goes running 5 days a week if the weather is good.
On the weekends he runs 10 kilometers unless the weather is bad.
This woman really enjoys reading, especially works of fiction.
She has read hundreds of books.
This young couple enjoys watching old movies, such as Titanic.
They both cried when it sank and many people went down with the ship.
These young boys enjoy playing sports on the weekend.
Sometimes they play basketball and sometimes they play football.
This young man eats too much sweet so he is overweight. He need to eat fewer sweets and exercises more.
He is overweight because he eats too many sweets.
Here are six of the earth’s seven continents.
Asia is the largest continent both in land and in population.
Asia covers 30% of the earth’s land area.
Africa is the second largest continent.
Of all the continent Africa has the youngest population.
Europe is to the west of Asia, and is second smallest continent.
Europe is the birthplace of classical music and some of the world’s greatest art and literature.
North and South America are bordered on the west by the Pacific Ocean and on the east by the Atlantic Ocean.
The first human beings to live in the Americas came from Asia more the 50000 years ago.
Australia is the world’s smallest continent and the world’s largest island.
Australia is surrounded by the Indian and Pacific Oceans.
Dialogue
Lesson 5 A Driverless Car
M1: Hey , look at that.
M2: Look at what?
M1: Look out the window. Do you see the young lady in the red dress?
M2: Yeah, I see her. Wow, she is beautiful and hot. Look at the way she walks.
M1: Yes, no one behind her. Look in the car that’s following her.
M2: I’d rather look at the young lady.
-What does his opinion about the young lady? –He thinks she’s beautiful and hot.
-Where is he supposed to look? –in the car.
M2: So what’s so special about the car?
M1: Look at the driver, do you see one?
M2: No, I don’t. There isn’t anybody driving the car.
M1: Right. It’s one of those new driverless cars.
M2: Maybe it’s the woman’s car. It’s following her.
M1: I don’t know. Maybe you are right.
M2: Now that’s a smart car. Maybe I’ll go outside and follow her too.
M1: Hey, get back to work.
-Who is driving the car? –no one.
-What is the car following? –a young lady.
Lesson 6 Calling Customer Service
Answering machine: Thank you for calling our customer support.
Please listen to the following menu to help us direct your call.
Please say or press 1 to pay your bill.
Please say or press 2 to upgrade your service plan.
Please say or press 3 to report a technical problem.
Please say or press 4 if you want to hear this choice again.
Customer: I don’t want any of these choices.
-How does the custom feel? -Angry.
Answering machine: You may also go to our website for help.
Customer: I went to your website but it didn’t help. I want to speak to a human being.
Answering machine: Your business is very important to us.
-How does the custom feel? –Frustrated.
Answering machine: Please say or press 5 or hang up to end this call.
Customer: None of these. I want a human being. I want to cancel my service.
Answering machine: Please wait while we connect you to a service representative.
Customer: Finally. This is what they call customer service?
-What is the custom trying to do? –He wants to cancel his service.
Answering machine: To assist our representative, please say your first and last name.
Customer: Tom Smith.
Answering machine: We hear Tom Smith. If this is correct, say or press 1.
If this is not correct, say or press 2. Customer: 1.
Answering machine: Thank you. For security purpose, what was your father’s middle name?
Customer: he didn’t have a middle name.
Answering machine: Thank you. A customer service representative will be with you shortly.
-Why did they want the custom’s father’s middle name? –To confirm the customer’s identity.
-For security purpose means about the same as? –For safety reasons.
Answering machine: I’m sorry but our offices are closed.
Please call back during business hours.
Our business offices are open Monday through Friday, from 8:00 am until 6:00 pm.
Thank you for calling.
Unit 3
1/4
Listening
Lesson 1 Life & Conditions 1-2
There are many forms of life on Earth, including human beings.
Life exists in a variety of conditions.
Some forms of life live in a watery environment, like the oceans.
Other forms of life can be found in very dry areas, like deserts.
However, for any form of life to exist, conditions must be right.
When conditions are not right, that form of life will become extinct.
To become extinct means to die out completely.
-What must be right for life to exist?-Conditions.
-What happens if conditions are not right? –Life cannot exist.
Conditions must be right for life to exist.
Millions of years ago, there were forms of life that no longer exist.
When conditions changed, these forms of life died out.
One extinction event happened about 250 million years ago.
This was the largest extinction event of all time.
Many forms of life became extinct.
96% of all life in the oceans died out.
Most insects also became extinct.
This event happened over a period of several million years.
-What happened about 250 million years ago? –Many forms of life became extinct.
-What happens in an extinction event? –Many forms of life became extinct.
The causes of this extinction event are still unknown.
Possible causes include large volcanic eruptions and global warming.
Some scientists believe that there were several causes.
They believe that a series of events caused the extinctions.
Scientists are working to better understand what really happened.
-What is the one possible cause of this event? –Volcanic eruptions.
In modern times, we humans face changing conditions.
For humans to live, we need clean air and clean water.
Pollution is now a growing problem around the world.
Pollution poisons the air and water that we depend on.
Polluted air makes people sick and afraid to go outside. Polluted water poisons our food supply.
As a result, we never know which foods are safe to eat.
Human beings cannot live in a poisoned environment.
Therefore, pollution is a major threat to our existence.
-What do humans need to live? –Clean air and clean water.
-What poisons the air and water? –Pollution.
Humans need temperatures to be in a comfortable range.
To be in a comfortable range means to be neither too hot nor too cold.
With global warming, global temperatures are rising.
As temperatures rise, the polar icecaps will melt.
As the polar ice caps melt, ocean levels will rise.
Areas of some countries will soon be under water.
People will be forced to relocate from flooded areas.
-As temperatures rise, what will happen to the polar icecaps? –The polar icecaps will melt.
-As the polar icecaps melt, what will happen? –Ocean levels will rise.
In nature, even small changes can sometimes have large effects.
It’s difficult to predict what’s going to happen.
The entire ecosystem that we depend on is changing.
Some of these changes are irreversible.
Irreversible changes cannot be undone.
-What can small changes sometimes cause? –Large effects.
-What is happening to the world’s ecosystem? –Ecosystem is changing.
Let’s hope that humans are smart enough to understand how the world is changing.
With more understanding, we can make better choices about what to do.
We can face the challenges of pollution and global warming.
We need to do this before it’s too late.
This planet Earth is our only home and we need to protect it.
-What challenges do we need to face? –Pollution and global warming. We need to protect the environment that supports us.
Vocabulary
Mammals are covered by hair or fur, have a backbone, and are warm blooded.
All female mammals produce milk for their young.
Reptiles are covered by scales, and includes snakes, lizards and turtles.
Reptiles have a backbone and are cold blooded, which means they often relied on the external source of heat.
Birds are covered by feathers and are warm blooded.
Most birds can fly and many types of birds migrate great distances.
Most insects such as ants and bees have a small three part of body with three pairs of legs.
Some insects, like mosquitoes, spread diseases that cause the deaths of many humans.
Unlike animals, plants get the energy that they need from the sun.
Plants convert light energy, along with carbon dioxide and water, into chemical energy.
Insects don’t have a backbone and most are cooled-blooded.
Insects such as ants and bees live in well-organized colonies.
Mosquitoes cause the deaths of more humans than any other animal.
Mammals include some of the most intelligent animals on earth, such as elephants and human beings.
Scales and rulers are used to measure weight and length.
Units of weight include kilograms and pounds, and units of length include centimeters and inches.
These instruments are used to observe very large and very small objects.
Telescopes are used to by astronomers and microscopes are used by biologists and doctors.
These appliances are used in the kitchens of almost every home.
Stoves are used to heat food and refrigerators are used to keep foods cool or cold.
Household tools like these are used to build and repair things.
Hammers are used to pound in nails and screwdrivers are used to turn a scow.
If you need to pound in a nail, use a hammer.
Dialogue
Lesson 5 Dating Anniversary
W: do you know what day it is today?
M: what do you mean? Is it a special day?
W: oh, so you don’t remember.
M: remember what? What’s so special?
W: it’s our anniversary. We started dating a year ago today.
M: oh, really, I’m sorry.
-When did they first start dating? –A year ago.
M: just a minute. What do you think this is?
W: oh, it’s a necklace.
M: do you like it?
W: yes, I do. It’s lovely, especially the red heart. May I put it on?
M: no, let me do it.
-What did he give her? –A necklace.
W: so you did remember.
M: of course I remembered. It’s a very special day for both of us.
W: I have something for you too.
M: you do?
W: yes, but it will have to wait until later.
M: oh, I can’t wait. Tell me what it is.
-What would have to wait until later? –She’s going to give him a gift.
Do you know what today is?
W: can you guess what it is?
M: could you give me a hint?
W: we went there six month ago.
M: oh, you mean Alfredo’s.
W: yes, are you excited? You said you really like the food there.
M: yes, that’s true. I also remember the dessert. Do you?
W: yes, but let’s not talk about that now. Let’s now ruin the surprise.
-What is Alfredo’s? –A restaurant.
-What aren’t they going to talk about? –They aren’t going to talk about the desert.
He remembered that today is their anniversary
W: That restaurant looks nice.
M: Yes, but it looks expensive.
W: Let’s go in and look the menu. Wow the menu looks great, especially the fish.
M: Yes, it looks good, but look at those prices.
-What doesn’t she like about the menu? –She likes the food choices.
M: Let’s try somewhere else.
W: Sometimes it’s ok to spend a little money.
M: Yes, but these prices are a bit too high, don’t you think?
W: Yes, there are a bit high. But don’t you think I’m worth it? Let’s enjoy ourselves.
M: Ah, ok, if you put it that way. Let’s see if we can get a table.
W: I’m glad you have your credit card.
M: I sure hope the food is good.
W: Stop worrying. Let’s just enjoy.
-Who is going to pay the bill? –He will pay the bill.
-How is he going to pay? –He is going to use his credit card. He is worried about spending so much money.
2/4
Listening
Quick Serve is a home repair company.
It provides quick, reliable repair services to homes.
Quick Serve handles plumbing and electrical issues, 24 hours a day.
It also cleans roofs, fixes internet connections and replaces broken windows.
For a small fee, customers subscribe to the service.
Its main customers are the elderly, which means older people.
Whenever customers have a problem, they can call for help.
There is also a small service charge for each service call.
-What kind of services does Quick Serve provide? –Home repair services
The company was established 5 years ago and is growing rapidly.
It started in one city but is now in 5 cities.
The company plans to expand to 10 cities within the next 24 months.
In each city there is a small central office in the low-rent area of the city.
The central office handles the business, advertising, payroll and billing.
It also takes calls from customers, either on line or by telephone. It takes calls 24 hours a day, 7 days a week.
-When was the company established? –It started five years ago.
-Where does the company locate its central offices? –They locate in low-rent areas.
60% of the company’s employees work from their homes.
When a customer calls into central office, a service employee is contracted.
The service employee then contracts the customer and signs up an appointment.
These service employees are highly trained and provide excellent service.
In emergencies, such as a serious plumbing problem, service can be provided within an hour.
One reason for this is that the service employees live in different parts of the city.
They are not centrally located so it’s quicker and easier for them to travel to a customer’s home.
-Where do 60% of the company’s employees work? –From their own homes.
Quick Serve has an excellent reputation.
Its prices are reasonable and its services are quick and efficient.
The company’s service employees are clean, polite and efficient.
In this type of business, person to person contact is the key to success.
With each satisfied customer, more customers subscribe.
Satisfied customers recommend Quick Serve to their friends.
This kind of word of mouth advertising is very cost effective.
Cost effective means that the results are good without paying a high price. In other words, quality service provides its own reward to the company.
-What kind of customers recommend Quick Serve to their friends? –Satisfied customers.
-What kind of reputation does the company have? –It has an excellent reputation.
The company takes great pride in being honest with its customers.
There are no hidden charges for their services.
As a result, the number of customers in each city is growing rapidly.
With the aging population there are more elderly people who need home repair services.
These people need to have confidence in the service provider.
They don’t want to be cheated.
These people don’t mind to pay a reasonable fee for high quality service. High quality service should be rewarded.
-What should be rewarded? –High quality service.
-What is the company pride of? –It’s honest with its customers.
The company provides a range of service plans, each with the different subscription plans.
The least expensive service plan is called the basic plan.
This plan provides non-emergency services with a very low service charge.
The most expensive service plan is their VIP plan.
The VIP plan provides emergency services 24 hours a day with no additional service charge.
It also provides rebates to customers who don’t call for any services during the year.
In addition, Quick Serve gives bonus points to customers for each year they subscribe.
These bonus points can be used to buy new appliances such as stoves and refrigerators.
-What kind of service plans does the company provide? –It has a range of plans.
-What can bonus points be used for? –Buying new appliances.
If the business continues to grow, the owners may decide to take the company public.
This means that the public can buy shares of the company.
It will then change from a privately-owned company to a public company.
The owners believe that their business is successful and can expand around the world. They also believe that taking their company public can make them rich.
-Why do the owners want to take their company public? –They can become rich.
Vocabulary
Biology is the study of life, including its structure and evolution.
Biologists study how life survives and reproduces.
Chemistry is the study of matter, including the structure of atoms and molecule.
Chemists study how various substances interact with each other.
Astronomy is one of the oldest sciences.
Astronomers study the structure and evolution of the universe, including the study of stars, planets, and galaxies.
Geology is the study of the structure and history of the Earth and the other planets.
Geologists study different types of rocks, earthquakes, and different layers of the Earth.
Mathematic is the study of numbers, shapes, patterns and change. Mathematic is used by all other branches of science.
Here are some types of terrible events that hurt or kill people.
Earthquakes are caused by forces deep within the Earth.
During earthquakes, many people are often killed by collapsing buildings and bridges.
Floods happen when rivers rise and overflow their banks.
Flood waters damage or destroy many houses and businesses.
Fires destroy buildings, land and forests.
There are many causes for fire, including lightning.
In a hurricane, high winds destroy buildings, and sometime cause flooding.
Some hurricanes have winds of more than 200 miles an hour.
Car accidents happen when cars collide, or when drivers lose control of their cars.
One of the main causes of car accidents is driving too fast.
When people are not careful, they can start fires that can cause a lot of damage.
Dialogue
W: What’s in the big box you are carrying?
M: It’s a new desk. I just bought it and now I have to put it together.
W: Do you need any help?
M: No, I don’t think so. I just need to get my tools. I’ll need a screwdriver and maybe a hammer.
W: Don’t forget to read the instructions.
-What does he need? –Some tools.
W: How are things going?
M: I’m almost finished.
W: Something doesn’t look right to me. The right side is higher than the left side.
M: Oh, you are right. It looks like I put a couple of screws into the wrong places.
-What doesn’t look right? –The desk.
W: So now you have to take it apart.
M: Great. And I thought I was almost finished.
W: I told you to read the instructions. Did you read them?
M: No, I didn’t read them. I hate to read instructions. I looked them, but they were confusing.
W: Well, this is what happens when you don’t. You were too impatient. Anyway, what can I do to help you?
M: Would you get another screwdriver and help me unscrew some of these screws?
W: Ok, but next time please read the instructions.
-What didn’t he do? –Read the instructions.
-What was wrong with the instructions? –They were confusing.
Lesson 6 Life and the Universe
W: Do you ever look up at the sky and think about life and universe?
M: I did when I was a kid. But I don’t do that for as much anymore. Why do you ask?
W: Sometimes I feel like I lost in day-to-day details.
Then when I look up at the sky, I see the big picture. I appreciate things more, even the little things.
-What happens when she sees the big picture? –She appreciates things more.
-What doesn’t he do so much anymore? –He doesn’t think about life and universe.
M: You sound like a philosopher or a poet. I felt like that too when I was a kid.
W: Don’t you feel like that anymore?
M: No, I don’t. In fact, I try not to. When I think about things too deeply, I get depressed.
It’s even a bit frightening.
W: Really? For me, it’s just the opposite. Everything seems like a wonderful miracle.
M: Doesn’t that frighten you a bit? The universe is so large and we are so small.
-What happens when he thinks too deeply? –He gets depressed.
W: What I realize is how little we understand. We just need to appreciate our lives and not get lost.
M: Sometimes being lost isn’t so bad. Do you the expression, ignorance is bliss?
W: Sure, I’ve heard it many times. To be ignorant is to be happy.
-What does the word bliss mean? –Complete happiness.
-What does she realize? –There is a lot that we don’t understand.
M: Maybe it’s true. Maybe it’s best not to think or know too much.
W: No, that’s not for me. I want to understand as much as possible. That’s why I became a scientist.
M: Well, I respect your choice, but it’s not for me. If understanding is painful, I’d rather not understand.
-Why does she become a scientist? –She wants to understand as much as possible. -What doesn’t he agree with? –Her choice.
3/4
Listening
Lesson 1 Harry’s Business Trip 1-2
Harry is on a business trip.
Yesterday he was supposed to fly from San Francisco to Shanghai.
However, things didn’t turn out the way they were supposed to.
In fact, nothing went the way it was supposed to.
Everything went wrong and he didn’t get on his flight.
As a result, he is still in San Francisco.
-What was he supposed to do yesterday? –Fly to Shanghai.
-When was Harry supposed to fly to Shanghai? –Yesterday.
The following is the summary of what happened.
Yesterday morning he got up as usual and had breakfast.
Everything seemed to be fine and he was looking forward to the trip.
He was just about to check out of his hotel when he felt a pain.
It was a pain in his lower back.
It was a doll pain at first, not too bad.
So he didn’t worry about it and he checked out of the hotel.
Then he got on a shuttle bus to the airport.
-Where was the pain located? –It was a pain in his lower back.
-Why didn’t he worry about the pain? –It wasn’t too bad at first.
About half way to the airport, the pain in his back started to get worse.
It was a growing pain, and he was beginning to worry.
Soon it was difficult for him to sit in the seat.
The pain was getting worse.
He wanted to lie down.
He started to sweat and breathe quickly.
He was in real pain then.
On a scale of 1 to 10, the pain was an 8.
-How was the pain changing? –It was getting worse.
-Why did he want to lie down? –It was difficult for him to sit in the seat.
When the bus got to the airport the bus driver helped him get off.
It was difficult for him to walk but he finally made it to the terminal.
Inside the terminal he went to the man’s bath room. He went to the toilet but that didn’t help.
Instead of improving he felt dizzy and he threw up.
By now he was wet for all the sweating.
He knew he couldn’t get on his flight.
-How did he feel after he went to the toilet? –He felt dizzy and sick.
-Where did he go once he got inside the terminal? –He went to the men’s bathroom.
He used his phone to call the airline.
He explained the situation and cancelled his reservation.
Then he called 911 for emergency help.
911 is the emergency number to call for help in the United State.
-What did he do to his reservation? –He cancelled it.
-Why did he call 911? –He called 911 for emergency help.
An ambulance arrived about 10 minutes after he called.
By then he was in so much pain that he could barely walk.
Once inside the ambulance they gave him oxygen to help him breathe.
But the pain was still terrible.
Then they drove him into a hospital near the airport.
Luckily the hospital was on his health plan.
That means his health insurance is supposed to pay for everything.
Medical costs in the United States are very high.
-Who was supposed to pay for his medicine care? –His health insurance company.
-What did they give him inside the ambulance? –They gave him oxygen to help him breathe.
When he arrived at the hospital he was taken into the emergency room.
After some test a doctor told him he had a kidney stone.
It was a very small stone but it caused a lot of pain.
It was passing through a small turbine his body from his kidney to his bladder.
The pain would go away once it got to his bladder.
Until then he had to get pain medicine to reduce the pain.
-Where was he taken when he got to the hospital? –He was taken to the emergency room.
-What did he take to control his pain? –Some pain medicine.
Harry didn’t have to stay at the hospital for very long.
With the pain medicine the pain went away very quickly.
He took a taxi back to his hotel and checked in for another night.
Then he called the airline and made reservation for another flight.
The flight will leave tomorrow.
Until then he’ll just rest in his hotel.
There may even be a good movie to watch.
-Where will he be until his next flight? –He’ll stay in his hotel.
-What is he going to do until his next flight? –He is going to have some rest.
So when you are travelling, please be prepared for emergencies.
Make sure you have medicine insurance.
You never know when something like this can happen to you.
So be prepared.
-What should you have before travelling? –Medicine insurance. It’s a good idea to have medicine insurance before travelling.
Vocabulary
Lesson 3 Sources of Energy
Solar energy is one of the cleanest and most plentiful sources of energy.
Solar power depends on sunlight, so in cloudy weather and at night, no power is generated.
Wind energy is nonpolluting but is only useful in place where there is a lot of wind.
Wind turbines convert the kinetic energy of the wind into mechanical power.
Nuclear energy is efficient and doesn’t produce carbon gases as a waste product.
The dangers of nuclear power include deadly radioactive waste products.
A major source of energy comes from the burning of fossil fuels, such as coal and oil.
When we burn fossil fuels, waste gases such as CO2 are produced.
Fossil fuels remain the largest source of energy for most countries.
Hydropower comes from the kinetic energy of falling water.
Output is reliable and can be regulated to meet the demand, except during the periods of drought.
One of the main problems we face is how to reduce the use of the fossil fuels to produce energy.
We need to reduce the use of the fossil fuels to produce energy. Dams are expensive to build and affect wildlife such as fish.
Here are some different types of words in English.
Words that are nouns or pronouns are used to represent objects.
A noun or a pronoun can be a person, an animal or a thing, including an idea.
Verbs are used to express actions, such as to sit down, or stand up.
We also use verbs to express relationships, such as to love someone or to own something.
We used adjectives to describe objects, such as a tall building.
Adjectives are used with nouns and pronouns, but not with verbs.
We use adverbs to describe actions, such as to run fast or walk slowly.
Adverbs express the quality of an action, such as how well or poorly something is done.
We use conjunctions to connect things or actions, such as to read and write.
Conjunctions include words such as and, or, because, but, and yet.
Nouns and pronouns can be used to represent any object.
Dialogue
Lesson 5 Good News & Bad News
W: Hey, I’ve got some news, some good news and some bad news.
M: OK, give me the bad news first.
W: We are moving to a new office.
M: When is this going to happen?
W: We are supposed to move at the end of next month.
M: How far away is the new office?
W: We are not sure yet. But it will mean a longer commute for most of us.
The new office will probably be on the other side of the city.
M: The commute is already too long for me and I’m not going to change flats. We just bought one.
-What did he just but? –He just bought a new flat.
-How is the move going to affect the commute? –It’ll make the commute longer for most of the employees.
M: Anyway, what’s the good news?
W: The good news is that we are going to expand.
The company is growing so we are going to hire more people.
M: Well, I’ve got some news for you too.
W: I hope it’s a good news.
M: Well, that depends on your point of view. I’m planning to start my own business.
W: Why? I thought you were happy working here.
M: I like the work, but I’m not learning anything new. I think I can do better on my own.
-Why is the company going to hire more people? –The company is growing.
M: I was planning to wait a few months. But now that the office is moving, I’m ready to make the change.
W: What is your wife think?
M: She’s in fever of it and she will help me. She’s already designing a website.
We’ll work from home at first.
W: So you really are serious about this? You’re taking a big risk. Most new businesses fail.
M: Yes, I know, but if I don’t do it now, I never will. I’m tired of working for others.
W: I know what you mean.
-What does his wife think his decision? –She’s in favor of it.
-What is he serious about? –He is serious about starting his own business.
M: Don’t tell anyone about this, OK? It’s still a secret.
W: Sure, I won’t say anything to anybody. I’m sure this will come as a surprise to everyone.
M: I’m sure changing offices will also come as a surprise to people.
This is exactly why I want to work on my own. I don’t like these kinds of surprises.
W: You are right about that. When are you going to let people know?
M: I’ll make the announcement at the beginning of next month.
-What is a secret? –His decision to leave the company.
-When is he going to let people know about his decision to leave? –He’ll announce his decision at the beginning of next month.
4/4
Listening
Lesson 1 Leonardo da Vinci 1-2
Leonardo Da Vinci is one of the greatest geniuses of all time.
He was a painter, an architect, an engineer and a scientist.
He was born in Vinci, Italy in 1452.
Vinci is a town just outside the great Italian city, Florence.
His name Da Vinci means of Vinci.
Leonardo’s father was a lawyer and a landowner and his mother was a present.
Leonardo’s parents were never married to each other.
-How long were his parents married? –They were never married.
-Where was he born? –In Vinci, Italy.
Leonardo lived with his mother until he was around 5 years old.
When he was 5, he moved into the home of his father.
By then, his father had married a 16-year-old girl.
Leonardo’s mother married another man and moved to another town.
She had many more children after that, with several different men.
In the end, Leonardo had more than 15 half-sisters and brothers.
-With whom did he live when he was 5? –His mother.
As a young man, Da Vinci didn’t go to school.
He was educated at home in reading, writing and mathematics.
In other subjects, he was mostly self-educated.
He had access to books at his father’s home.
Leonardo spent a lot of time outdoors and developed a strong interest in nature.
He loved to observe things, especially birds.
He was also interested in the properties of water.
-What did he have access to at home? –Books at his father’s home.
-In what did he develop a strong interest? –He developed a strong interest in nature.
Leonardo’s early drawings and paintings demonstrated a rare talent.
His father and his father’s friend recognized his talent and encouraged him.
When he was 15, he was sent to Florence.
In Florence, he became an apprentice to a famous master painter.
For the next few years Leonardo worked at his master’s workshop.
It wasn’t long before his ability surpassed that of his master.
Some people say that his master became jealous about Leonardo’s greatest talent.
They say that the master vowed to never paint again.
In 1478, with his father’s help, Leonardo set up his own workshop.
-Who became jealous with Leonardo’s talent? –His master in Florence.
In 1482, he entered the service of a powerful man in the city of Milan.
This man was the duke of Milan.
For the next few years, Leonardo designed buildings, machinery and weapons of war.
Weapons were important because Italy was constantly at war during this period.
From 1485 to 1490, Leonardo produced designs for a variety of weapons.
In his notes, he predicted the development of advanced weapons such as submarines and flying machines. In 1499, the French invaded Italy, and Leonardo left Milan.
-Why did Leonardo live Milan? –The French invaded Italy.
-Who did Leonardo work for in Milan? –He worked for the duke of Milan.
All together Leonardo spent 17 years in Milan.
During this period he spent much of his time studying in nature.
He dissected bodies, both human and animal, to study an illustrate anatomy.
His detailed illustrations are masterpieces.
Leonardo filled many notebooks with drawings and ideas.
He wrote backwards so you need a mirror to read them.
-Why do you need a mirror to read his notebooks? –He wrote backwards. He left Milan because the French invaded Italy.
After 1500, Leonardo spent time in a number of Italian cities.
He worked very slowly and the range of his interests was very wide.
As a result Leonardo left many paintings and projects unfinished.
One painting that he did finish was the Mona Lisa, one of the world’s most famous paintings.
People are still interested in this painting, 500 years after he painted it.
Though there are many theories nobody knows who the woman in the painting really was.
-Why did Leonardo leave so many projects unfinished? –He worked slowly and had a wide range of interests.
-Who was the woman in the painting? –Nobody knows for sure.
In 1516, Leonardo left Italy for good when the French King, Francis I (the first), offered him a position.
There he had a freedom to paint and draw whatever he wanted.
Leonardo died in 1519 at the age of 67.
Some said that the French king who had become a close friend was with him when he died.
He was buried in the church which was destroyed during the French revolution.
The exact location of his remains is unknown.
-How old was he when he died? –He died at the age of 67.
-Who offered Leonardo a position in 1516? –The king of France.
Vocabulary
Lesson 3 Sources of Pollution
Waste water and carbon gases from farm animals are bad for the environment.
Animals waste and other chemicals flow into the ground and pollute water supplies.
Exhaust gases from automobiles are a major cause of air pollution and global warming.
As a result many companies are trying to produce more efficient and cleaner cars.
Pesticides and fertilizers are used by farmers to grow crops such as fruits and vegetables.
These chemicals pollute water supplies when they flow into the ground or rivers.
Factories like this one allow harmful chemicals to get into the air or water.
Companies need to try harder to protect the environment and our health.
Nuclear waste products are radioactive and can pollute the environment for thousands of years. They need to be safely transported and stored in a safe place.
Nuclear waste products need to be stored in a safe place.
Lesson 4 Historical Figures
The British writer, Jane Austin, was born in England in 1775, one of seven children.
She wrote some of the most popular love stories of all time.
One of the most famous female rulers in history, Cleopatra had affairs with Julius Caesar and later with Mark Antony.
She was known for her great beauty and charming voice.
Born in 1756, Mozart composed and performed some of the world’s greatest classical music.
He was the youngest of 7 children and by the age of 5, he was already composing music.
The sun of the king, Alexander the great, was the military leader who created one of the largest empires in the ancient world.
As a youth, Alexander was taught by the Greek philosopher Aristotle.
Mohandas Gandy was a 20th century leader who used non-violent resistance to lead India to independence. Gandy dedicated his life to the pursuit of truth.
Mozart started writing music as a young child.
Dialogue
M: I’d like to speak with Mr. Bennett, please.
W: I’m sorry, but he’s not here right now. Would you like to leave a voice message?
M: It’s urgent that I speak with him. It’s an emergency.
W: Oh, I see. What kind of emergency?
M: It’s very personal so I can’t give you any details.
-What does the word urgent mean? –Need quick attention.
-Why doesn’t he want to leave a voice message? –It’s an urgent matter.
W: Without any details I’m afraid I can’t give you his number.
Give me your number and I’ll let him know about your call.
Then maybe he’ll call you back, would that be okay?
M: Sure, my number is 5834987. It would be great if he could call me within the next half hour.
-Why doesn’t she give out Mr. Bennett’s number? –She needs more details.
M1: That was a great dinner. Here, put away your wallet, I’ll the bill.
M2: You paid last time, this time is my turn to pay.
M1: Hey, you don’t have a job, and I do, let me pay.
M2: Thanks for the offer, but I can handle it.
-Why does he want to pay? –It’s his turn to pay.
M1: Wait, let’s flip for it.
M2: Flip for it? What does that mean?
M1: Do you see this corn? This side is heads and the opposite is tails. I’ll flip up in the air.
If it comes down with heads facing up, I’ll pay. If tails are the up, you can pay.
M2: OK, that’s fine with me.
-How are they going to decide who is going to pay? –They are going to flip a corn.
M1: Look, it’s heads up, so I’ll pay.
M2: Thanks, it’s very nice of you.
M1: It’s my pleasure.
Lesson 6 Setting the Bill
W: Do you want anything else, Sir? Would you like to see the desserts menu?
M: No, thanks, I’m ready for the check. Here is my credit card.
W: I’m sorry, Sir, but we don’t take credit cards.
M: You’re joking, right?
W: No, sir. I’m not joking. Do you see that sign? It says cash only.
M: I didn’t see it when I came in. I don’t have enough cash to pay the bill.
-How did he plan to pay? –He planned to pay by credit card.
-Why can’t he pay? –He doesn’t have enough cash.
W: There is a bank down the street.
If you let me hold your driver’s license, you can go and get the cash.
M: OK, I hope the bank is open.
W: The bank is closed, but you can use the ATM to get your cash.
-Where can he get the cash? –He can get the cash at an ATM down the street. He has to leave his driver’s license with the waiter.
android接入支持海外的支付,visa,mastercard2015-09-08 11:00:32
。最后还是找到了支付宝海外支付。
sdk文档地址:(对,只有英文文档,没有中付(这个目前我们应用测试结果是这样子的)。
国内的信用卡不能支付,不管是双币还是其他(这个很忧伤)。我在测试环境测试好后,只能麻烦海外用户帮忙测试。。。
下面我把基本步骤给贴出来,还有一些注意事项。
开发前的准备工作
申请注册webhook《--这里有说明
按照文档说,发送申请邮件到指定邮箱,在发之前,最好跟支付宝技术人员先联系上,说明想接入他们这个sdk。否则人家看到你发的邮件都不知道是多久以后了。
webhook的作用:主要是通知我们的服务端,支付结果。
1、选择下载哪个demo
官方网站有三个demo(mCommerce Sample App、CheckoutScreens Sample App、Tokenization Sample),我接入的是第一个,
第二个放入我们工程会报错,第三个支付宝技术人员说不要用(我就想既然建议不要用,为何要有)。
下面我说的,就是按照demo里面的代码该注意的地方重点说明。
下面的这个两个参数,测试环境下就按照官方给的值,不用改。在正式环境中,建议吧这两个值放在服务端。
在测试环境中.初始化initializaProvider(PWProviderMode.TEST,
APPLICATIONIDENTIFIER, PROFILETOKEN); 正式环境中记得改成PWProviderMode.LIVE.
创建订单,
这里我选择的是美元收款,文档里面可以有多种收款币种选择的。最后支付宝会结算成人民币给我们。信用卡类型,我总共就用两个visa和mastercard。两种充值类型逻辑都是一样的,唯一的区别就是这个PWCreditCardType.VISA还是PWCreditCardType.MASTERCARD.根据自己的需求。
创建订单后要选择对订单中哪些数据进行风控。这个风控系统是支付宝自己的系统,主要判断订单的风险性,他们自己有套过滤标准。
这个demo里面绝对没有,除非后面更新了。
这里的美元单位是要美分的
设置订单号:
paymentParams.setCustomIdentifier(orderNum+"");
发起注册预授权(pa)
_binder.createAndRegisterPreauthorizationTransaction(paymentParams);在回调函数
creationAndRegistrationSucceeded中
发起pa:
_binder.preauthorizeTransaction(transaction);
pa成功后,注册cp:
_binder.createAndRegisterCaptureTransaction(paymentParams, transaction.getMobileIdentifier());
注册cp成功,发起cp:
_binder.captureTransaction(transaction);
完整的java 代码如下:
public class ProcessTransactionActivity extends Activity implements
PWTransactionListener{//,PWTransactionStatusListener
private PWProviderBinder _binder;
private String APPLICATIONIDENTIFIER = null;//"payworks.sandbox";
private String PROFILETOKEN = null;//"20d5a0d5ce1d4501a4826a8b7e159d19";
private ServiceConnection _serviceConnection = null;
private PWPaymentParams paymentParams = null;
private PWTransaction transaction = null;
private RelativeLayout ry_btn_back,ry_btn_next;
private TextView tv_title,tv_tips;
private EditText edt_name,edt_cardNumber,edt_cvvNumber,edt_mm,edt_yyyy,edt_emailAddress;
private TextView btn_submit;
private Dialog waitDlg;
private RechargeCoinType coinType;
private int fromWhere = 0;
private String orderNum = "0"; //订单号
private String clientIPAddress = ""; //客户端的ip地址
private boolean isOperating = false;
private int clickPayWay = 0;
private final static int aplipayClientPay = 1;
private final static int aplipayWebPay = 2;
private final static int visaPay = 3;
private final static int masterCardPay = 4;
private TextView textTips;
private void setStatusText(final String string) {
runOnUiThread(new Runnable() {
public void run() {
if (textTips == null) {
textTips = ((TextView) findViewById(R.id.textView1));
}
textTips.setText(string);
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_processtransaction);
Bundle bundle = this.getIntent().getExtras();
if (bundle != null) {
fromWhere = bundle.getInt("fromWhere");
PROFILETOKEN = bundle.getString("profiletoken");//可以根据自己的设计获取
APPLICATIONIDENTIFIER = bundle.getString("applicationidentifier");//可以根据自己的设计获取
orderNum = bundle.getString("ordernum");
clientIPAddress = bundle.getString("clientIPAddress");
clickPayWay = bundle.getInt("clickPayWay");
}
if (clickPayWay == visaPay) {
clickKey = "visa";
} else if (clickPayWay == masterCardPay) {
clickKey = "matercard";
}
if (PROFILETOKEN == null || APPLICATIONIDENTIFIER == null) {
finish();
return;
}
initServiceConnection();
startService(new Intent(this, com.mobile.connect.service.PWConnectService.class));
bindService(new Intent(this, com.mobile.connect.service.PWConnectService.class),
_serviceConnection, Context.BIND_AUTO_CREATE);
initView();
setListener();
}
private void showDialog(String str) {
closeDialog();
waitDlg = DialogUtil.loadingDlg(this, str);
}
private void closeDialog() {
if (waitDlg != null && !this.isFinishing()) {
waitDlg.cancel();
waitDlg = null;
}
}
private void initView() {
ry_btn_back = (RelativeLayout) findViewById(R.id.ry_btn_back);
ry_btn_next = (RelativeLayout) findViewById(R.id.ry_btn_next);
ry_btn_next.setVisibility(View.GONE);
tv_title = (TextView)findViewById(R.id.tv_title);
if (clickPayWay == visaPay) {
tv_title.setText(R.string.recharge_visa_pay);
} else if (clickPayWay == masterCardPay) {
tv_title.setText(R.string.recharge_mastercard_pay);
}
edt_name = (EditText) findViewById(R.id.edt_name);
edt_cardNumber = (EditText) findViewById(R.id.edt_cardNumber);
edt_cvvNumber = (EditText) findViewById(R.id.edt_cvvNumber);
edt_mm = (EditText) findViewById(R.id.edt_mm);
edt_yyyy = (EditText) findViewById(R.id.edt_yyyy);
edt_emailAddress = (EditText) findViewById(R.id.edt_emailAddress);
btn_submit= (TextView) findViewById(R.id.btn_submit);
tv_tips = (TextView) findViewById(R.id.tv_tips);
tv_tips.setText(getString(R.string.pay_charge_choose) + coinType.money + getString(R.string.dollar) + coinType.coinNum + getString(R.string.cointype));
}
private void setListener() {
btn_submit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!LocalUsers.isAleadyLogin()) {
ShowUtil.showToast(ProcessTransactionActivity.this, R.string.login_first);
return;
}
submitToAlipay();
}
});
}
private void initServiceConnection() {
_serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
_binder = (PWProviderBinder) service;
// we have a connection to the service
try {
_binder.initializeProvider(PWProviderMode.LIVE, APPLICATIONIDENTIFIER, PROFILETOKEN);
_binder.addTransactionListener(ProcessTransactionActivity.this);
} catch (PWException ee) {
setStatusText(getString(R.string.provider_not_init));
// error initializing the provider
ee.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
_binder = null;
}
};
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.activity_tokenization, menu);
return true;
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(_serviceConnection);
stopService(new Intent(this,
com.mobile.connect.service.PWConnectService.class));
}
@Override
public void creationAndRegistrationFailed(PWTransaction transaction,PWError error) {
this.transaction = transaction;
isOperating = false;
closeDialog();
String errorDetail = error.getErrorMessage();
if (errorDetail.contains("000.400.100")) {
errorDetail = "交易失敗,訂單進入風控系統,不會發生扣款,如果收到扣款短信,請以您的信用卡賬單為準,有問題聯系客服";
setStatusText(errorDetail +
"(errorcode:" + error.getErrorCode() +
",error:" + error.getErrorMessage() + ")");
} else {
setStatusText(getString(R.string.creationAndRegistrationFailed) +
",errorcode:" + error.getErrorCode() +
",error:" + error.getErrorMessage());
}
MyLog.e("TokenizationActivity",
error.getErrorMessage());
}
int isPro = 0;//0发起pa,1发起cp
@Override
public void creationAndRegistrationSucceeded(PWTransaction transaction) {
this.transaction = transaction;
isOperating = true;
closeDialog();
mHandler.sendEmptyMessage(101);
try {
if (isPro == 0) {
_binder.preauthorizeTransaction(transaction);
} else if (isPro == 1) {
_binder.captureTransaction(transaction);
}
} catch (PWException e) {
setStatusText(getString(R.string.transactionFailed));
e.printStackTrace();
}
}
@Override
public void transactionFailed(PWTransaction arg0, PWError error) {
this.transaction = arg0;
isOperating = false;
closeDialog();
setStatusText(getString(R.string.transactionFailed) +
",errorcode:" + error.getErrorCode() +
",error:" + error.getErrorMessage());
MyLog.e("TokenizationActivity", "isPro" + isPro +
error.getErrorMessage());
}
@Override
public void transactionSucceeded(PWTransaction transaction) {
this.transaction = transaction;
try {
if (isPro == 0) {
isOperating = true;
try {
_binder.checkTransactionStatus(transaction.getMobileIdentifier());
} catch (PWException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
_binder.createAndRegisterCaptureTransaction(paymentParams, transaction.getMobileIdentifier());
isPro = 1;
} else {
isOperating = false;
isPro = 0;
closeDialog();
setStatusText(getString(R.string.recharge_finish));
mHandler.sendEmptyMessage(102);
}
} catch (PWException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
switch(msg.what) {
case 100:
showDialog(getString(R.string.Preparing));
break;
case 101:
showDialog(getString(R.string.Processing));
break;
case 102:
ShowUtil.showToast(ProcessTransactionActivity.this, R.string.recharge_finish);
finish();
break;
}
}
};
private void submitToAlipay() {
if (coinType == null) {
return;
}
String holder = edt_name.getText().toString();
String cardnumber = edt_cardNumber.getText().toString();
String cvv = edt_cvvNumber.getText().toString();
String month = edt_mm.getText().toString();
String year = edt_yyyy.getText().toString();
String title = orderNum + "_安卓VISA";
if (clickPayWay == visaPay) {
title = orderNum + "_安卓VISA";
} else if (clickPayWay == masterCardPay) {
title = orderNum + "_安卓MASTER";
}
String emailAddress = edt_emailAddress.getText().toString();
if (emailAddress == null || emailAddress.length() <= 0 || !ToolUtil.isEmail(emailAddress)) {
setStatusText(getString(R.string.mail_type_wrong));
return;
}
try {
if (clickPayWay == visaPay) {
paymentParams = _binder.getPaymentParamsFactory()
.createCreditCardPaymentParams(coinType.money,
PWCurrency.US_DOLLAR, title, holder,
PWCreditCardType.VISA, cardnumber, year,
month, cvv);
} else if (clickPayWay == masterCardPay) {
paymentParams = _binder.getPaymentParamsFactory()
.createCreditCardPaymentParams(coinType.money,
PWCurrency.US_DOLLAR, title, holder,
PWCreditCardType.MASTERCARD, cardnumber, year,month, cvv);
}
if (paymentParams != null) {
paymentParams.addCriterion("CRITERION.ALIRISK_orderNo", orderNum+"");//订单号
paymentParams.addCriterion("CRITERION.ALIRISK_item1ItemProductName", "coins");//商品名称
paymentParams.addCriterion("CRITERION.ALIRISK_item1ItemQuantity", "1");//商品数量
paymentParams.addCriterion("CRITERION.ALIRISK_item1ItemUnitPrice", coinType.money*100 + "");//商品单价
paymentParams.addCriterion("CRITERION.ALIRISK_item1ItemUnitPriceCurrency", "US_DOLLAR");//币种
paymentParams.addCriterion("CRITERION.ALIRISK_txnAmount", coinType.money*100 + "");//订单总金额
paymentParams.addCriterion("CRITERION.ALIRISK_txnCurrency", "US_DOLLAR");//订单总金额币种
paymentParams.addCriterion("CRITERION.ALIRISK_billToEmail", emailAddress);//账单邮箱地址
paymentParams.setCustomIdentifier(orderNum+""); //customid
if (clientIPAddress != null && clientIPAddress.length() > 0) {
paymentParams.addCriterion("CRITERION.ALIRISK_clientIP", clientIPAddress);//客户端的ip地址
}
}
} catch (PWProviderNotInitializedException e) {
setStatusText(getString(R.string.provider_not_init));
e.printStackTrace();
return;
} catch (PWException e) {
int errorCode = e.getError().getErrorCode();
int str = R.string.invalid_parameters;
if (errorCode == 1111) { //卡号填写有误
str = R.string.invalid_parameters_accountname;
} else if (errorCode == 1112) { //持卡人姓名填写有误
str = R.string.invalid_parameters_username;
} else if (errorCode == 1122) { //到期月份填写有误
str = R.string.invalid_parameters_mm;
} else if (errorCode == 1123) { //到期年份填写有误
str = R.string.invalid_parameters_yyyy;
} else if (errorCode == 1124) { //cvv填写错误
str = R.string.invalid_parameters_cvv;
}
setStatusText(getString(str));
e.printStackTrace();
return;
}
ToolUtil.closeKeyBoard(ProcessTransactionActivity.this);
setStatusText("");
mHandler.sendEmptyMessage(100);
try {
//发起pa
_binder.createAndRegisterPreauthorizationTransaction(paymentParams);
} catch (PWException e) {
setStatusText(getString(R.string.cant_contact_gateway));
e.printStackTrace();
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if ((keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)) {
if (isOperating) {
ShowUtil.showToast(ProcessTransactionActivity.this, R.string.Processing_notClose);
}
finish();
}
}
return super.onKeyDown(keyCode, event);
}
下面讲讲服务端的处理的时候注意事项(.net)
服务端测试的通知回调地址是:
服务端正式的通知回调地址是:
服务端需要有ssl证书的,我测试的时候没有ssl证书,有时候会出现因为这个失败
下面是我们服务端的主要代码
/// <summary>
/// 验证外卡支付订单并给予充值金币
/// </summary>
/// <param name="customIdentifier">自己系统的订单Id</param>
/// <param name="identifier">EventId</param>
/// <param name="tid">transactionId</param>
public static void NewMethod(string customIdentifier, string identifier, string tid)
{
if (!string.IsNullOrWhiteSpace(identifier) && !string.IsNullOrWhiteSpace(tid))
{
LogHelper.Record("Mpymnt==>identifier:" + identifier + ",,,,tid:" + tid);
string url = "" + identifier;//正式的验证地址
string heads = "payworks-apiIdentifier apiIdentifier=" + MpymntConfig.APIIdentifier + ",apiSecretKey=" + MpymntConfig.Key; //MpymntConfig.APIIdentifier和MpymntConfig.Key需要支付宝配置的
string Trade_no = identifier + "," + tid;
var info = HttpGetMpy(url, "", heads, "yanzheng", int.Parse(customIdentifier), Trade_no);
LogHelper.Record("Mpymnt==>去验证获得==>info:" + info);
if (!string.IsNullOrWhiteSpace(info))
{
MpymntCheckModel infomodel = HttpUtil.ParseJson<MpymntCheckModel>(info);
if (infomodel != null)
{
string out_trade_no = customIdentifier;
decimal total_fee = infomodel.data.transaction.amount; //订单金额
//如果是成功的时候,去加金币
if (infomodel.status == "ok" && infomodel.data.transaction.transactionType.ToLower() == "cp")
{
// LogHelper.Record("Mpymnt==>subject:" + subject + ",,out_trade_no:" + out_trade_no + ",,total_fee:" + total_fee);
var row = OrdersBll.Da.UpdateState(int.Parse(out_trade_no), "订单完成", (int)OrdersStatecDescType.SuccessOrder, Trade_no);
if (row > 0) //成功更改表 状态 step=2
{
Core.LogResult("【外卡支付】【时间:】" + DateTime.Now.ToString() + "【交易金额:】" + total_fee + "【订单编号:】" + out_trade_no + ",外卡订单号:【" + tid + "】EventId:" + identifier + "【备注:】--交易成功--");
}
else
{
if (row == -25)
{重复");
}
else
{成功 ,给用户加币失败");
OrdersBll.Da.UpdateState(int.Parse(out_trade_no), "支付成功,加币失败", (int)OrdersStatecDescType.AddCoinError, Trade_no);
}
}
} + ",交易状态:【" + infomodel.status + "】 infomodel.status:" + infomodel.status + ",,transactionType(CP才加):" + infomodel.data.transaction.transactionType.ToLower());
// RefundOrders(int.Parse(out_trade_no), tid);
}
} + " --外卡验证请求链接返回格式Info为Json,Model为NULL。");
OrdersBll.Da.UpdateState(int.Parse(customIdentifier), "外卡验证请求格式Json为NULL", (int)OrdersStatecDescType.CheckMpymntError, Trade_no);
}
}
else
{
LogHelper.Record("Mpymnt==>验证identifier返回的信息空。");
}
}
else
{
LogHelper.Record("Mpymnt==>POST过来的Json解析值为空。identifier:" + identifier + ",,,,tid:" + tid);
}
}
VISA Glossary2011-08-19 17:54:32: Visa Transaction Processing Network. V.I.P : VisaNet Integrited Payment System. SMS : Single Message System. DMS : Dual Message System. STIP : stand in process(代授权) Acquirer :收单行...
VisaNet : Visa Transaction Processing Network.
V.I.P : VisaNet Integrited Payment System.
SMS : Single Message System.
DMS : Dual Message System.
STIP : stand in process(代授权)
Acquirer :收单行
Issurer :发卡行
On Us :Acquirer=Issurer
Not On Us( informay called Off Us) :Acquirer != Issurer
PIN :Personal Identification Number (密码)
BIN : Bank Identification Number
PAN : Primary Account Number
VIFD : Visa Issuer Fraud Detection
FRS :Fraud Reporting System
PVS :PIN Verification Service
Auto-CDB :Automatic Cardholder Database Update
DKE : Dynamic Key Exchange
WK : Working Key
AZK : Acquirer Working Key
IZK : Issurer Working Key
ZCMK :Zone Control Master Key
KEK : Key Exchange Key
AKEK :Acquirer Key Exchange Key
IKEK : Issurer Key Exchange Key
KSK : Key Storage Key
MacKey : Message Authentication Code Key
VSDC :Visa Smart Debit/Smart Credit
CORE :Customer Online Repository
Reconciliation :对账
Clearing :结算
Settlement :交割
HSM :Hardware security module
DUKPT :Derived unique key per transaction
PED :PIN entry device
TRSM :Tamper resistant/responsive security module
MK/SK :Master key / session key
POS : Point of Sale / Point of Service
Chinese students in the US: Taking a stand @Nature2019-07-14 16:54:45Between 1985 and 2000, some 26,500 Chinese students earned science and engineering PhDs in the United States — more than double the number of students from all of Western Europe, according to the ...
[转载]2017 中国电信(美洲)公司CTExcel US电话卡使用攻略_拔剑-浆糊的传说_新浪博客2018-12-26 11:02:23原文地址:2017中国电信(美洲)公司CTExcelUS电话卡使用攻略作者:zhshzh521 中国电信(美洲)公司CTExcel US电话卡使用攻略 2017-9-21 中国电信(美洲)公司为一家中/美通讯运营商,在美国...
first season eighteenth episode,let us play poker!!!2020-07-10 21:23:54Phoebe: (reading): Your Visa bill is huge! Rachel: (grabs the bill) Give me that! (Camera cuts to Chandler and Ross at table.) Chandler: You know, I can't believe you. Linda is so great! Why won't ...
mastercard 接口_万事达卡(MasterCard)和维萨(Visa)取消了广受欢迎的付款验证计划...2020-08-11 05:11:11mastercard 接口MasterCard SecureCode and Verified by Visa; they’re names synonymous with ecommerce and if you’ve ever purchased something online using either a Visa card or a MasterCard then the ...
iOS提交应用至App Store流程2015-10-14 11:33:32... 1 准备材料 ...@"***-***-***/id *******?ls=1&mt=8" ]; [[ UIApplication sharedApplication ] openURL :url]; } }
Guidance for Students in Applying for a UK Visa2007-03-02 22:58:00we will not normally refuse you entry to the UK unless your circumstances have changed, or you gave false information or did not tell us important facts when you applied for your visa. When you ...
Python库——Faker2019-10-16 20:52:07en_US - English (United States) es_ES - Spanish (Spain) es_MX - Spanish (Mexico) et_EE - Estonian fa_IR - Persian (Iran) fi_FI - Finnish fr_FR - French hi_IN - Hindi hr_HR - Croatian hu_HU - Hungarian...
【数据集】计算机视觉,深度学习,数据挖掘数据集整理2018-04-04 10:46:093)Number of images with bounding box annotations: 1,034,908 4)Number of synsets with SIFT features: 1000 5)Number of images with SIFT features: 1.2 million Imagenet数据集是目前深度学习图像领域应用...
陈正康考研英语长难句 51~752020-11-21 20:01:32【DAY57】In the wake of September 11, changes in the visa process caused a dramatic decline in the number of foreign students seeking admission to U.S. universities, and a corresponding surge in ...
paypal nvp name value paire paypal ecshop sanbox测试账号2015-09-17 15:36:42那个是微信里面用的 ...VISA Expiration Date: 10/2020 PayPal Balance: 9999.00 USD 4 NVP NVP SOAP SOAP NVP NVP SOAP SOAP 接口地址 ...
校验为空不为空 公共类2017-04-05 15:49:00public static final String isSignedIntegerMsg = "The Number must be a valid signed whole decimal number."; public static final String isLongMsg = "The Number must be a valid unsigned whole decimal ...
Foreign Applications To US Graduate Schools Slow2009-04-10 00:50:252008-10-13 The number of Chinese and Middle Eastern students applying for fall admission to U.S. graduate programs surged, while applications from India and South Korea fell, according to a survey to...
ART运行时Foreground GC和Background GC切换过程分析2015-05-04 00:57:34通过前面一系列文章的学习,我们知道了ART运行时既支持Mark-Sweep GC,又支持Compacting GC。其中,Mark-Sweep GC执行效率更高,但是存在内存碎片问题;而Compacting GC执行效率较低,但是不存在内存碎片问题。...
Cover Letter实用指南2012-03-27 08:44:07The poster number of my paper is 007. I found the 'OFFICIAL ACCEPTANCE LETTER' you sent to me was lack of your signature. I'm afraid this would cause some trouble when I go to the embassy for my ...
- So unless you are a bank or large vendorthat deals with a high volume of transaction this is not going to be an option.For most of us a Gateway provider is not optional. FrontEnd Network The ...
- Mr Bennett explained: "Since all embassies have to use the 6532 telephone prefix and the number of lines is limited, the US embassy is only allotted two lines for our appointment system. Insgroupsto ...
此交易无法处理。 请输入有效的信用卡号码并输入2014-09-22 13:00:49<p>I have entered correct Visa card number, Exp. date, and Correct US address with correct zip code. <p>I have check this error on paypal. Its showing me <code>Invalid Data</code>. <p>I am using ...
Expo大作战(三十一)--expo sdk api之Payments(expo中的支付),翻译这篇文章傻逼了,完全不符合国内用户,我...2019-09-26 22:08:01简要:本系列文章讲会对expo进行全面的介绍,本人从2017年6月份接触expo以来,对expo的研究断断续续,一路走来将近10个月,废话不多说,接下来你看到内容,讲...country String - 地址的ISO国家代码(例如“US...
freelance平台_完整的Freelance Web开发人员指南:如何通过Freelance编程工作来赚钱2020-08-14 10:17:23freelance平台It’s common for developers to go the freelance route. This is true for many who have just finished freeCodeCamp and are thinking of working for themselves as opposed to working for “the...
Braintree-国外支付对接(三) 之Customer UI2018-03-22 14:03:30#card-image.visa { background-position: 0 -398px; } #card-image.master-card { background-position: 0 -281px; } #card-image.american-express { background-position: 0 -370px; } #card-...
Different 3DS and OTP(一次密碼)2021-06-08 18:36:443D Secure is a FREE service facilitated by VISA and MasterCard that lets you transact online securely using your Debit or Credit Card. This service is available only on 3D Secure merchant sites. ...
- ...
苹果开发者账号购买或续费支付表单填写全记录purchase form2014-05-24 21:34:35...
编程是可能用到的 一些英文词的标准缩写2016-12-06 08:46:16A number of people or things that have been "counted", such as inventory cycle count Country CTRY County CNTY Course* CRSE* Coverage* ...
如何在sqlserver可空列中创建唯一约束,但是允许多个null值2018-05-31 14:58:01However, in situations of people entering this country using a work visa, it would take sometime for them to get a social security number. Until that time, the data would be NULL. Now let us try to ...
外国人申请居留许可服务指南(中英文)2013-09-29 16:49:16申请就业及随行家属类居留许可 一、申请的条件: 在郑就业的外国人及随行家属。 二、申请时须回答有关询问并提供下列材料 (一)本人有效护照及签证的原件和复印件;...(二)填写《外国人签证、居留许可申请表》;...
空空如也
空空如也 | https://www.csdn.net/tags/MtjaMg4sNTM3NzctYmxvZwO0O0OO0O0O.html | CC-MAIN-2021-49 | refinedweb | 20,673 | 79.67 |
Moving .NET libraries to .NET Core
Jürgen Gutsch - 20 November, 2015
At the MVP Summit 2015 Albert Weinert.
Currently I'm working at LightCore to make it compatible to .NET Core, to make the world a little better ;) Hopefully. This needs some steps to do. More details are in a separate blog post about LightCore 2.0. Because the unit tests of LightCore don't use mocking tools this was easier than expected.
With this post I want to tell you, what you need to do to move your library to .NET Core. I will use the 'Simple Object Store' to make a step by step tutorial. At the end my open source library will be compatible with .NET Core :)
But why should I do this? Is this future proof? Does the effort make sense?.
The current state of the Simple Object Store.)
That means I have four projects for the SimpleObjectStore and the same number of projects for the AzureStorageProviders. And I have two test projects, one for the main library and one for the providers library.
The goal is to have four different libraries instead of 10.
Step 1: Convert the main library.
Step 2: Convert the providers library)
Step 3: Converting the unit test projects
Currently I'm using NUnit to test the SimpleObjectStore. I need to decide whether to change to Xunit or to use the new NUnit 3.0.0 portable build..
"commands": { "test": "nunit.runner.dnx" }
(I use the NUnit namespace because I want to contribute this runner to the NUnit project. I use it here as a kind of dog-fooding to test the runner.).
Step 4: Add a CI server
To get this compiled and published I also use AppVeyor as a favorite CI server i the same way as written in the last post about Building LightCore 2.0
Final words? ;)
A pretty detailed tutorial about how to move libraries to DNX was written by Marc Gravell: | https://asp.net-hacker.rocks/2015/11/20/move-libraries-to-net-core.html | CC-MAIN-2021-49 | refinedweb | 326 | 84.98 |
#include <hallo.h> * Hunter Peress [Sun, Dec 22 2002, 07:14:42AM]: > > > He? You do not need additional space for having two versions? > this is that since i686 has been around for a good few years, most users > will choose it over i386 (thats pentium pro all the way on up to today A good majority will choose 686, another one K6/K7, etc., and lots will still need Debian for 486er boxes. > and for new chips at least 1-2 years still) and that covers a LOT of > people. So would that people pay for having optimised versions? Oh, and please top using a broken MUA. I mean something that does not manage to recognise mailing lists, to keep the references and sends two different messages. Gruss/Regards, Eduard. -- The early bird gets the worm. If you want something else for breakfast, get up later. | https://lists.debian.org/debian-devel/2002/12/msg01372.html | CC-MAIN-2015-40 | refinedweb | 146 | 82.65 |
Original link: The article wrote it myself, only in their own independent javaeye blog and blog. Welcome reproduced, thank acknowledgment. ubuntu 8.04 LTS 64-bit systems nginx + mysql + php5-fpm + wordpress de
Transfer from my ChinaUnix this blog: 2009-12-02 Ubuntu generally two ways to install wine, source compile or install from a network source. Relatively stable source compile and install, fast,
1) Download ubuntu, I will use rookie rookie version. . Download: In the VMware install. . . The next step the next step, quite simply goes without saying. 2) To search subversion (mave
Because a friend asked me this question, so I practice what to write down. 1, in the top of the other computer with internet access to download emacs: wget-c
1. Install ree Visit the official website ree Download the latest version found, and then use wget to just download the directory: wget
Download Source: The following were introduced in the Mac, Ubuntu, Centos and Windows install Node.js. -------------------------------- Mac In the Mac, if you prefer to use homebrew, then only one line can be installed Students used a list deb lucid main restricted universe multiverse deb lucid-security main restricted universe multiverse deb
In order to change the boot sequence, like in ubuntu The following check method, there is no input , Called a difficult ah ! Contempt SCIM, so loading fcitx. But on the page can cloud Sogou input method, the reaction is quite slow , But still good fr
Case configure: error: libjpeg. (A | so) not found. Solve 2011-08-06 08:45:01 | Category: Web | font subscription original works, for permission to reproduce, reprint, please be sure to indicate the form of hyperlinks original source of article, auth
接上篇,上篇仅安装了Mono本身,并没有安装libgdiplus.gtk-sharp.mod_mono.MonoDevelop 等其他相关的软件. 这篇主要是配置安装libgdiplus. 准备工作 先在VS2012上编译一个winform,代码如下: using System; using System.Windows.Forms; namespace FormsTest { static class Program { /// <summary> /// 应用程序的主入口点. /// &l
因为有朋友问我这个问题,所以我就实践一下,写了下来. 1, 在其它能上网的电脑上面下载 emacs : view plain copy to clipboard print ? wget -c 82% [===============================> ] 38,794,237 438K/s
今晚在公司值班,就想着试试装一下php,之前ubuntu装在移动硬盘上直接启动就是了.之前也有装过一个apache给svn用,但发现源码装php相当麻烦,就偷懒一下,直接apt-get,真是简单方便啊! 119 apt-get install mysql-server mysql-client 120 apt-get install nginx 121 /etc/init.d/nginx start 122 apt-get install php5-fpm 注 ubuntu10.04 官方没有p
公司原来的Mantis在个人的机器上,现在购置了服务器,迁移到Linux系统中,以下是手记 1.MySQL安装配置 1.1.安装 $sudo apt-get install mysql-server 1.2.配置 $mysql -uroot -p 输入root密码 建立用户 mysql>create user 'mantis'@'localhost' identified by 'mantis'; 建表 mysql>create database mantis default characte
1.Nginx("engine x") 是一个高性能的 HTTP 和反向代理服务器,也是一个 IMAP/POP3/SMTP 代理服务器 2.本文实现Ubuntu下源码编译安装 Nginx-1.1.10+PHP5.2.13+fastfpm+Mysql5.5+eaccelerator (之所以选择PHP 5.2的版本主要一是因为跟张宴大师学习,二是fast-fpm在php5.2还是分开的,在php5.3已经集成捆绑到php中了,先单独安装熟悉下) 3.对安装过程中遇到的"坑&qu
最近搞了下分布式PB级别的存储CEPH 尝试了几种不同的安装,使用 期间遇到很多问题,和大家一起分享. 一.源码安装 说明:源码安装可以了解到系统各个组件, 但是安装过程也是很费劲的,主要是依赖包太多. 当时尝试了centos 和 ubuntu 上安装,都是可以安装好的. 1下载ceph wget 2 安装编译工具apt-get install automake
ubuntu fedora linux netbeans 6.8 openjdk Chinese garbled solution: This problem belongs to OpenJDK Chinese font configuration errors. 1, view their own use of the JVM, I'm using / usr / lib / jvm / java 2, enter the directory / usr / lib / jvm / java
Ubuntu 8.10 installed when the Chinese version of NetBeans 6.5, the Chinese turned into a small box full! This is a result of a small Chinese characters, which require Chinese font support. The Internet to find a solution together to share! A very si
First, install: $ Sudo apt-get install im-switch libapt-pkg-perl fcitx If you need to uninstall the SCIM input method that comes with ubuntu $ Sudo apt-get remove scim Second, set to the default input method: $ Im-switch-s fcitx (if you want to set t
1. To the official website RAR download rar for linux 2. Unzip, modify makefile file prefix = / usr / local / RAR, and then run the command line: sudo make install 3. To establish the soft link: sudo ln-s / usr / lo
WinXP poisoning recently, and then upgrade experience under Windows7, download the good the Win7's Chinese Professional installation files, 2.3 G, were found to the hard disk installation, Bahrain, and found the Ubuntu 9.1 prior to the start menu was
Ubuntu installation on NFS configuration NFS Linux host to access the network for other shared resources on a Linux host. NFS is the principle client remote host via a network shared file system to mount (Mount) way to add the native file system, the
Reprinted: 1, sysv-rc-conf Introduction sysv-rc-conf is a powerful service management procedures, opinions of the masses is the sysv-rc-conf easy to use than chkconfig. Second, background kn
ubuntu dpkg-L xxx look under the application installation path
Under the winxp virtual ubuntu, the ubuntu to access shared folder win the following error: / Sbin / mount.vboxsf: mounting failed with the error: No such device 1, To use the shared folders feature, you must install linux guest additions 2, lsmod |
First of all, from download jdk, my version is jdk1.6.0_12, I downloaded the bin file, I put the downloaded jdk1.6.0_12.bin file / usr / lib / jvm / java in the Then, in the shell to execute: Code: sudo chmod u + x / usr/lib/jvm/j
Command-line multi-threaded HTTP download tool-axel parameter description: deepfuture @ Server-deepfuture1: ~ $ Axel - H Usage: axel [options] url1 [url2] [url ...] - Max-speed = x-sx Specify maximum speed (bytes per second) - Num-connections = x-nx
Example to find the path to JDK 1, use find, can be found in the output list / usr/lib/jvm/java-6-sun-1.6.0.14 Find such a format commonly used to find the directory to start looking for the file-name To start looking for the following directory is /
1. Installation jdk6 shell>sudo apt-get install sun-java6-jdk( With the new legislation package installation ) 2. Download tomcat6 The download address is : This installation is :apache-tomcat-6.0.18.tar.gz 3. Installation Co
First, install the download jamesAMES mail server JAMES mail server under UBUNTU Download file james-binary-2.3.1.tar.gz Extract tar zxvf james-binary-2.3.1.tar.gz mv james-2.3.1 / usr / local / Authorize chmod + x run.sh chmod + x phoenix.sh Run . /
Ubuntu software installation and remove the associated command to install the software command: apt-get install softname1 softname2 softname3 ... ... Uninstall the software command: apt-get remove softname1 softname2 softname3 ... ... Remove and purg
After installing ubuntu server version, the default is not without installing any graphical desktop systems, need to manually install and configure. In text mode, you can use nano, vi novice difficult to adapt. For convenience, you can activate the r
See: sudo apt-get install make gcc g + + Reloading manual function sudo apt-get install manpages-dev Another method: sudo apt-get install build-essential After the impleme
CodeWeblog.com 版权所有 黔ICP备15002463号-1
processed in 0.038 (s). 8 q(s) | http://www.codeweblog.com/stag/ubuntu-libjpeg-devel/ | CC-MAIN-2016-07 | refinedweb | 1,141 | 55.44 |
so my project is due tomarrow and im stuck i need to some help. This is what i have it came up with some errors and i need to finish it. The conditions are TOTAL BALANCE and need to withdraw only multipule of 20
// This is a program that is an ATM. #include <iostream> #include <cstdlib> #include <iomanip> using namespace std; // These are function prototypes void welcome(); void menu(); double amountDeposit (); void amountWithdrawal(); double finalBalance (); void exit(); // This the main function that will operate all other funtions. int main () { char choice; double deposit,totalBalance; welcome(); do { menu(); cin >> choice; while (choice < 'A' || choice > 'C') { cout << " Please make a choice in the range"; cout << " of A through C:"; cin >> choice; } switch (choice) { case 'a' : case 'A' : exit(); break; case 'b' : case 'B' : amountDeposit(); cout << "You deposited $ " << amountDeposit() << "." << finalBalance () << "." << endl; break; case 'c' : case 'C' : amountWithdrawal(); break; } } while ( choice != 'A'); return 0; } // Function is the welcome menu. void welcome() { cout << "- - - - - - - - - - - - - - - - - - -" << endl; cout << "- Welcome to DDJ'S ATM Servies -" << endl; cout << "- Please follow the instructions -" << endl; cout << "- to access you account -" << endl; cout << "- - - - - - - - - - - - - - - - - - -" << endl; system ("PAUSE"); system ("cls"); } // Function is the welcome Main menu that gives you the choices. void menu() { cout << "What would you like to do?" << endl; cout << "A. Exit the program" << endl; cout << "B. Make a deposit" << endl; cout << "C. Make a withdrawal" << endl; } // Function will run the deposits. double amountDeposit(double deposit) { cout << "How much would you like to deposit? $"; cin >> deposit; if ( deposit >=1000) { cout << "Only able Deposit Maximum of $1000.00 Try Again" << endl; cin >> deposit; } return (deposit); system ("PAUSE"); system ("cls"); } // Function will run the withdrawals. void amountWithdrawal() { double withdrawal; cout << "How much would you like to withdrawal? $"; cin >> withdrawal; if ( withdrawal >=500) { cout << "Only able withdrawal Maximum of $500.00. Try Again" << endl; cin >> withdrawal; } if ( withdrawal= withdrawal % 20) { cout << "Withdrawal Must be a multiple of $20. Try Again" << endl; cin >> withdrawal; } system ("PAUSE"); system ("cls"); } double finalBalance (double totalBalance) { double balance = 800, totalbalance; totalBalance = balance + amountDeposit(); return (totalbalance); } // This is the exit funtion void exit () { cout << "Please come again.\n"; } | https://www.daniweb.com/programming/software-development/threads/277291/atm-machine-due-tomarrow | CC-MAIN-2017-09 | refinedweb | 346 | 62.68 |
Atsushi Nemoto wrote:
+static void tx4939ide_check_error_ints(ide_hwif_t *hwif, u16 stat)
+{
+ if (stat & TX4939IDE_INT_BUSERR) {
+ unsigned long base = TX4939IDE_BASE(hwif);
+ /* reset FIFO */
+ TX4939IDE_writew(TX4939IDE_readw(base, Sys_Ctl) |
+ 0x4000,
+ base, Sys_Ctl);
Are you sure bit 14 is self-clearing? The datashhet doesn't seem to
say that...
Well, I cannot remember... I thought I checked that bit cleard by
reading it, but actually the bit is write-only. Maybe clearing
explicitly would be a safe bet.
+ rc = __tx4939ide_dma_setup(drive);
+ if (rc == 0) {
+ /* Number of sectors to transfer. */
+ nframes = 0;
+ for (i = 0; i < hwif->sg_nents; i++)
+ nframes += sg_dma_len(&hwif->sg_table[i]);
+ BUG_ON(nframes % sect_size != 0);
+ nframes /= sect_size;
+ BUG_ON(nframes == 0);
+ TX4939IDE_writew(nframes, base, Sec_Cnt);
Ugh, it looks much easier in my TC86C001 driver... doesn't
hwgroup->rq->nr_sectors give you a number of 512 sectors?
Why bother with other (multiple of 512) sizes when you can always
program transfer in 512-byte sectors? Or was I wrong there?
Hmm. Good idea. I will try it.
At least it worked with a CD-ROM for me. :-)
+static int tx4939ide_dma_end(ide_drive_t *drive)
+{
+ if ((dma_stat & 7) == 0 &&
+ (ctl & (TX4939IDE_INT_XFEREND | TX4939IDE_INT_HOST)) ==
+ (TX4939IDE_INT_XFEREND | TX4939IDE_INT_HOST))
+ /* INT_IDE lost... bug? */
+ return 0;
You shouldn't fake the BMDMA interrupt. If it's not there, it's not
there. Or does this actually happen?
IIRC, Yes.
Hum, let me think... worth printing a message if this happens.
+ /*
+ * If only one of XFERINT and HOST was asserted, mask
+ * this interrupt and wait for an another one. Note
This comment somewhat contradicts the code which returns 1 if only
HOST interupt is asserted if ERR is set.
Indeed. I will make the comment more precise.
+ case TX4939IDE_INT_HOST | TX4939IDE_INT_XFEREND:
+ dma_stat = TX4939IDE_readb(base, DMA_stat);
+ if (!(dma_stat & 4))
+ pr_debug("%s: weired interrupt status. "
+ case TX4939IDE_INT_HOST | TX4939IDE_INT_XFEREND:
+ dma_stat = TX4939IDE_readb(base, DMA_stat);
+ if (!(dma_stat & 4))
+ pr_debug("%s: weired interrupt status. "
Weird.
Sure. But it can happen IIRC...
I meant the typo. :-)
#ifdef __BIG_ENDIAN
+/* custom iops (independent from SWAP_IO_SPACE) */
+static u8 mm_inb(unsigned long port)
+{
+ return (u8)readb((void __iomem *)port);
+}
+static void mm_outb(u8 value, unsigned long port)
+{
+ writeb(value, (void __iomem *)port);
+}
+static void mm_tf_load(ide_drive_t *drive, ide_task_t *task)
+{
#ifdef __BIG_ENDIAN
+/* custom iops (independent from SWAP_IO_SPACE) */
+{
+ return (u8)readb((void __iomem *)port);
+}
+static void mm_outb(u8 value, unsigned long port)
+{
+ writeb(value, (void __iomem *)port);
+}
+static void mm_tf_load(ide_drive_t *drive, ide_task_t *task)
+{
[...]
+ if (task->tf_flags & IDE_TFLAG_OUT_DEVICE) {
+ unsigned long base = TX4939IDE_BASE(hwif);
+ mm_outb((tf->device & HIHI) | drive->select,
+ io_ports->device_addr);
I'm seeing no sense in re-defining so far...
+ /* Fix ATA100 CORE System Control Register */
+ TX4939IDE_writew(TX4939IDE_readw(base, Sys_Ctl) & 0x07f0,
+ base, Sys_Ctl);
Ah... you're doing it here (but not in LE mode?). I think to avoid
duplicating ide_tf_load() you need ot use selectproc().
Oh, my fault. LE mode also needs this fix. I still need ide_tf_load
on BE mode to support IDE_TFLAG_OUT_DATA.
Yeah, that totally useless flag...
+static void mm_insw_swap(unsigned long port, void *addr, u32 count)
+{
+ unsigned short *ptr = addr;
+ unsigned long size = count * 2;
+ port &= ~1;
+ while (count--)
+ *ptr++ = le16_to_cpu(__raw_readw((void __iomem *)port));
+ _...
+static const struct ide_tp_ops tx4939ide_tp_ops = {
+ .exec_command = ide_exec_command,
+ .read_status = ide_read_status,
+ .read_altstatus = ide_read_altstatus,
+ .read_sff_dma_status = tx4939ide_read_sff_dma_status,
Hum, it should be re-defined in both LE and BE mode (but actually not
called anyway).
What do you mean? Please elaborate?
MBR, Sergei | http://www.linux-mips.org/archives/linux-mips/2008-09/msg00076.html | CC-MAIN-2015-18 | refinedweb | 537 | 59.5 |
Smart card risks and rewards
Despite all this, I'm a big believer in smart cards.
Smart cards are better authenticators than passwords. They're two-factor (which defeats some attacks), they're easier to work with than long and complex passwords, and the underlying representative hash is usually formed from a very long and complex password (which prevents cracking). In general, smart card users are more knowledgeable about computer security risks.
But don't give smart cards more protection than they've earned. As with any computer security mechanism, there are trade-offs. Smart cards aren't accepted by every application and can't be used on every computer or computing device. They're also expensive to implement and maintain. I haven't looked at the latest figures, but in the recent past I've read that every lost or broken smart card costs about $70 to $80 to replace (including support and physical expenses).
You can also blame smart cards for unique attacks. As an example, most smart cards are tied to a user's email address or perhaps logon name. An attacker can often change their email address, logon name, or universal principal name (UPN) in the underlying namespace (DNS, Active Directory, and so on) and "become" that person to the authenticating operating system.
If I were an insider with the appropriate permissions, I'd change my UPN to match an innocent person's UPN (you'd have to change that person's UPN temporarily). Then, when I logged on using my own smart card and PIN, the underlying namespace would see my smart card as successfully attesting to someone else's identity. I could then wreak havoc using that identity. The security logs would attribute all the ensuing events to the innocent user, and after I've done all my damage, I could change everything back. Nobody, including the innocent user, would suspect a thing. It could be the perfect crime.
To do the same using a traditional username and password, the villain (in most authentication systems) would have to reset the user's password in order to steal their identity. Then the original user would know something is up because their original password would no longer be recognized. In this particular (rare and extreme) scenario, a simple username and password actually has benefits over a smart card.
That's why I always tell enterprises using smart cards to strictly limit and audit who can change the identity attributes of smart card users. In some environments, a ton of people can do that, and each one is a risk.
What works better?
What's more effective at preventing attacks than two-factor authentication? Almost everything else. I always tell clients to start by analyzing how they were successfully compromised (usually either poor patching or social engineering), then implement solutions that directly address the attack vectors.
If you do your homework, you'll see that smart cards are good, but not great defenders of the enterprise. Nearly everything I've said here applies to most other forms of two-factor authentication. They have their pluses and minuses. If you're involved in a similar project, don't let anyone oversell the solution.
This story, "Don't put all your faith in smart cards," was originally published at InfoWorld.com. Keep up on the latest developments in network security and read more of Roger Grimes' Security Adviser blog at InfoWorld.com. For the latest business technology news, follow InfoWorld.com on Twitter. | http://www.infoworld.com/article/2612812/security/don-t-put-all-your-faith-in-smart-cards.html?page=2 | CC-MAIN-2016-30 | refinedweb | 584 | 55.44 |
Write a poem about code
Ben Halpern
・1 min read
I’m waiting...
Classic DEV Post from Apr 29
Please compile, please compile,
It would surely make me smile,
When I glance at the clock,
And thirty minutes has gone by non-stop,
I think that I've won, that I've beaten the odds,
But alas it is not the day, says the evil programming gods,
As this is all a ruse, just one big long deception,
Since my terminal froze ten minutes ago, from an UndefinedException
This is lame but try it on Language CLI.
Code, oh code,
is this string a float?
Let me write a method to check,
with numerous errors the compiler reports back!
What the heck did I wrong?
Give me a hint, at least a little one!
After searching half the day,
I got it fixed - hurray!
Brought up during my daily retrospective,
in the future, I have to be more perceptive!
Originally posted on my blog: jonasws.github.io/2016/04/02/pytho...
Midway upon the journey of our debugging
I found myself within an exception,
For the straightforward console.log had not been working.
Ah me! how hard a thing it is to say
What was this session, long, exhausting, and unproductive,
Which in the very thought renews the headache.
So bitter is it, kernel panic is little more;
But of the good to treat, which there I found,
Speak will I of the bugfix I wrote there.
I cannot well repeat how there I entered,
So full was I of linting errors at the moment
In which I had abandoned the right way.
But after I had reached a stack’s trace,
At that point where the stderr terminated,
Which had with consternation pierced my shell,
Upward I scrolled, and I beheld its cursor,
Vested already with that red flags,
Which leadeth others right by every log.
PS: This is Dante’s Inferno
As listed on xpbytes.com/404, written in 2015
Bits. And pieces.
Bits. Bits and pieces. Bits and Bytes. I see the spinner whilst it compiles. Waiting. Chunks of code. Bits and pieces. My mind reduced to machinery; logic; harsh, rude and singular truth.
I type. I save. I press the button. I watch the spinner.
Code lights up as exceptions are thrown. Thrown exceptions, breaking the code in bits and pieces. Like a CPU, my mind goes into overdrive, heating up ever so slightly. Where did I go wrong, what did I do wrong. I think, I linger.
I type. I save. I press the button. I watch the spinner.
“It works for me”, “Not enough information”, “By Design”. Writing on the interwebs can only answer my lingering questions so much. Piece by piece I will find the solution and write the code, from mind to machinery.
I type. I save. I want to press the button
My mind wanders and I am lost.
while (TRUE) {
if (happiness / 1 > π)
printf("me")
return free;
}
I didn't write this but I have to share it. Jo Pearce owned it jopearce.co.uk/poetry/aisforangular/. An angular poem
Code oh code
You should work
But you don't
You're a real mess
Oh, maybe that's the point?
I scaffolded it
I coded it
I refactored it
I tested it
I deployed it
I need a beer
Summertime code - a haiku.
Tranquil summertime
A snaking, squiggly code builds
despite the linter
git co -b feature-branch
git commit -m "some code"
git rebase master
error: could not apply 230d653...
answer == false
Error! Instruction is bad
def Try_Harder end | https://dev.to/ben/write-a-poem-about-code-on8 | CC-MAIN-2019-43 | refinedweb | 602 | 83.25 |
In this tutorial, we’ll create a simple movie-themed web app using Airtable and React. So, what are you waiting for? Let’s get started!
Table of Contents
- Introduction
- What Are We Making?
- Setting up the React App
- Scaffolding with Create React App
- Adding Bootstrap
- Importing Bootstrap
- Creating the Base Component
- Stubbing out the Base Component
- Creating the MovieCard Component
- Looping Through the Array
- Setting up Airtable
- Customizing the Airtable Base
- Accessing the Airtable Bases’ API
- Integrating React and Airtable
- Using our Airtable Data
- Wrapping up React and Airtable
Introduction
Before we begin, I’m sure some of you are wondering what Airtable is.
Airtable looks and feels like a spreadsheet, but it’s actually a database with an easy to use API that we can plug straight into our front-end with little effort.
Just like in Google Sheets how you add your data in rows and columns, Airtable also lets you add data in rows and columns. The user interface feels very familiar to Google sheets, making it very easy to understand and use by non-technical people.
If you’d like to read more about Airtable before we get started on our web app, you can check out their excellent getting started guide.
What Are We Making?
We’re keeping with the movie theme in this tutorial because I’m a huge fan of
I try to stick with the same tools and libraries in all of my web apps. Therefore, we’ll be using the following stack:
- React
- Bootstrap 4.1
- Airtable
That’s it! Just three ingredients for a delicious web app! Let’s open our text editors and terminals and begin, shall we? Oh, if you’re using Atom, be sure to check out the Best Atom Plugins for Front End Developers.
Setting up the React App
Our first task is to create a new React project. We could do this manually, but that would take too long. Instead, we’re using a tool the React team at Facebook have created called Create React App.
Scaffolding with Create React App
Go to the Create React App Github repository page and follow the instructions on setting up a new React project. Come back here when you have the base app up and running. It should look something like this:
Adding Bootstrap
Now that we have our React app working, our second task is to add Bootstrap to the codebase. For those who don’t know, Bootstrap is a component library which gives us well documented, styled HTML components such as buttons, cards, tabs, etc.
If you’re wondering what the difference between React and Bootstrap is, think of them within the context of a novel. React would be the spine and pages of the book, while Bootstrap would be the words, headings,
andimages.
There is a library called Reactstrap that has ‘
To install the latest Bootstrap, open up a terminal window, make sure you’re in the new React project directory, and run the following commands:
npm i bootstrap --save && npm i popper.js --save && npm i jquery --save
This command installs three libraries:
- Bootstrap.
- Popper.js, a bootstrap dependency that powers the tooltips and popover components.
- jQuery, another bootstrap dependency that Bootstrap relies on for animations, hiding and showing of elements, amongst other things.
If all goes well, you should see a console output that looks very similar to this:
+ bootstrap@4.1.3 added 1 package from 2 contributors in 18.516s [+] no known vulnerabilities found [35668 packages audited] npm WARN bootstrap@4.1.3 requires a peer of jquery@1.9.1 - 3 but none is installed. You must install peer dependencies yourself. + popper.js@1.14.5 added 1 package from 2 contributors in 16.791s [+] no known vulnerabilities found [35669 packages audited] + jquery@3.3.1 added 1 package from 1 contributor in 15.364s [+] no known vulnerabilities found [35670 packages audited]
Importing Bootstrap
You’re halfway there! Next, we need to actually import bootstrap into our React app so that we can begin using it.
We want Bootstrap to be accessible from anywhere in our code. Therefore, we should import it at the root of the application.
Open up index.js and add two new import statements for the Bootstrap CSS and JS files, towards the end of the existing imports:
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; // Import Bootstrap CSS and JS import 'bootstrap/dist/css/bootstrap.css'; import 'bootstrap/dist/js/bootstrap.js'; ReactDOM.render(<App />, document.getElementById('root')); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: serviceWorker.unregister();
Good stuff! Now, let’s make sure Bootstrap has been imported successfully. Open up App.js and add one line of HTML to insert a Bootstrap styled HTML button component, immediately below the ‘Learn React’ link:> <button type="button" className="btn btn-primary">Primary</button> </header> </div> ); } } export default App;
Save your changes and navigate to the running web app in your browser. If you see a blue button, similar to the screenshot below, then you’ve installed and imported Bootstrap successfully and we can move on! 👍
Creating the Base Component
When building a dynamic web app, I always like to ‘stub’ out the components first using dummy data. This involves creating the user interface and populating it using static data that I define at the top of the component. You’ll see what I mean in a few minutes.
While you’re in App.js, go ahead and delete everything in the render function, as well as the last two import statements at the top of the file.
Then, add a Bootstrap container, row,
import React, { Component } from 'react'; class App extends Component { render() { return ( <div className="container mt-5"> <div className="row"> <div className="col"> ... </div> </div> </div> ); } } export default App;
Don’t hit that save button just yet! We need to add our card HTML components inside the column class. For now, we’ll add three cards:
import React, { Component } from 'react'; class App extends Component { render() { return ( <div className="container mt-5"> <div className="row"> <div className="col"> <div className="card-deck"> <div className="card"> <img className="card-img-top" src="" alt="Card image cap" /> <div className="card-body"> <h5 className="card-title">Card title</h5> <p className="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.< card has supporting text below as a natural lead-in to additional content.<> </div> </div> </div> </div> ); } } export default App;
Each card component is filled with static content for now, so we can see what our app will look like once it’s being populated with dynamic data from Airtable.
Now you can hit that save button! Once it’s refreshed, you should see something that looks like this:
Stubbing out the Base Component
Now that we have three static movie cards looking nice in our component, we can begin to ‘stub’ out the data. When stubbing out the data, I do the following:
- Create a temporary array of objects which mimics the structure of the data that will eventually be passed into this component from our database via an API. In this case, Airtable.
- Turn the static HTML components into a new React component, so that I can dynamically render it.
- Loop through the array of objects, rendering out the new React component for each object.
Let’s start with the first step. At the top of our App.js component, right after the import statement, add the following array of objects:
const movieData = [ { title: 'Avengers: Infinity War', year: '2018', description: 'Iron Man, Thor, the Hulk and the rest of the Avengers unite to battle their most powerful enemy yet -- the evil Thanos. On a mission to collect all six Infinity Stones, Thanos plans to use the artifacts to inflict his twisted will on reality.', imageURL: '', }, { title: 'Bohemian Rhapsody', year: '2018', description: 'Bohemian Rhapsody is a foot-stomping celebration of Queen, their music and their extraordinary lead singer Freddie Mercury. Freddie defied stereotypes and shattered convention to become one of the most beloved entertainers on the planet.', imageURL: '', }, { title: 'The Incredibles 2', year: '2018', description: 'Everyone’s favorite family of superheroes is back in “Incredibles 2” – but this time Helen is in the spotlight, leaving Bob at home with Violet and Dash to navigate the day-to-day heroics of “normal” life.', imageURL: '', }, ];
What we’re doing here is instantiating a new constant of type array. Inside this array are three objects, each with a name, year, description, and image_url key/value pairs.
Creating the MovieCard Component
This is where the fun begins…
We’ve checked off step one: stubbing out our component with dummy data.
If you remember our three steps from before, step two was converting the static HTML components into a React component. To do that, at the bottom of App.js after the export statement, let’s define a new stateless, functional React component called MovieCard:
const MovieCard = () => ( > );
Remember, all React component names are written in upper camel case (pascal case). For example: MovieCard, TableList, and SideBar.
A stateless functional component has no state, and its props are passed into
Our component has no props. Let’s go ahead and add these to the parameter list. We’ll also add the props in the HTML so we can begin to populate our HTML component with the values that are passed into the props.
const MovieCard = ({ title, year, description, imageURL }) => ( <div className="card"> <img className="card-img-top" src={imageURL} <div className="card-body"> <h5 className="card-title">{title}</h5> <p className="card-text">{description}</p> <p className="card-text"> <small className="text-muted">{year}</small> </p> </div> </div> );
Looping Through the Array
Now for the magic part! Our third and final step for stubbing out our component is to loop through the array of objects and render a new copy of our MovieCard component for each object in that array.
Begin by deleting the static HTML card components from the render function, keeping the outer .card-deck div, like so:
class App extends Component { render() { return ( <div className="container mt-5"> <div className="row"> <div className="col"> <div className="card-deck"> ... </div> </div> </div> </div> ); } }
Finally, inside the .card-deck div, loop through the temporary movieData array we defined earlier and render a new copy of our <MovieCard /> component for each object in the movieData array.
class App extends Component { render() { return ( <div className="container mt-5"> <div className="row"> <div className="col"> <div className="card-deck"> {movieData.map(movie => <MovieCard {...movie} /> )} </div> </div> </div> </div> ); } }
The line of code we inserted above is doing quite a lot for one line of code.
- We’re looping through our movieData array.
- For each object in that array, we’re returning our <MovieCard /> component.
- Finally, we’re passing in the entire movie object into the <MovieCard /> component as props.
Save the file, switch to your web browser and you should see something similar to before, but this time the cards are being populated by the data defined in our array!
Play around with the array data for a while so you can see how the data is populating our MovieCard components. Try changing the data in the array. Add more objects to the movieData array to see more cards being added to our web app.
I suggest you take a minute to go over what we’ve covered so far before moving onto the next section!
Setting up Airtable
The final piece of the React and Airtable web app puzzle — Plugging an Airtable database into our quite static front end!
Sign up for a new Airtable account if you haven’t already.
I’d really appreciate it if you used my referral link:.
(Full disclosure: after signing up, I receive a $10 credit towards my Airtable account.)
You should be redirected to the dashboard page where you can create a new base after creating a new account. A base is Airtables name for a database.
Click the ‘Add a base’ button and then ‘Start from scratch’.
Give your new base a name (I chose ‘Movies’ — it felt appropriate), change the color, and pick a funky icon. Once you’re done customizing your base, click into it.
Customizing the Airtable Base
An empty base always starts with three columns: ‘Name’, ‘Notes’, and ‘Attachments’. We want to store data about our favorite movies. Change the current column structure by:
- Rename ‘Table 1’ to ‘favorites’.
- Delete the ‘Notes’ and ‘Attachments’ columns.
- Rename the ‘Name’ column to ‘title’ (use lowercase!).
- Create a new column of type number and name it ‘year’.
- Add a new column of type long text and name it ‘description’.
- Create a new column of type attachment and name it ‘
imageURL‘.
You can start adding in the movie data once you have added these columns. Feel free to add new movies, or copy the data from the movieData array we defined earlier in the tutorial.
You’ll have to find images of the movie posters online so you can upload them to the ‘imageURL’ column.
Accessing the Airtable Bases’ API
What makes Airtable so great for developers is their API. Each base provides its own very well documented API, allowing you to add, delete, edit, and save data from within your own apps. How great is that?!
The best part is the API is already set up for you, and it’s absolutely free!
While you’re still signed in, go to.
Find your base and click on it. In front of you is some rather lengthy technical documentation that describes how you interact with the Airtable API.
Scroll down to ‘Authentication’ and look at the code examples in the dark section to the right of the screen. We’re interested in the line of code under ‘EXAMPLE USING QUERY PARAMETER’.
Copy and paste just the URL somewhere for now, or make a note of it. We will need this very soon. Make sure you click the ‘Show API Key’ checkbox in the upper right-hand corner.
Integrating React and Airtable
Next let’s bring the data from Airtable into our React app.
An API (short for Application Programming Interface) is a way for software to communicate with each other. For example, our React web app wants to know what movies are stored in our Airtable database.
Airtable provides us with API documentation which tells us what URLs we must talk to from our React web app.
Open your text editor and go to the App.js component.
Let’s add
Define an initial state inside of a constructor method, like so:
class App extends Component { constructor(props) { super(props); this.state = { movies: [], }; } ... }
We’re setting the initial state of the App component to be an object with an empty array named ‘movies’.
Add another method called componentDidMount directly underneath this new constructor method.
... componentDidMount() { fetch('') .then((resp) => resp.json()) .then(data => { this.setState({ movies: data.records }); }).catch(err => { // Error :( }); } ...
componentDidMount is a lifecycle method of a class component. The code inside of it is run whenever a component is ready to be loaded onto the page.
The code above does several things:
- It adds the componentDidMount method, so that code is run once the component is ready to be shown on the web page.
- It uses fetch to call the Airtable API and get our list of movies we added to it earlier.
- It updates the component state key ‘movies’ to be the data coming back from Airtable.
Remember to use your Airtable API_KEY and code I asked you to save earlier or this won’t work!
Using our Airtable Data
Finally, change the render method to use our new ‘movies’ array stored in the component state:
... render() { return ( <div className="container mt-5"> <div className="row"> <div className="col"> <div className="card-deck"> {this.state.movies.map(movie => <MovieCard {...movie.fields} /> )} </div> </div> </div> </div> ); } ...
We need to modify the MovieCard component so that the HTML image component src attribute points to the correct value in the object:> );
Save and check out the running web app in your browser. You should see some really great looking, data-driven movie cards!
The final component is below:
import React, { Component } from 'react'; class App extends Component { constructor(props) { super(props); this.state = { movies: [], }; } componentDidMount() { fetch('') .then((resp) => resp.json()) .then(data => { console.log(data); this.setState({ movies: data.records }); }).catch(err => { // Error }); } render() { return ( <div className="container mt-5"> <div className="row"> <div className="col"> <div className="card-deck"> {this.state.movies.map(movie => <MovieCard {...movie.fields} /> )} </div> </div> </div> </div> ); } } export default App;> );
Wrapping Up React and Airtable
There you have it. We created a dynamic web app using React and Airtable.
I hope you enjoyed going through this tutorial as much as I did writing it!
As always, leave a comment if you run into any issues, or if you want more React and Airtable tutorials.
See you next time!
💻 More React Tutorials
Hi James!
I’m part-way through your tutorial (I was on a plane when I started, so I’m only just getting back to it now.
In the section “Creating the MovieCard Component” there is a slight error in your code.
This bit here:
“const MovieCard = ({ title, year, description, imageURL }) => (”
I think it should be:
“const MovieCard = ({ name, year, description, image_url }) => (”
or (and probably betterer… I haven’t gone through the Airtable bit yet) you place-setting array (which is currently)
” name: ‘Avengers: Infinity War’,
year: ‘2018’,
description: ‘Iron Man, Thor, the Hulk and the rest of the Avengers unite to battle their most powerful enemy yet — the evil Thanos. On a mission to collect all six Infinity Stones, Thanos plans to use the artifacts to inflict his twisted will on reality.’,
image_url: ‘×200’,”
should probably change name to title and image_url to imageURL.
Anyway, wanted to let you know before I forgot… especially since you specifically told us to refer what we’d done before we start with the next section.
Hi James,
This tutorial is amazing! I’ve finished it and it all totally works… I’ve actually been looking for a tutorial that links React to a database… but honestly, it’s just so nice to actually do a tutorial that doesn’t break halfway through. Your writing is excellent and everything was so clear.
The only thing I’d mention is maybe add a screen shot of the ‘Show API key’ checkbox you mention in the “Accessing the Airtable Bases’ API” section? I couldn’t find what you were talking about… but I did find a way to generate my API key in my Account section, and that totally worked, my react app looks great.
So… I don’t want to sound greedy because I really am super appreciative on this incredible tutorial.. but would you consider a follow on tutorial where we write to the database from within the app? I’d love that so hard!
Hi James!
Ah… that would be beyond amazing! Yes, I forgot about modifying and deleting records, but of course I’d need that as well.
I’ve just worked out that the “Show API Key” checkbox only appears when you’ve selected your table on the top left hand drop down box. I think I must have had it on “My First Workspace” or something similarly generic.
Thanks again!
Great tutorial! I would love to see filtering data using Airtable and React.
🙌 Great tut was successful:
I’d love to see anything more on airtable. I agree, your writing and explanation is perfect, clear and very helpful. Thank you!
Hi – Thanks so much for this tutorial! I apologize for what may be a silly question, but I’m getting errors at this line:
The error is referencing the “0”. Am I missing something? The picture that is saved in my airtable sheet is a jpg. Does it need to be a png or some other format?
Hi James, love this tutorial! thank you!
I have everything working except the final step where you change imageURL to imageURL[0]. I keep getting the following error ‘TypeError: Cannot read property ‘0’ of undefined’. If i remove ‘[0]’ it compiles and runs fine with my live airtable data but with the exception of broken images (obviously).
what am I missing? can you post source so I can make sure I didn’t misplace something.
Great tutorial. If you are a front-end developer you need data! This is a perfect way to reach data. Can you make more detailed tutorials about airtable and react?
Hi.
Great tutorial but I have an error with the image_url code.
I use the code: “src={imageURL[0].url}”
However i get the error message: Cannot read property ‘0’ of undefined
The only difference is the name of my image column/field in airtable.
Any ideas?
Hi James! Have you embedded your tutorial example website anywhere where I can check it out? I want to see what the output is before I go through the entire tutorial, so I can make sure this is the right solution for me. Thank you!
Hi James!
Your app is really a good idea, i was stunned when i first saw it, but when i try to compile it it says “TypeError: this.state.movies is undefined” on line 27, i copied ebery step right, what could it be?
Hi James!
If I have n movies and I want to split them in many rows, so that I have 3 columns per row, how can I do it in the simplest way?
One thing that had me stuck for a long time is that you have to go to your account settings and hit generate API key before the ‘Show API Key checkbox’ you spoke will show up in the right hand corner.
Hi James,
Thanks for the great tutorial. I’m new to React and having a problem rendering the final state. See below – my code is otherwise the same as yours, and when I paste your code in, and change my API key, I get the same problem.
Any ideas?
TypeError: Cannot read property ‘map’ of undefined
App.render
C:/Users/JK-PC/my-app/src/App.js:29
26 |
27 |
28 |
> 29 |
| ^ 30 | {this.state.movies.map(movie => )}
31 |
32 |
View compiled
▶ 17 stack frames were collapsed.
(anonymous function)
C:/Users/JK-PC/my-app/src/App.js:18
15 | .then((resp) => resp.json())
16 | .then(data => {
17 | console.log(data);
> 18 | this.setState({ movies: data.records });
| ^ 19 | }).catch(err => {
20 | // Error 🙁
21 | });
View compiled
Thanks,
Justin
A couple things to note, having an empty last row will cause the error with “property ‘0’ of undefined” for the imageURL[0]. The error “Cannot read property ‘map’ of undefined” means it can’t find your database name from the YOUR_AIRTABLE_ENDPOINT. To get the correct endpoint, generate an API key and refresh the API docs and then the ‘show API key’ option will appear with the correct info as mentioned in the comments.
First, this tutorial is awesome. You got me from ZERO to a full working web app in about 30 minutes. One concern I have is the API KEY itself. If it’s in my javascript, that means it is accessible to an enterprising user that wants to dig through my .js files, right?
Do you have an effective way to prevent people from accessing that? Because I love what I’ve got working, I’m just concerned that we’ve got a bit of a security hole.
For example, the API KEY you’re using ends in “CqF4.” (I’m not malicious, just curious how you’d solve for that.)
Awesome how-to. I’m having the same issue as Justin. I’m getting the Cannot read property ‘map’ of undefined on line 28. Wondering what I’m missing. Thanks for your help. | https://upmostly.com/tutorials/create-simple-web-app-react-airtable | CC-MAIN-2020-29 | refinedweb | 4,030 | 64 |
what do the use of yeild in python ?
What is the python generator and how yeild works in python ?
what is yeild python example ?
What are metaclasses in Python?
Does Python have a ternary conditional operator?
What does if name == “main“: do?
how to call the external commanad in the python script?
How to merge two dictionaries in a single expression?
How to create a nested directory in Python?
Does Python have a string ‘contains’ substring method?
sorting a dictionary by value?
Checking wheather the list is empty or not ?
Difference between append vs extend list in Python ?
What is the difference between staticmethod and classmethod?
Accessing the index ‘for’ loops in python script ?
Using global variables in a function in python ?
Understanding Python slice notation ?
How to make a chain of function decorators in python?
Finding the index of an item given a list containing it in Python ?
Check if a given key already exists in a dictionary in python ?
Iterating over dictionaries using ‘for’ loops in python ?
How to make a flat list out of list of lists?
How do I install pip on Windows?
How do I install pip on linux?
How do I install pip on centos?
How do I install pip on ubuntu?
How do I install python on Windows?
How do I install python on linux?
How do I install python on centos?
How do I install python on ubuntu?
Difference between str and repr in Python?
How do I pass a variable by reference in Python?
“Least Astonishment” and the Mutable Default Argument in Python ?
How to get current date time in Python?
how to formate a date?
What does ** (double star/asterisk) and * (star/asterisk) do for parameters?
How do you split a list into evenly sized chunks?
Is there a way to substring a string?
Manually raising (throwing) an exception in Python
How to get the number of elements in a list in Python?
How do I copy a file in Python?
Find current directory and file’s directory
Converting string into datetime
How to lowercase a string in Python?
Are static class variables possible?
Replacements for switch statement in Python?
Why is reading lines from stdin much slower in C++ than Python?
Delete a file or folder
What is init.py for?
Getting the last element of a list in Python
Upgrading all packages with pip
Why is “1000000000000000 in range(1000000000000001)” so fast in Python 3?
Determine the type of an object?
How to print without newline or space?
Python join: why is it string.join(list) instead of list.join(string)?
How do I sort a list of dictionaries by a value of the dictionary?
Static methods in Python?
Convert bytes to a string?
How do I access environment variables from Python?
How to randomly select an item from a list?
Meaning of @classmethod and @staticmethod for beginner?
How do I check if a string is a number (float)?
Calling a function of a module by using its name (a string)
Parsing values from a JSON file?
How do you append to a file?
Use of *args and **kwargs
How to know if an object has an attribute in Python
Renaming columns in pandas
Python string formatting: % vs. .format
How to remove a key from a Python dictionary?
How can I count the occurrences of a list item?
How to leave/exit/deactivate a python virtualenv?
Reverse a string in Python
How can I represent an ‘Enum’ in Python?
How do I remove an element from a list by index in Python?
Getting the class name of an instance?
Converting integer to string in Python?
Create a dictionary with list comprehension in Python
Nicest way to pad zeroes to a string
Random string generation with upper case letters and digits in Python
Select rows from a DataFrame based on values in a column in pandas
How to print to stderr in Python?
Find all files in a directory with extension .txt in Python
What is the meaning of a single and a double underscore before an object name?
UnicodeEncodeError: ‘ascii’ codec can’t encode character u’\xa0′ in position 20: ordinal not in range(128)
How can you profile a Python script?
Most elegant way to check if the string is empty in Python?
How can I print literal curly-brace characters in python string and also use .format on it?
What are the differences between type() and isinstance()?
Generate random integers between 0 and 9
How do I trim whitespace from a Python string?
Proper way to declare custom exceptions in modern Python?
What’s the canonical way to check for type in Python?
Does Django scale?
Delete an element from a dictionary
How to iterate over rows in a DataFrame in Pandas?
Extracting extension from filename in Python
How to flush output of print function?
Why does comparing strings in Python using either ‘==’ or ‘is’ sometimes produce a different result?
How do I trim whitespace?
Installing specific package versions with pip
What is the purpose of self?
How do I check what version of Python is running my script?
null object in Python?
Why use pip over easy_install?
Way to create multiline comments in Python?
What’s the difference between lists and tuples?
Pythonic way to create a long multi-line string
Delete column from pandas DataFrame using del df.column_name
What is the difference between old style and new style classes in Python?
What is the Python 3 equivalent of “python -m SimpleHTTPServer”
If Python is interpreted, what are .pyc files?
In Python, how do I determine if an object is iterable?
Why are Python lambdas useful?
Python class inherits object
How can I do a line break (line continuation) in Python?
Use different Python version with virtualenv
How to get the ASCII value of a character?
How to import a module given the full path?
Convert two lists into a dictionary in Python
How to find if directory exists in Python
Save plot to image file instead of displaying it using Matplotlib
Correct way to write line to file?
How can I reverse a list in Python?
How do I parse XML in Python?
fatal error: Python.h: No such file or directory
How do I write JSON data to a file?
How can I get a list of locally installed Python modules?
Terminating a Python script
How to get line count cheaply in Python?
“Large data” work flows using pandas
Count the number occurrences of a character in a string
What is a mixin, and why are they useful?
Peak detection in a 2D array
How to remove items from a list while iterating?
How do I create a constant in Python?
Is there a simple way to delete a list element by value?
Why does Python code run faster in a function?
How to install packages using pip according to the requirements.txt file from a local directory?
How to get file creation & modification date/times in Python?
Should I use ‘has_key()’ or ‘in’ on Python dicts?
Is there a built-in function to print all the current properties and values of an object?
How do I find the location of my Python site-packages directory?
What are “named tuples” in Python?
How does the @property decorator work?
Single quotes vs. double quotes in Python
How do I download a file over HTTP using Python?
How do I read a text file into a string variable in Python
Import a module from a relative path
pip install mysql-python fails with EnvironmentError: mysql_config not found
Removing duplicates in lists
How do I remove/delete a folder that is not empty with Python?
What is the use of “assert” in Python?
Checking whether a variable is an integer or not
How can I sort a dictionary by key?
Can someone explain all in Python?
differentiate null=True, blank=True in django
Understanding kwargs in Python
list comprehension vs. lambda + filter
How do I check if a variable exists?
How do I get time of a Python program’s execution?
How does Python’s super() work with multiple inheritance?
python setup.py uninstall
How to put the legend out of the plot
Adding new column to existing DataFrame in Python pandas
How do I install a Python package with a .whl file?
Using @property versus getters and setters
How to prettyprint a JSON file?
How do I remove packages installed with Python’s easy_install?
How do I unload (reload) a Python module?
Python progression path – From apprentice to guru
How to make IPython notebook matplotlib plot inline
Display number with leading zeros
Is arr.len() the preferred way to get the length of an array in Python?
Running shell command and capturing the output
Get list from pandas DataFrame column headers
What is setup.py?
mkdir -p functionality in Python
How can I check for NaN values?
How do you remove duplicates from a list whilst preserving order?
What is the standard Python docstring format?
Creating a singleton in Python
How to get the filename without the extension from a path in Python?
Behaviour of increment and decrement operators in Python
Python’s equivalent of && (logical-and) in an if-statement
How to fix “Attempted relative import in non-package” even with init.py
How can I force division to be floating point? Division keeps rounding down to 0?
How to properly ignore exceptions
What is the difference between range and xrange functions in Python 2.X?
How to get the home directory in Python?
Why shouldn’t I use PyPy over CPython if PyPy is 6.3 times faster?
Is there any way to kill a Thread?
Why is [] faster than list()?
Selecting multiple columns in a pandas dataframe
What is the best project structure for a Python application?
Multiprocessing vs Threading Python
Convert hex string to int in Python
Speed comparison with Project Euler: C vs Python vs Erlang vs Haskell
Getting key with maximum value in dictionary?
Emulate a do-while loop in Python?
How to iterate through two lists in parallel?
Which Python memory profiler is recommended?
What is the naming convention in Python for variable and function names?
Python integer incrementing with ++
What is the difference between dict.items() and dict.iteritems()?
Putting a simple if-then-else statement on one line
How to move a file in Python
How to sort a list of objects based on an attribute of the objects?
if/else in Python’s list comprehension?
How to change a string into uppercase
Using Python 3 in virtualenv
List comprehension vs map
Shuffling a list of objects
Convert a String representation of a Dictionary to a dictionary?
Fastest way to check if a value exist in a list
Get difference between two lists
What is a clean, pythonic way to have multiple constructors in Python?
How to subtract a day from a date?
What are the differences between the urllib, urllib2, and requests module?
How to define a two-dimensional array in Python
Remove all whitespace in a string in Python
How to check file size in python?
How to remove the first Item from a list?
Python
if x is not None or
if not x is None?
Should I put #! (shebang) in Python scripts, and what form should it take?
Retrieving python module path
Differences between distribute, distutils, setuptools and distutils2?
How to make a class JSON serializable
How can I get the concatenation of two lists in Python without modifying either one?
Is there a difference between
== and
is in Python?
How to use a decimal range() step value?
Usage of slots?
How do I protect Python code?
Why are Python’s ‘private’ methods not actually private?
How do you test that a Python function throws an exception?
How to print the full traceback without halting the program?
How do I change directory (cd) in Python?
How to print a date in a regular format?
Use a Glob() to find files recursively in Python?
Split Strings with Multiple Delimiters?
How do I do a not equal in Django queryset filtering?
How to import other Python files?
How to get an absolute file path in Python
Traverse a list in reverse order in Python
How can I use Python to get the system hostname?
How to print number with commas as thousands separators?
Running unittest with typical test directory structure
How to get a function name as a string in Python?
not None test in Python
How do I detect whether a Python variable is a function?
What does the ‘b’ character do in front of a string literal?
Adding a Method to an Existing Object Instance
Remove empty strings from a list of strings
Directory-tree listing in Python
Converting from a string to boolean in Python?
How to get full path of current file’s directory in Python?
Difference between del, remove and pop on lists
open() in Python does not create a file if it doesn’t exist
Maximum and Minimum values for ints
Styling multi-line conditions in ‘if’ statements?
Find which version of package is installed with pip
How do I get the row count of a Pandas dataframe?
How to debug in Django, the good way?
How to read/process command line arguments?
add one row in a pandas.DataFrame
Argparse optional positional arguments?
How can I open multiple files using “with open” in Python?
Is there a portable way to get the current username in Python?
What is the purpose of the single underscore “_” variable in Python?
Best way to convert string to bytes in Python 3?
How to drop rows of Pandas DataFrame whose value in certain columns is NaN
How do I append one string to another in Python?
What is the Python equivalent of static variables inside a function?
About catching ANY exception
How do you get the logical xor of two variables in Python?
Python reverse / invert a mapping
What is the difference between pip and conda?
What does the star operator mean?
Why use def main()?
pip install from git repo branch
How to make a Python script standalone executable to run without ANY dependency?
Convert date to datetime in Python
Build a Basic Python Iterator
Extract file name from path, no matter what the os/path format
What is the quickest way to HTTP GET in Python?
What exactly do “u” and “r” string flags do, and what are raw string literals?
What is future in Python used for and how/when to use it, and how it works
How to split a string into a list?
How to overcome “datetime.datetime not JSON serializable”?
Best way to strip punctuation from a string in Python
Get Last Day of the Month in Python
String comparison in Python: is vs. ==
How to create a GUID/UUID in Python
Convert nested Python dict to object?
How to test multiple variables against a value?
Difference between abstract class and interface in Python
How to generate all permutations of a list in Python
Python Print String To Text File
Why does “not(True) in [False, True]” return False?
How to sort (list/tuple) of lists/tuples?
Why is init() always called after new()?
What does functools.wraps do?
Change data type of columns in Pandas
How do I convert datetime to date (in Python)?
Relative imports in Python 3
Find intersection of two nested lists?
How to do relative imports in Python?
How to get data received in Flask request
List of lists changes reflected across sublists unexpectedly
How to a read large file, line by line in Python
How to capitalize the first letter of each word in a string (Python)?
Call a parent class’s method from child class in Python?
What is the difference between venv, pyvenv, pyenv, virtualenv, virtualenvwrapper, pipenv, etc?
Finding local IP addresses using Python’s stdlib
Python: What OS am I running on?
How to install psycopg2 with “pip” on Python?
Python try-else
Writing a list to a file with Python
Should you always favor xrange() over range()?
python open built-in function: difference between modes a, a+, w, w+, and r+?
Simple argparse example wanted: 1 argument, 3 results
How do I capture SIGINT in Python?
Does Python have “private” variables in classes?
What does ‘super’ do in Python?
How to urlencode a querystring in Python?
Iterating each character in a string using Python
How to import the class within the same directory or sub directory?
Django – Set Up A Scheduled Job?
How do I use raw_input in Python 3
Pandas writing dataframe to CSV file
Convert list to tuple in Python
What is a “slug” in Django?
Non-blocking read on a subprocess.PIPE in python
Get key by value in dictionary
What is a Python egg?
Is it possible to break a long line to multiple lines in Python
How to set the current working directory?
Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?
Use a list of values to select rows from a pandas dataframe
Python add new item to dictionary
Importing modules from parent folder
Does Python’s time.time() return the local or UTC timestamp?
Asking the user for input until they give a valid response
Convert a Unicode string to a string in Python (containing extra symbols)
User input and command line arguments
Why dict.get(key) instead of dict[key]?
How to install lxml on Ubuntu
How to check version of python modules?
IndentationError: unindent does not match any outer indentation level
Disable output buffering
Calling C/C++ from Python?
How to install pip with Python 3?
Is there a list of Pytz Timezones?
How do I do a case-insensitive string comparison?
How are Pandas iloc, ix and loc different and related?
Find and Replace Inside a Text File from a Bash Command
Convert all strings in a list to int
What is the common header format of Python files?
Installation Issue with matplotlib Python
“is” operator behaves unexpectedly with integers
Check if a Python list item contains a string inside another string
What’s the difference between a Python module and a Python package?
Best practice for Python assert
Tensorflow: how to save/restore a model?
Short Description of the Scoping Rules?
How do I get the path and name of the file that is currently executing?
Python: Find in list
How to check Django version
How do I make python to wait for a pressed key
How do I find the location of Python module sources?
What’s the idiomatic syntax for prepending to a short python list?
How to import a module given its name?
Transpose/Unzip Function (inverse of zip)?
Which exception should I raise on bad/illegal argument combinations in Python?
How to check if an object is a list or tuple (but not string)?
How do I update pip itself from inside my virtual environment?
Post JSON using Python Requests
How can I represent an infinite number in Python?
What is monkey patching?
Proper indentation for Python multiline strings
Parsing boolean values with argparse
Remove specific characters from a string in Python
Is there a simple, elegant way to define singletons?
How to convert strings into integers in Python?
How to print objects of class using print()?
Getting a map() to return a list in Python 3.x
How can I parse a YAML file in Python
How do I correctly clean up a Python object?
How to print an exception in Python?
How do I use Python’s itertools.groupby()?
What are the advantages of NumPy over regular Python lists?
How to return dictionary keys as a list in Python?
What is the python keyword “with” used for?
How can I fill out a Python string with spaces?
Is there a short contains function for lists?
How to install python3 version of package via pip on Ubuntu?
How to print the full NumPy array?
Rename multiple files in a directory in Python
Access an arbitrary element in a dictionary in Python
Creating a JSON response using Django and Python
Convert list of dictionaries to a pandas DataFrame
What is the easiest way to remove all packages installed by pip?
How to comment out a block of code in Python
How do I calculate number of days between two dates using Python?
What is the best way to remove accents in a Python unicode string?
How to find out the number of CPUs using python
Why are there no ++ and – operators in Python?
How do I get the day of week given a date in Python?
What is the difference between re.search and re.match?
In Matplotlib, what does the argument mean in fig.add_subplot(111)?
What is the most “pythonic” way to iterate over a list in chunks?
What does the Python Ellipsis object do?
How do I get my Python program to sleep for 50 milliseconds?
Dump a NumPy array into a csv file
How can I find script’s directory with Python?
Can I get JSON to load into an OrderedDict?
Python int to binary?
Create List of Single Item Repeated n Times in Python
What does the “at” (@) symbol do in Python?
python: list vs tuple, when to use each?
Finding the average of a list
How to save a Python interactive session?
What do the python file extensions, .pyc .pyd .pyo stand for?
No module named pkg_resources
Separation of business logic and data access in django
How to detect a Christmas Tree?
What is a Python equivalent of PHP’s var_dump()?
Is it worth using Python’s re.compile?
PyLint, PyChecker or PyFlakes?
Convert a list of characters into a string
Getting a list of all subdirectories in the current directory
Flatten an irregular list of lists
Flattening a shallow list in Python
Proper way to use **kwargs in Python
How to make an unaware datetime timezone aware in python
Does Python have an ordered set?
Get current time in milliseconds in Python?
How would you make a comma-separated string from a list of strings?
How to delete a character from a string using Python
Pretty printing XML in Python
Most pythonic way to delete a file which may not exist
What are the differences between json and simplejson Python modules?
How do I convert seconds to hours, minutes and seconds?
What’s the difference between eval, exec, and compile?
Python “extend” for a dictionary
Get HTML Source of WebElement in Selenium WebDriver using Python
Generator Expressions vs. List Comprehension
Python module for converting PDF to text
Why do some functions have underscores “” before and after the function name? How to break out of multiple loops in Python? How to sort a list of strings? Empty set literal? How can the Euclidean distance be calculated with NumPy? Create an empty list in python with certain size Import error: No module name urllib2 Comprehensive beginner’s virtualenv tutorial? pip: dealing with multiple Python versions? Return None if Dictionary key is not available How to access the ith column of a NumPy multidimensional array? What is the python “with” statement designed for? Is there a NumPy function to return the first index of something in an array? Which version of Python do I have installed? Relative imports for the billionth time How can I tell if a string repeats itself in Python? Python error “ImportError: No module named” Checking whether a string starts with XXXX How do I translate an ISO 8601 datetime string into a Python datetime object? What does “SyntaxError: Missing parentheses in call to ‘print'” mean in Python? How to serve static files in Flask How do I set the figure title and axes labels font size in Matplotlib? What is the difference between ‘/’ and ‘//’ when used for division? How do I determine if my python shell is executing in 32bit or 64bit mode on OS X? Simple Digit Recognition OCR in OpenCV-Python Determine function name from within that function (without using traceback) Convert string representation of list to list Split string on whitespace in Python Python: Split string with multiple delimiters How do I log a Python error with debug information? Import a file from a subdirectory? How can I iterate over files in a given directory? Understanding dict.copy() – shallow or deep? How to change the font size on a matplotlib plot How do you round UP a number in Python? Install a Python package into a different directory using pip? Elegant Python function to convert CamelCase to snake_case? How to deal with SettingWithCopyWarning in Pandas? Filter dict to contain only certain keys? What exactly are iterator, iterable, and iteration? Creating a new dict in Python Converting a Pandas GroupBy object to DataFrame How can I check if a string represents an int, without using try/except? Python multiprocessing pool.map for multiple arguments Python Dictionary Comprehension How do I get indices of N maximum values in a NumPy array? Concatenate item in list to strings super() raises “TypeError: must be type, not classobj” for new-style class Determine if variable is defined in Python How does collections.defaultdict work? Difference between __getattr vs getattribute
Can I force pip to reinstall the current version?
Elegant ways to support equivalence (“equality”) in Python classes
Recommendations of Python REST (web services) framework?
Fastest way to list all primes below N
Difference between exit() and sys.exit() in Python
Should import statements always be at the top of a module?
Python Graph Library
SQLAlchemy: What’s the difference between flush() and commit()?
How do I remove/delete a virtualenv?
How to delete the contents of a folder in Python?
Pretty-print an entire Pandas Series / DataFrame
Making Python loggers output all messages to stdout in addition to log file
Sort a list of tuples by 2nd item (integer value)
How to create a zip archive of a directory
Python pandas, how to widen output display to see more columns?
How do I resize an image using PIL and maintain its aspect ratio?
Deleting DataFrame row in Pandas based on column value
Python vs Cpython
Filter dataframe rows if value in column is in a set list of values
python 3.5: TypeError: a bytes-like object is required, not ‘str’ when writing to a file
SQLAlchemy ORDER BY DESCENDING?
How do you express binary literals in Python?
What SOAP client libraries exist for Python, and where is the documentation for them?
How to empty a list in Python?
What’s the difference between raw_input() and input() in python3.x?
How do I read CSV data into a record array in NumPy?
Python datetime to string without microsecond component
Is it a good practice to use try-except-else in Python?
How to retrieve an element from a set without removing it?
Installing pip packages to $HOME folder
Showing the stack trace from a running Python application
Python List vs. Array – when to use?
time.sleep — sleeps thread or process?
What is the difference between init and call in Python?
Finding what methods a Python object has
Get exception description and stack trace which caused an exception, all as a string
Return JSON response from Flask view
Text Progress Bar in the Console
Why does python use ‘else’ after for and while loops?
if else in a list comprehension
Python and pip, list all versions of a package that’s available?
Setting the correct encoding when piping stdout in Python
Python: Extract numbers from a string
How to list all functions in a Python module?
Why isn’t Python very good for functional programming?
Sort a list by multiple attributes?
Tabs versus spaces in Python programming
Changing the “tick frequency” on x or y axis in matplotlib?
Append integer to beginning of list in Python
Expanding tuples into arguments
Getting the index of the returned max or min item using max()/min() on a list
Python Image Library fails with message “decoder JPEG not available” – PIL
How to use the pass statement?
Is there a “not equal” operator in Python?
Difference between map, applymap and apply methods in Pandas
Saving utf-8 texts in json.dumps as UTF8, not as \u escape sequence
How do I find the duplicates in a list and create another list with them?
Reading binary file and looping over each byte
Reloading submodules in IPython
Numpy array dimensions
How to check if any value is NaN in a Pandas DataFrame
Python Create unix timestamp five minutes in the future
Is there a Python equivalent to Ruby’s string interpolation?
How can I replace all the NaN values with Zero’s in a column of a pandas dataframe
How can I check the syntax of Python script without executing it?
How do I disable log messages from the Requests library?
Removing pip’s cache?
How to get a random number between a float range?
check if all elements in a list are identical
UnicodeDecodeError: ‘charmap’ codec can’t decode byte X in position Y: character maps to
Can a variable number of arguments be passed to a function?
When is del useful in python?
The difference between sys.stdout.write and print?
How to get all possible combinations of a list’s elements?
What is the standard way to add N seconds to datetime.time in Python?
How can I selectively escape percent (%) in Python strings?
Selenium using Python – Geckodriver executable needs to be in PATH
Generating a PNG with matplotlib when DISPLAY is undefined
Python: How to ignore an exception and proceed?
Call a function from another file in Python
Python — return, return None, and no return at all
Threading pool similar to the multiprocessing Pool?
Decorators with parameters?
How to write a Python module/package?
Print a list in reverse order with range()?
How to state in requirements.txt a direct github source
Convert string to JSON using Python
How to add to the pythonpath in Windows?
Change one character in a string?
Selecting a row of pandas series/dataframe by integer index
Python String and Integer concatenation
How to download image using requests
Use ‘import module’ or ‘from module import’?
Why are some float < integer comparisons four times slower than others? Find full path of the Python interpreter? Configure Flask dev server to be visible across the network How do I find out my python path using python? Python string.replace regular expression What are the differences between numpy arrays and matrices? Which one should I use? python exception message capturing How can I compare two lists in python and return matches Multiple variables in Python ‘with’ statement How do I fix ‘ImportError: cannot import name IncompleteRead’? How do you get a query string on Flask? How to define two fields “unique” as couple Python list sort in descending order How to compare two dates? How can I convert a datetime object to milliseconds since epoch (unix time) in Python? Python unittest – opposite of assertRaises? Get the name of current script with Python Read .mat files in Python How do I watch a file for changes? Circular (or cyclic) imports in Python Using module ‘subprocess’ with timeout How do I remove a substring from the end of a string in Python? Alphabet range python What is the best (idiomatic) way to check the type of a Python variable? How to write inline if statement for print? Set value for particular cell in pandas DataFrame using index Reading entire file in Python Iterating through a range of dates in Python Python date string to date object Hiding axis text in matplotlib plots CSV file written with Python has blank lines between each row Check if multiple strings exist in another string Python argparse: How to insert newline in the help text? Remove all occurrences of a value from a list? Why is ‘x’ in (‘x’,) faster than ‘x’ == ‘x’? clang error: unknown argument: ‘-mno-fused-madd’ (python package installation failure) Append values to a set in Python How to overload init method based on argument type? Why is “except: pass” a bad programming practice? How can I check if a key exists in a dictionary? How to download large file in python with requests.py? How do you convert a Python time.struct_time object into a datetime object? In practice, what are the main uses for the new “yield from” syntax in Python 3.3? How to convert index of a pandas dataframe into a column? How do I execute a string containing Python code in Python? What is the most efficient way to loop through dataframes with pandas? What does Ruby have that Python doesn’t, and vice versa? Does Python support short-circuiting? What does asterisk * mean in Python? How do I calculate the date six months from the current date using the datetime Python module? How to use timeit module Chain-calling parent constructors in python Simple way to remove multiple spaces in a string? How to invoke the super constructor? What is an alternative to execfile in Python 3? Unicode (UTF-8) reading and writing to files in Python Adding 5 days to a date in Python Unresolved reference issue in PyCharm What blocks Ruby, Python to get Javascript V8 speed? Understanding get and set and Python descriptors Django development IDE Passing a dictionary to a function in python as keyword parameters What is the difference between an expression and a statement in Python? What is logits, softmax and softmax_cross_entropy_with_logits? How to find elements by class Are dictionaries ordered in Python 3.6+? What is the maximum recursion depth in Python, and how to increase it? Python dictionary from an object’s fields What’s the bad magic number error? Find all occurrences of a substring in Python How do I get a Cron like scheduler in Python? How to “test” NoneType in python? How to manage local vs production settings in Django? Creating an empty Pandas DataFrame, then filling it? Reimport a module in python while interactive TypeError: ‘str’ does not support the buffer interface Why use argparse rather than optparse? argparse option for passing a list as option Is it possible to use pip to install a package from a private github repository? In Python, when to use a Dictionary, List or Set? How can I explicitly free memory in Python? Get all object attributes in Python? What is a “callable” in Python? Is there a standardized method to swap two variables in Python? Split by comma and strip whitespace in Python What is
related_name used for in Django?
Get the last 4 characters of a string
setup script exited with error: command ‘x86_64-linux-gnu-gcc’ failed with exit status 1
How to send an email with Gmail as provider using Python?
Error: ” ‘dict’ object has no attribute ‘iteritems’ ”
How to install Python MySQLdb module using pip?
How to clear the interpreter console?
Is there a way to perform “if” in python’s lambda
Redirect stdout to a file in Python?
Correct way to try/except using Python requests module?
What do *args and **kwargs mean?
Getting “Error loading MySQLdb module: No module named MySQLdb” – have tried previously posted solutions
Use of “global” keyword in Python
What’s the best solution for OpenID with Django?
How to find all occurrences of an element in a list?
Test if executable exists in Python?
Is a Python list guaranteed to have its elements stay in the order they are inserted in?
Wrapping a C library in Python: C, Cython or ctypes?
Stripping everything but alphanumeric chars from a string in Python
How do I check if a given Python string is a substring of another one?
How to avoid .pyc files?
How can I get a list of all classes within current module in Python?
How to query as GROUP BY in django?
What is the correct syntax for ‘else if’?
Reading a file without newlines
Which is the preferred way to concatenate a string in Python?
Permanently add a directory to PYTHONPATH?
Python setup.py develop vs install
Python: Run function from the command line
join list of lists in python
How to get string objects instead of Unicode from JSON?
How do I install the yaml package for Python?
How to count number of rows per group (and other statistics) in pandas group by?
Syntax error on print with Python 3
Print in one line dynamically
Run a python script from another python script, passing in args
How do I get the parent directory in Python?
How to use filter, map, and reduce in Python 3
Why doesn’t os.path.join() work in this case?
How do I access command line arguments in Python?
How to terminate a python subprocess launched with shell=True
Getting the SQL from a Django QuerySet
Python: defaultdict of defaultdict?
Find nearest value in numpy array
How to uninstall Python 2.7 on a Mac OS X 10.6.4?
Why is IoC / DI not common in Python?
What does -> mean in Python function definitions?
PyPy — How can it possibly beat CPython?
Explaining Python’s ‘enter‘ and ‘exit‘
Generating an MD5 checksum of a file
How to implement common bash idioms in Python?
In Python, what does it mean if an object is subscriptable or not?
Python – How do I pass a string into subprocess.Popen (using the stdin argument)?
Reading JSON from a file?
How do I create a variable number of variables?
How to calculate the angle between a line and the horizontal axis?
How to pretty-printing a numpy.array without scientific notation and with given precision?
Compiled vs. Interpreted Languages
How to declare and add items to an array in Python?
Implement touch using Python?
pandas: filter rows of DataFrame with operator chaining
How do I convert local time to UTC in Python?
How to disable python warnings
Sorting list based on values from another list?
Python dictionary: are keys() and values() always the same order?
Store output of subprocess.Popen call in a string
Representing and solving a maze given an image
find first sequence item that matches a criterion
How to exit from Python without traceback?
Check if a given key already exists in a dictionary and increment it
Append dictionary to a dictionary?
Normal arguments vs. keyword arguments
How do I check whether an int is between the two numbers?
How many classes should I put in one file?
How do I get user IP address in django?
How to percent-encode URL parameters in Python?
Python 3 ImportError: No module named ‘ConfigParser’
No Multiline Lambda in Python: Why not?
Search and replace a line in a file in Python
How to get current CPU and RAM usage in Python?
Python: Checking if a ‘Dictionary’ is empty doesn’t seem to work
How do I execute a program from Python? os.system fails due to spaces in path
Turn a string into a valid filename?
What is PEP8’s E128: continuation line under-indented for visual indent?
Strip HTML from strings in Python
Calculating arithmetic mean (one type of average) in Python
What are the differences between Perl, Python, AWK and sed?
‘too many values to unpack’, iterating over a dict. key=>string, value=>list
Change the name of a key in dictionary
Get the cartesian product of a series of lists?
How to fix Python indentation
How can I create a directly-executable cross-platform GUI app using Python?
How do I split a multi-line string into multiple lines?
How can I create an object and add attributes to it?
Understanding the map function
Cannot install Lxml on Mac os x 10.9
How can I check for Python version in a program that uses new language features?
How do I get list of methods in a Python class?
Installing Python packages from local file system folder to virtualenv with pip
Lazy Method for Reading Big File in Python?
Python string.join(list) on object array rather than string array
Python argparse command line flags without arguments
Why do python lists have pop() but not push()
logger configuration to log to file and print to stdout
What’s the difference between filter and filter_by in SQLAlchemy?
How to delete items from a dictionary while iterating over it?
Best way to format integer as string with leading zeros?
matplotlib Legend Markers Only Once
Using pip behind a proxy
SSL InsecurePlatform error when using Requests package
Sorting arrays in NumPy by column
What is main.py?
Case insensitive Python regular expression without re.compile
Deep copy of a dict in python
Python nonlocal statement
Relationship between SciPy and NumPy
How can I convert a character to a integer in Python, and viceversa?
Can “list_display” in a Django ModelAdmin display attributes of ForeignKey fields?
How can I read inputs as numbers?
PyCharm shows unresolved references error for valid code
How to format a floating number to fixed width in Python
Why is there no xrange function in Python3?
Converting Python dict to kwargs?
Why does range(start, end) not include end?
How to execute a file within the python interpreter?
How do I create an empty array/matrix in NumPy?
What is the purpose of class methods?
Get lengths of a list in a jinja2 template
Class method differences in Python: bound, unbound and static
How can I find all matches to a regular expression in Python?
Why doesn’t Python have multiline comments?
How do you create a daemon in Python?
How to change legend size with matplotlib.pyplot
Typical AngularJS workflow and project structure (with Python Flask)
How to send email attachments?
What is the difference between ” is None ” and ” ==None “
What is the best way to call a script from another script?
How to merge lists into a list of tuples?
Splitting on first occurrence
How do I find the time difference between two datetime objects in python?
How do you run a Python script as a service in Windows?
Download file from web in Python 3
Creating a range of dates in Python
Django datetime issues (default=datetime.now())
How to hide output of subprocess in Python 2.7
How to make good reproducible pandas examples
Printing Lists as Tabular Data
Python Flask how to get parameters from a URL?
Convert base-2 binary number string to int
Django – what is the difference between render(), render_to_response() and direct_to_template()?
What is the best way to compare floats for almost-equality in Python?
How to perform OR condition in django queryset?
How to take the first N items from a generator or list in Python?
How to write LaTeX in IPython Notebook?
Using both Python 2.x and Python 3.x in IPython Notebook
Most efficient way to reverse a numpy array
How do I check if a string is unicode or ascii?
Convert datetime object to a String of date only in Python
Python – Create list with numbers between 2 values?
What does Python’s eval() do?
Measuring elapsed time with the Time module
Django gives Bad Request (400) when DEBUG = False
Split a string by spaces — preserving quoted substrings — in Python
Automatically creating directories with file output
Catching an exception while using a Python ‘with’ statement
multiprocessing.Pool: When to use apply, apply_async or map?
Python subprocess/Popen with a modified environment
How to start a background process in Python?
Python try…except comma vs ‘as’ in except
How do I integrate Ajax with Django applications?
Extract subset of key-value pairs from Python dictionary object?
How do I keep Python print from adding newlines or spaces?
How do I check which version of NumPy I’m using?
Why compile Python code?
How to get Linux console window width in Python
Find index of last occurrence of a substring in a string
How to reset index in a pandas data frame?
A clean, lightweight alternative to Python’s twisted?
Pythonic way to avoid “if x: return x” statements
Python read a single character from the user
Unzipping files in python
python: how to identify if a variable is an array or a scalar
Converting Epoch time into the datetime
Python: How to get a value of datetime.today() that is “timezone aware”?
Print current call stack from a method in Python code
How to convert 2D float numpy array to 2D int numpy array?
Efficient way to shift a list in python
Get the first item from an iterable that matches a condition
How can I see normal print output created during pytest run?
Decode HTML entities in Python string?
What is getattr() exactly and how do I use it?
Difference between numpy.array shape (R, 1) and (R,)
Having Django serve downloadable files
Simpler way to create dictionary of separate variables?
Retrieving the output of subprocess.call()
Is there a way to detach matplotlib plots so that the computation can continue?
What’s the difference between dist-packages and site-packages?
how to get the return value from a thread in python?
Substitute multiple whitespace with single whitespace in Python
How to extract the substring between two markers?
DatabaseError: current transaction is aborted, commands ignored until end of transaction block
How to use “raise” keyword in Python
Pythonic way to combine FOR loop and IF statement
Python: split a list based on a condition?
Why aren’t python nested functions called closures?
Converting between datetime, Timestamp and datetime64
Django auto_now and auto_now_add
Reference requirements.txt for the install_requires kwarg in setuptools setup.py file?
Sending HTML email using Python
Cost of len() function
Add Variables to Tuple
How to add an extra column to a NumPy array
Check if something is not in a list in Python
Python format timedelta to string
Python function global variables?
Shuffle an array with python, randomize array item order with python
Is there any difference between “foo is None” and “foo == None”?
Initialise a list to a specific length in Python
Can a website detect when you are using selenium with chromedriver?
Argparse: Way to include default values in ‘–help’?
Ignore python multiple return value
Why is there no tuple comprehension in Python?
Get the key corresponding to the minimum value within a dictionary
Why return NotImplemented instead of raising NotImplementedError
How to initialize a two-dimensional array in Python?
namedtuple and default values for optional keyword arguments
Matplotlib make tick labels font size smaller
How to put individual tags for a scatter plot
Secondary axis with twinx(): how to add to legend?
Can’t subtract offset-naive and offset-aware datetimes
How do I run all Python unit tests in a directory?
Convert a number range to another range, maintaining ratio
How can I make one python file run another?
Python: Attribute Error – ‘NoneType’ object has no attribute ‘something’
How do I set the maximum line length in PyCharm?
filename.whl is not supported wheel on this platform
Breaking out of nested loops
What is the fastest way to send 100,000 HTTP requests in Python?
Assign output of os.system to a variable and prevent it from being displayed on the screen
Django – How to rename a model field using South?
Initializing a list to a known number of elements in Python
How do I clone a Django model instance object and save it to the database?
How to get POSTed json in Flask?
Is there any way to do HTTP PUT in python
Converting NumPy array into Python List structure?
Does Python have a built in function for string natural sort?
Import multiple csv files into pandas and concatenate into one DataFrame
How to load all modules in a folder?
json.dumps vs flask.jsonify
Is there a Python equivalent of the C# null-coalescing operator?
Removing a list of characters in string
Writing Unicode text to a text file?
django filter with list of values
What’s the scope of a variable initialized in an if statement?
How to get a complete list of object’s methods and attributes?
Python pip install fails: invalid command egg_info
Is it possible only to declare a variable without assigning any value in Python?
Executing command line programs from within python
Getting list of parameter names inside python function
Join a list of items with different types as string in Python
Create empty file using python
Is False == 0 and True == 1 in Python an implementation detail or is it guaranteed by the language?
Is there a way to use PhantomJS in Python?
UnicodeDecodeError: ‘utf8’ codec can’t decode byte 0x9c
How do I filter ForeignKey choices in a Django ModelForm?
I can’t install python-ldap
from ... import vs
import .
Is it possible to make abstract classes in Python?
How to check if a user is logged in (how to properly use user.is_authenticated)?
Python idiom to return first item or None
How to input a regex in string.replace?
How do I increase the cell width of the Jupyter/ipython notebook in my browser?
Parse JSON in Python
Timeout on a function call
How would I specify a new line in Python?
Python str versus unicode
How to get MD5 sum of a string using python?
Python in Xcode 4+?
What do (lambda) function closures capture?
How to count the occurrence of certain item in an ndarray in Python?
UnicodeDecodeError when reading CSV file in Pandas with Python
Shuffle DataFrame rows
How can I use pickle to save a dict?
How do I loop through a list by twos?
Why does datetime.datetime.utcnow() not contain timezone information?
How to rename a file using Python
Install tkinter for Python
Standard way to embed version into python package?
How to take column-slices of dataframe in pandas
How can I see the entire HTTP request that’s being sent by my Python application?
Installing SciPy with pip
‘pip’ is not recognized as an internal or external command
Python creating a dictionary of lists
How to store a dataframe using Pandas
Get a filtered list of files in a directory
Get loop count inside a Python FOR loop
In python, why does 0xbin() return False?
Check if two unordered lists are equal
What can you use Python generator functions for?
When is “i += x” different from “i = i + x” in Python?
Why do we need the “finally” clause in Python?
Find the similarity metric between two strings
“OSError: [Errno 1] Operation not permitted” when installing Scrapy in OSX 10.11 (El Capitan) (System Integrity Protection)
How to use a different version of python during NPM install?
Best way to find the intersection of multiple sets?
How do I create test and train samples from one dataframe with pandas?
Django set default form values
django order_by query set, ascending and descending
How to send POST request?
Python Pandas – Re-ordering columns in a dataframe based on column name
Running Python on Windows for Node.js dependencies
Replace non-ASCII characters with a single space
Check if string matches pattern
What is the global interpreter lock (GIL) in CPython?
Reverse Y-Axis in PyPlot
Named colors in matplotlib
How to install python modules without root access?
Extracting text from HTML file using Python
read subprocess stdout line by line
How do I get the data frame index as an array?
Configuring so that pip install can work from github
Loop backwards using indices in Python?
How to drop a list of rows from Pandas dataframe?
How can I improve my paw detection?
How to replace multiple substrings of a string?
Can’t pickle when using multiprocessing Pool.map()
Python
what do the use of yeild in python ? | http://desiconsultancies.com/tag/python-programming/ | CC-MAIN-2019-26 | refinedweb | 8,607 | 75.1 |
Agenda
See also: IRC log
<DanC> minutes 26 March
RESOLUTION: Minutes approved for last week
SW: No call April 9 -- Easter
Monday
... Norm scribes on April 16
... Noah possible regrets for Apr 16
... Apr 16: Possibly make progress on passwords in the clear
<timbl_> Regrets from Tim for the 16th
<ht>
HT: clarify difference between URIs
and URI references.
... Possible name: Abbreviated URIs 54
<DanC> (I prefer to leave the {abs}ln j clark syntax out of scope of this new issue)
<Norm> {}foo as an expansion of x:foo where xmlns:x="" is in-scope
<Noah> My reference to the Clark syntax is indeed a mistake.
<ht> {abs}ln is an expansion of a QName
<ht> Referred to in XML Namespaces 1.1 as an "expanded name"
<Noah> I'm merely saying that I don't think it's the fact that CURIEs or anything else are smaller that's the issue. It's if they are a nonstandard syntax for URIs.
<Noah> If for some bizarre reason I swapped each pair of characters in a URI, it would be nonstandard but no shorter. Would the issues raised be particularly different?
<ht> No, and we'd let you discuss them under this issue!
<timbl_> AbbreviatedURIs56
<Noah> OK, I just find that the name "abbreviated" suggests that it's the compactness that's the source of trouble, and Dan just said he thinks it is.
SW: summarizes new issue: Abbreviated URIs
RESOLUTION: Open new TAG issue with short name AbbreviatedURIs-56
<DanC> ACTION: DC to respond to with SPARQL QNames and other details [recorded in]
SW: Skipping versioning while we await Dave
SW: 6 TAG members expected to be present
TimBL: Focus on properties of the
Internet layer that are needed to make the Web layer work e.g.
anyone can talk to anyone
... NAT boxes are the root of all evil in the Internet world
... possible audience includes people who are on the line between walled-gardens for mobile and the big Web
SW: Conludes that no one on the TAG
appears interested in leading this panel.
... Ask Danny Weisner?
<Noah> Why does the TAG being involved in something necessary imply an issue or a finding. I think it's very appropriate that we facilitate discussion and fact finding, in part to decide whether there are lurking issues that we should open formally.
<DanC> (skimming [the docs] now, a lot looks familiar; has anybody made a diff?)
<timbl_> Previous version:
<DanC> agenda points to a draft of 26 March 2007,
Dave to give a 10 minute overview
<timbl_> Version numbers for HTML and CSS
DC: versioning coming up in html
HT: where is the material about abstract languages that came up in Vancouver
<timbl_> An unusual form of versioning ;-)
<DanC> this web publishing thing is kinda tricky
<Stuart>
TVR, DC, TBL: all point out that html and css versioning are topics o discussion
<timbl_> 1.1.3
<DanC> (is Dave giving a diff, or summarizing the whole thing?)
sounds like a detailed exposition to me...
<timbl_> The whole thing I think .. he gave an overview of changes when he started
<raman> Document needs to identify different types of extensions: extension points (explicit vs impolicit ) created by language designer; extensions introduced by consuming apps that attach meaning to underspecified portions of a language; and how language designers work in the future in the face of such extensions
<raman> I believe the above approximately captures the situation with html
<raman> we shouldn't work on versioning in the belief that the only person versioning a language is the language designer
<timbl_> Examples I think are needed for each good practcie note, positive and negative.
<raman> microfomats here sticks out as a later addition?
<raman> Note that microformats isn't a new language or language version -- it uses an existing "implicit extension point" of HTML -- the class attribute -- as a payload to hold additional information
<timbl_> +1 to: raman: we shouldn't work on versioning in the belief that the only person versioning a language is the language designer
DO: Switch back to the email
DO: Major differences -- insertions of material pulled from part 1
DO: added some new versioning
strategies . . . version numbers, substitution groups
... other discussion of XML Schema 1.0
... 8 case studies
... XML Schema <redefine>
... [summary of ToC]
<DanC> +1 survey/use-cases. I'd rather the document started with one of those rather than "Terminology"
DO: I'm particularly hoping that the case studies will address a number of outstanding requests for examples
<timbl_> I would find the tables easier if they were 2d matrices with a row for each example.
<Stuart> I wonder whether we need a collection of smaller chunks?
DO: New sections, new organisation - - feedback requested on whether this works, is what people were looking for
SW: Floor open for questions
... How does this work relate to the work in W3C XML Schema - land
DO: Schema WG folks have been looking
at this document, I've been working in the WG to try to improve the
ability of XML Schema 1.1 to be a good language for
versioning
... The "Guide to Versioning in XML Schema 1.1" not quite the same thing, rather, it's focussing on what the new mechanisms are in Schema 1.1
... There's interest in a full-scale "how to version with Schema" document, but I haven't tried to do that
... There's not much overlap with the TAG finding drafts, although some of the use cases are common
RL: Read previous versions of both
docs, and the new version of part one, skimmed new part two
... part two seems to be the thing I as a consumer really need, as I set out to try to design an XML language myself
... Do we have all the best practices in there now -- can we actually provide guidance?a
DO: I started out only caring about
part two -- how to version XML
... The TAG wanted to expand to covering a larger scope, to understand what is meant by language, version, extension
... and this has consumed a lot of effort -- but I hope we're going to get back to the XML part of things
... Wrt 'best practices', that's how we got started, I made concrete suggestions about how XML languages should have extensibility built in
... That surfaced as my two xml.com articles, using the extension element technique, with explicit schemas illustrating this
... But the TAG thought that was too narrow, we need more of a survey of the range of mechanisms and requirements
... Compare UBL, with new namespaces for every change, to DocBook, with no change of namespace ever
RL: Didn't mean to imply there was one right answer, but a clear connection wrt design choices for a language and mechanisms and approaches to extensibility which would be appropriate
DO: Yes, I want to get there --
tempted to give a flow-chart/decision procedure, but my only effort
to do so didn't converge
... Yes, I do intend to combine all the tables together
... But some of the entries are sort of too long for a table-cell. . .
<Zakim> Noah, you wanted to talk a bit about scope and goals
NM: There's convergence in the
sections we've talked about at length -- some more work is needed,
but clear progress
... I'm worried about the logistics of getting this to a consensus-attracting TAG finding
... The whole of WebArch is 49 pages -- part 2 of this doc. is 34 pages, the whole things is close to 80
... Maybe we need to prioritise and select
... Even if we don't, I'm concerned that most of what's there still needs serious attention, and that will take a lot of time
... The scale is, as you pointed out, a consequence of the range of interests within the TAG in this area
... What we really shouldn't do is work hard on improving sections and then deciding to throw a lot out
NM: So that's things for other TAG members to think about as they read this
DO: I agree with all of that -- I've
been concerned as I've been asked to expand this with precisely
that problem
... Language versioning in general, there's a lot of material here -- several PhD theses
... at any rate
DO: I'm happy to keep working on this, but we do all need to know that the work we do will end up being used
<Noah> I think what's happened is: Dave wanted this to be a mainly XML finding. Some of us suggested it should be a mainly non-XML finding. For the moment, that's turned into "let's put everything in there".
<Noah> I don't think that's the whole issue though. Even within the separate parts, I think we may do better to deliver the really key points carefully and clearly, and to leave to others some of the other details.
DO: The thing I don't want to lose is what's needed to answer RL's requirement: What should a language designer do?
SW: So as we read this we need to be assessing its status -- is there a backbone here, from which we can separate a number of smaller, more accessible supplementary documents
DO: [One person's 80 is another person's 20]
TBL: I don't mind the length, as long
as there's a logical and consistent story throughout
... Maybe people only interested in XML will mostly read the 2nd part, and only go back to the 1st part when they hit a problem with terminology
... I'm not sure cutting large chunks out is a good idea -- lots of the bulk is examples -- as long as it's logically laid out, people will focus on the parts that are relevant to them
<Noah> FWIW: my concern is not that it's illogical. It's whether we can find the energy to tune something so long to the quality we need.
SW: So TAG members should all read
the drafts, and send comments by email, with an eye to working on
this at the f2f in May
... As many reviews as possible would be good
TBL, DC: I may have to focus my effort, not cover the whole thing
NM: I just want to be sure that even in part two, we're all happy with recommendations and best practices
SW: Adjourned | http://www.w3.org/2007/04/02-tagmem-minutes | CC-MAIN-2016-22 | refinedweb | 1,745 | 65.56 |
What is CLASSPATH?
The CLASSPATH environment variable is used by Java to determine where to look for classes referenced by a program. If, for example, you have an import statement for my.package.Foo, the compiler and JVM need to know where to find the my/package/Foo class.
What is the purpose of these variables ?
The JAVA_HOME variable is used by other programs to know where your JDK is. Most IDEs will use it. It is also used as a convenient shortcut, to avoid having to change the other places referring to the JDK install directory. For example, we have used it to set the PATH variable (%JAVA_HOME%). This is very convenient, because if you install another version of the JDK, all you need to do is to update your JAVA_HOME, without having to touch the PATH.
Running my first JAVA program.
If you have not installed JAVA before, then goto Oracle Website and download JAVA JDK.
Note, JAVA JDK is essential to compile JAVA code. Lot of Systems have JAVA JRE pre installed which is good enough to run the JAVA programs but it does not have the capability to compile JAVA programs. So you need JDK. These days JRE comes along with the JDK package. So all you need to do is download the latest JDK onto your machine.
Next you need set the path variable. I am using windows, so this is how you set.
control panel -> system – > advance setting -> environment variable – > system variables
select path and add new entry C:\Program Files\Java\jdk1.8.0_91\bin
Once you have done the above step. Open your command prompt and type javac
if that is working then the path variable is set correctly.
Use your favorite text editor to create a new file. You don’t need any advanced IDE like Eclipse or IntelliJ yet.
For the moment, stick to the editor you’re used to. Copy/paste the following code in your editor :
public class MooseGreetings { public static void main(String[] args) { System.out.println("mooooooooooo"); } }
Save the file in the directory of your choice
The filename must match exactly the name of your class.
Compiling the program
At the command prompt, go to the directory where you have saved the MooseGreetings.java file.
C:\>cd \java\src C:\java\src>javac MooseGreetings.java
The class should be compiled, and a new file called MooseGreetings.class should be created in the same directory.
Executing the program
C:\java\src>java -classpath . MooseGreetings mooooooooooo
The –classpath flag (or -cp flag) may be used at the command prompt to tell Java where to look for .class files. In our example, “-classpath .” means that Java should scan the current directory (“.”) for class files. These can be set in the classpath either by setting the CLASSPATH environment variable, or by using the -classpath flag.
Note – I will be adding newer posts with further versions like 2 , 3 etc till i have learned JAVA well. This is my way of making notes.
References:
Head First Java 2nd Edition | https://knowingofnotknowing.wordpress.com/2016/05/07/java-beginers-theory-2/ | CC-MAIN-2018-22 | refinedweb | 508 | 76.22 |
31 32 package org.hsqldb.util;33 34 /**35 * Exceptions thrown by the SqlTool system externally to SqlFile.36 * (As opposed to the nested Exceptions within those classes).37 * This class is misnamed, because it is not only errors.38 * When there is time, this file and class should be renamed.39 */40 public class SqlToolError extends Exception {41 42 public SqlToolError(Exception e) {43 super(e.getMessage());44 }45 46 public SqlToolError(String s) {47 super(s);48 }49 50 public SqlToolError() {51 super();52 }53 }54
Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ | | http://kickjava.com/src/org/hsqldb/util/SqlToolError.java.htm | CC-MAIN-2016-44 | refinedweb | 103 | 60.31 |
This guide will cover how to control motors using the openFrameworks face tracker mode. The motors will be connected to an Arduino and the data processed through the Wekinator software program.
The input data will be transferred from the Wekinator to the openFrameworks platform. The face tracker mode used in openFrameworks will send the x, y, and width measurements of the face detected.
The Wekinator will be trained according to the input values and send the output data to processing—which forwards it to an Arduino that controls the motors.
In this guide, we'll record samples for four outputs:
- For a face that appears in front of the camera.
- For a face that appears to the right of the camera.
- For a face at a certain distance from the camera.
- For objects that appear in front of the camera.
Installing the openFrameworks Face Tracker Mode
The installation file for openFrameworks, as well as the face tracking feature, is available on the Wekinator website.
Image displaying the location of the face tracking download file on Wekinator website.
Once you download the face tracking file, unzip it and run the program. It should activate the computer webcam to track the face of the user.
An example image of the face tracker program using a computer webcam to identify a face.
Processing Instructions
On the processing side, this guide will require using a sketch that will receive the output data from the Wekinator software and forward it to the Arduino.; void setup() { // Starting the serial communication, the baudrate and the com port should be same as on the Arduino side. Serial serial = new Serial(this, "COM10", 115200); sender = new ValueSender(this, serial); // Synchronizing the variables as on the Arduino side. The order should be same. sender.observe("output"); //(); // Converting the output to int type output = int(value); } } void draw() { // Nothing to be drawn for this example }
Connecting DC Motors to the Arduino
The processing sketch will send the output data from the Wekinator to the Arduino, which will control the motors accordingly.
In order to connect the motors to the Arduino, follow the placements in the figure below.
Check out our article detailing How to Send and Receive Data Through the openFrameworks Platform Using Arduino to better understand how openFrameworks communicates with an Arduino.
Schematic of motors connected to an Arduino UNO.
Arduino Code
#include <VSync.h> //Including the library that will help us in receiving and sending the values from processing ValueReceiver<1> receiver; /*Creating the receiver that will receive only one value. Put the number of values to synchronize in the brackets */ /* The below variable will be synchronized in the processing and(115) { //Right digitalWrite(IN1, HIGH); digitalWrite(IN2, LOW); digitalWrite(IN3, LOW); digitalWrite(IN4, LOW); } else if (output == 3) { //Left digitalWrite(IN1, LOW); digitalWrite(IN2, LOW); digitalWrite(IN3, HIGH); digitalWrite(IN4, LOW); } else if (output == 4) { //Stop digitalWrite(IN1, LOW); digitalWrite(IN2, LOW); digitalWrite(IN3, LOW); digitalWrite(IN4, LOW); } }
Using Face Detection in Wekinator
The first step is to launch the Wekinator platform and change the settings to reflect those in the figure below.
- Set the input values to 3.
- Set the output values to 1.
- Assign the output type to "all continuous"
- Leave all other settings in their default format.
In order to enable communication between the Wekinator and openFrameworks platforms, you'll need to download the ChucK programming language, you can do so on the Chuck official website.
For more information on installing and using the Wekinator program, take a look at our guide on How to Get Started with Wekinator.
The Wekinator will receive the 3 inputs from the openFrameworks application, then send 5 different outputs to the ChucK program, which prompts it to produce different sounds.
The 'Create new project' window in the Wekinator software program.
Click on 'Next' and the 'New Project' window will display as shown below.
The 'New Project' window in the Wekinator software program.
Record some tests by placing your face close to the camera. Designate the classifier output value to '1.' You'll also want to record a short sample of this movement.
An example image displaying how the face tracker feature identifies a face close to the camera.
Next, move your face to the right side of the screen and change the classier output value to '2.' Once again, record the movement.
An example image displaying how the face tracker feature identifies a face to the right of the camera.
Then move your face further back from the camera and change the classifier output to '3.'
An example image of how the face tracker feature identifies a face further back from the camera.
The last step is to move out of the camera view entirely. Assign the classifier output to '4.'
An example image of the face tracker feature not identifying a face in the camera view.
Now when you click on the 'Train' then 'Run' buttons, the motors should move according to your position on-camera. | https://maker.pro/wekinator/projects/how-to-connect-a-dc-motor-to-arduino-and-control-it-with-face-detection | CC-MAIN-2019-26 | refinedweb | 828 | 54.12 |
PyTorch Tensor Basics
This is an introduction to PyTorch's Tensor class, which is reasonably analogous to Numpy's ndarray, and which forms the basis for building neural networks in PyTorch.
Now that we know WTF a tensor is, and saw how Numpy's
ndarray can be used to represent them, let's switch gears and see how they are represented in PyTorch.
PyTorch has made an impressive dent on the machine learning scene since Facebook open-sourced it in early 2017. It may not have the widespread adoption that TensorFlow has -- which was initially released well over a year prior, enjoys the backing of Google, and had the luxury of establishing itself as the gold standard as a new wave of neural networking tools was being ushered in -- but the attention that PyTorch receives in the research community especially is quite real. Much of this attention comes both from its relationship to Torch proper, and its dynamic computation graph.
Image source.
Tensor (Very) Basics
So let's take a look at some of PyTorch's tensor basics, starting with creating a tensor (using the
Tensor class):
import torch # Create a Torch tensor t = torch.Tensor([[1, 2, 3], [4, 5, 6]]) t
tensor([[ 1., 2., 3.], [ 4., 5., 6.]])
You can transpose a tensor in one of 2 ways:
# Transpose t.t() # Transpose (via permute) t.permute(-1,0)
Both result in the following output:
tensor([[ 1., 4.], [ 2., 5.], [ 3., 6.]])
Note that neither result in a change to the original.
Reshape a tensor with view:
# Reshape via view t.view(3,2)
tensor([[ 1., 2.], [ 3., 4.], [ 5., 6.]])
And another example:
# View again... t.view(6,1)
tensor([[ 1.], [ 2.], [ 3.], [ 4.], [ 5.], [ 6.]])
It should be obvious that mathematical conventions which are followed by Numpy carry over to PyTorch Tensors (specifically I'm referring to row and column notation).
Create a tensor and fill it with zeros (you can accomplish something similar with
ones()):
# Create tensor of zeros t = torch.zeros(3, 3) t
tensor([[ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.]])
Create a tensor with randoms pulled from the normal distribution:
# Create tensor from normal distribution randoms t = torch.randn(3, 3) t
tensor([[ 1.0274, -1.3727, -0.2196], [-0.7258, -2.1236, -0.8512], [ 0.0392, 1.2392, 0.5460]])
Shape, dimensions, and datatype of a tensor object:
# Some tensor info print('Tensor shape:', t.shape) # t.size() gives the same print('Number of dimensions:', t.dim()) print('Tensor type:', t.type()) # there are other types
Tensor shape: torch.Size([3, 3]) Number of dimensions: 2 Tensor type: torch.FloatTensor
It should also be obvious that, beyond mathematical concepts, a number of programmatic and instantiation similarities between
ndarray and
Tensor implementations exist.
You can slice PyTorch tensors the same way you slice
ndarrays, which should be familiar to anyone who uses other Python structures:
# Slicing t = torch.Tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Every row, only the last column print(t[:, -1]) # First 2 rows, all columns print(t[:2, :]) # Lower right most corner print(t[-1:, -1:])
tensor([ 3., 6., 9.]) tensor([[ 1., 2., 3.], [ 4., 5., 6.]]) tensor([[ 9.]])
PyTorch
Tensor To and From Numpy
ndarray
You can easily create a tensors from an
ndarray and vice versa. These operations are fast, since the data of both structures will share the same memory space, and so no copying is involved. This is obviously an efficient approach.
# Numpy ndarray <--> PyTorch tensor import numpy as np # ndarray to tensor a = np.random.randn(3, 5) t = torch.from_numpy(a) print(a) print(t) print(type(a)) print(type(t))
[[-0.52192738 -1.11579634 1.26925835 0.10449378 -1.02894372] [-0.78707263 -0.05350072 -0.65815075 0.18810677 -0.52795765] [-0.41677548 0.82031861 -2.46699201 0.60320375 -1.69778546]] tensor([[-0.5219, -1.1158, 1.2693, 0.1045, -1.0289], [-0.7871, -0.0535, -0.6582, 0.1881, -0.5280], [-0.4168, 0.8203, -2.4670, 0.6032, -1.6978]], dtype=torch.float64) <class 'numpy.ndarray'> <class 'torch.Tensor'>
# tensor to ndarray t = torch.randn(3, 5) a = t.numpy() print(t) print(a) print(type(t)) print(type(a))
tensor([[-0.1746, -2.4118, 0.4688, -0.0517, -0.2706], [-0.8402, -0.3289, 0.4170, 1.9131, -0.8601], [-0.6688, -0.2069, -0.8106, 0.8582, -0.0450]]) [[-0.17455131 -2.4117854 0.4688457 -0.05168453 -0.2706456 ] [-0.8402392 -0.3289494 0.41703534 1.9130518 -0.86014426] [-0.6688193 -0.20693372 -0.8105542 0.8581988 -0.04502954]] <class 'torch.Tensor'> <class 'numpy.ndarray'>
Basic Tensor Operations
Here are a few tensor operations, which you can compare with Numpy implementations for fun. First up is the cross product:
# Compute cross product t1 = torch.randn(4, 3) t2 = torch.randn(4, 3) t1.cross(t2)
tensor([[ 2.6594, -0.5765, 1.4313], [ 0.4710, -0.3725, 2.1783], [-0.9134, 1.6253, 0.7398], [-0.4959, -0.4198, 1.1338]])
Next is the matrix product:
# Compute matrix product t = (torch.Tensor([[2, 4], [5, 10]]).mm(torch.Tensor([[10], [20]]))) t
tensor([[ 100.], [ 250.]])
And finally, elementwise multiplication:
# Elementwise multiplication t = torch.Tensor([[1, 2], [3, 4]]) t.mul(t)
tensor([[ 1., 4.], [ 9., 16.]])
A Word About GPUs
PyTorch tensors have inherent GPU support. Specifying to use the GPU memory and CUDA cores for storing and performing tensor calculations is easy; the
cuda package can help determine whether GPUs are available, and the package's
cuda() method assigns a tensor to the GPU.
# Is CUDA GPU available? torch.cuda.is_available() # How many CUDA devices? torch.cuda.is_available() # Move to GPU t.cuda()
Related:
- WTF is a Tensor?!?
- Getting Started with PyTorch Part 1: Understanding How Automatic Differentiation Works
- A Simple Starter Guide to Build a Neural Network | https://www.kdnuggets.com/2018/05/pytorch-tensor-basics.html | CC-MAIN-2021-17 | refinedweb | 974 | 66.13 |
View License
Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.
» Watch video
Join the 15-year community celebration.
Play games and win prizes!
» Learn more
by
Patrick Mineault
Patrick Mineault (view profile)
8 files
136 downloads
4.82381
30 Apr 2011
(Updated
13 Nov 2012)
writes fully valid MEX .cpp files including mexFunction boilerplate based on numeric C/C++ snippet
|
Watch this File
mexme automates the process of writing MEX files. You give mexme a snippet of C which just does numeric computations, as well a list of arguments, and it generates a valid MEX .cpp file. The generated code compiles in Linux (gcc) and in Windows (Visual Studio C++). New in version 1.1, it writes tedious input and output validation code for you. This way you can write a MEX file without manually coding calls to mx* API functions. It's inspired by SciPy's weave function.
Example: translate this piece of (non-vectorizable) .m code that applies a recursive filter into C:
function [y] = myrecursivefilter(x,alpha)
y = zeros(size(x));
y(1) = x(1)*alpha;
for ii = 2:length(x)
y(ii) = y(ii-1)*(1-alpha) + x(ii)*alpha;
end
end
Step 1: Write myrecursivefilter.csnip which does the same thing as the m file:
y[0] = x[0]*alpha;
for(mwSize i = 1; i < x_length; i++) {
y[i] = x[i]*alpha + y[i-1]*(1-alpha);
}
Step 2: Define arguments to your function (in Matlab):
inputargs = [InputNum('x'),...
InputNum('alpha',true,true,'double','alpha > 0 && alpha < 1)]; %scalar
%The last condition
outputarg = OutputNum('y','x_length,1');
Step 3: Generate a fully fledged .c file that can be compiled with mex:
cfile = mexme('myrecursivefilter.csnip',inputargs,outputarg)
writefile('myfilt.c',cfile);
mex myfilt.c
x = randn(1e6,1);
y = myfilt(x,.1);
plot([x,y])
cfile =
/*#include and #define not shown*/
#include "mexmetypecheck *x_ptr = prhs[0];
const mwSize x_m = mxGetM(x_ptr);
const mwSize x_n = mxGetN(x_ptr);
const mwSize x_length = x_m == 1 ? x_n : x_m;
const mwSize x_numel = mxGetNumberOfElements(x_ptr);
const int x_ndims = mxGetNumberOfDimensions(x_ptr);
const mwSize *x_size = mxGetDimensions(x_ptr);
const double *x = (double *) mxGetData(x_ptr);
const mxArray *alpha_ptr = prhs[1];
if(mxGetNumberOfElements(alpha_ptr) != 1)
mexErrMsgTxt("Argument alpha (#2) must be scalar");
const double alpha = (double) mxGetScalar(alpha_ptr);
if(!(alpha > 0 && alpha < 1))
mexErrMsgTxt("Argument alpha (#2) did not pass test \"alpha > 0 && alpha < 1\"");
mwSize y_dims[] = {x_length,1};
plhs[0] = mxCreateNumericArray(2,y_dims,mxDOUBLE_CLASS,mxREAL);
mxArray **y_ptr = &plhs[0];
double *y = (double *) mxGetData(*y_ptr);
/*Actual function*/
#include "myfilt.csnip"
}
For every argument that you define, mexme generates extra "magic" variables. For example, if the variable is x, then in C:
x is the data
x_m is the size of the first dimension
x_n is the size of the second dimension
x_length is the length of a vector
x_numel is the number of elements in an array
x_ndims is the numer of dimensions
x_size is equivalent to the Matlab code size(x)
x_ptr is a reference to the mxArray that contains the x data
And if x is complex, x_r and x_i are the real and imaginary components of the data.
mexme currently does not support sparse data or non-numeric types but it does support full numeric arrays of any type (int8, single, double, etc.).
Verbatim: Get The Text Of A Block Comment. inspired this file.
This file inspired Fast B Spline Class.
You can run this function under Windows, if you change the file extension from .c to .cpp: In C89 the declarations of variables must be found before the first line of code. Resorting the lines and moving the declaration out of "for(mwSize i; ...)" to the initial block of the code, allows to compile the code created by TestMexMe. But changing the extension enables the C++ style.
Casting the output of mxGetNumberOfDimensions to "int" is a bad programming practice when the code should work reliably in 32 and 64 bit environments, although you will most likely never get an overflow from mwSize values here.
Instead of defining "uint64", "int64", etc in the code, using "uint64_T" etc. defined in the Matlab headers would be more reliably.
This submission is an excellent idea and an excellent documentation. The created code needs some manual tuning, which reduces the usability substantially, if you want to run MexMe in a "fire&forget" mode. But it is really a hard job to generate platform independent code automatically. This submission is useful, but has a two-fold usability between 3 and 5 stars.
You might like to check out: - linking Visual Studio to Simulink.
It was tested with gcc on Linux only. Hard to say what the problem is without the error message.
Awesome! Worked as expected for me in my usual Linux environment. Tried to share with a coworker on Windows who couldn't get the c file mexed. I am not as familiar with the Visual Studio compiler, so I haven't been able to figure it out (we have both successfully mexed files in the past). What compiler was it tested with?
It's updated now.
Sorry, I forgot to include TestMexMe.m in the zip, just uploaded the file, should be there in a day or so.
Added reference to verbatim
Added TestMexMe.m in zip file
Added input/output validation code generation
Added compatibility with Visual Studio and implemented Jan Simon's suggestions
Implemented Jan Simon's suggestions, including compatibility with Visual Studio
Accelerating the pace of engineering and science
MathWorks is the leading developer of mathematical computing software for engineers and scientists.
Discover... | http://www.mathworks.com/matlabcentral/fileexchange/31257-mexme-write-mex-files-in-no-time?requestedDomain=www.mathworks.com&nocookie=true | CC-MAIN-2016-50 | refinedweb | 925 | 55.54 |
Problem: contains the size of the matrix i.e. n * m where n is the number of rows and m is the number of columns.
n lines follow each having a string of size m.
Output :
A single value for the area of the triangle.
Solution :
Since we have one side parallel to the y – axis we will treat this side as the base of the triangle. The area of a triangle can be written as (1 / 2) * base * height. So the problem reduces to maximising the value of the base and the height. We also want that all the vertices should have different values. Lets first consider the task of maximising the base.
pre-computation :
For each column we can find the first and the last occurrence of the value of {r, g, b}. So we will get 2 sets of 3 values. It can be easily seen that if the base is in this column then it must have one vertex from the first set and the second vertex from the second set such that the values are not the same. This can be done in O(n * m).
Given the base of the column now we have to maximise the height. The height of the triangle will be maximum of the distance of this column from the farthest point on the left or the right having value different from the other 2 vertices of the triangle. This farthest point can be calculated in O(n * m) time.
Now the solution can be found by once iterating through all the columns, and for each column calculating the maximum area of triangle that has base in this column, using the information calculated above.
Code:
#include <bits/stdc++.h> using namespace std; #define MAXN 1000 #define MAXM 1000 //contains the first occurrence of the values in the column int Top[3][MAXM]; //contains the last occurrence of the values in the column int Bottom[3][MAXM]; //contains the first occurrence of the values in the row int Left[3]; //contains the last occurrence of the values in the row int Right[3]; vector <string> v; //mapping for easy access int mapping(char ch) { if(ch == 'r') return 0; else if(ch == 'g') return 1; else if(ch == 'b') return 2; } void precompute(int n, int m) { int i, j; Left[0] = MAXM, Left[1] = MAXM, Left[2] = MAXM; memset(Right, -1, sizeof Right); for(i = 0;i < MAXM; ++i) Top[0][i] = MAXN, Top[1][i] = MAXN, Top[2][i] = MAXN; memset(Bottom, -1, sizeof Bottom); //to find out global left and right color values for(i = 0;i < n; ++i){ for(j = 0;j < m; ++j){ Left[mapping(v[i][j])] = min(Left[mapping(v[i][j])], j); Right[mapping(v[i][j])] = max(Right[mapping(v[i][j])], j); } } //to find out top and bottom values for each column for(j = 0;j < m; ++j){ for(i = 0;i < n; ++i){ Top[mapping(v[i][j])][j] = min(Top[mapping(v[i][j])][j], i); Bottom[mapping(v[i][j])][j] = max(Bottom[mapping(v[i][j])][j], i); } } } double maximum_area(int n, int m) { int i, s1, s2, s3; double ans = (double)1; //setting the column for(i = 0;i < m; ++i){ //setting the two vertices in this column for(s1 = 0;s1 < 3; ++s1){ for(s2 = 0;s2 < 3; ++s2){ //finding the third vertex s3 = 3 - s1 - s2; if(s1 != s2 && Top[s1][i] != MAXN && Bottom[s2][i] != -1 && Left[s3] != MAXM){ ans = max(ans, ((double)1 / (double)2) * (Bottom[s2][i] - Top[s1][i]) * (i - Left[s3])); } if(s1 != s2 && Top[s1][i] != MAXN && Bottom[s2][i] != -1 && Right[s3] != -1){ ans = max(ans, ((double)1 / (double)2) * (Bottom[s2][i] - Top[s1][i]) * (Right[s3] - i)); } } } } return ans; } int main() { freopen("input.txt", "r", stdin); cout << "Enter the size of the matrix : \n"; int n, m, i; cin >> n >> m; cout << "Enter the matrix : \n"; for(i = 0;i < n; ++i){ string temp; cin >> temp; v.push_back(temp); } precompute(n, m); cout << "The maximum possible area is : " << maximum_area(n, m); return 0; }
Time Complexity :
O(n * m) | http://www.crazyforcode.com/find-largest-area-triangle-2d-matrix/ | CC-MAIN-2017-26 | refinedweb | 693 | 63.22 |
PSI - Pressure Stall Information¶
- Date
April, 2018
- Author
Johannes Weiner <hannes@cmpxchg.org>
When CPU, memory or IO devices are contended, workloads experience latency spikes, throughput losses, and run the risk of OOM kills.
Without an accurate measure of such contention, users are forced to either play it safe and under-utilize their hardware resources, or roll the dice and frequently suffer the disruptions resulting from excessive overcommit.
The psi feature identifies and quantifies the disruptions caused by such resource crunches and the time impact it has on complex workloads or even entire systems.
Having an accurate measure of productivity losses caused by resource scarcity aids users in sizing workloads to hardware–or provisioning hardware according to workload demand.
As psi aggregates this information in realtime, systems can be managed dynamically using techniques such as load shedding, migrating jobs to other systems or data centers, or strategically pausing or killing low priority or restartable batch jobs.
This allows maximizing hardware utilization without sacrificing workload health or risking major disruptions such as OOM kills.
Pressure interface¶
Pressure information for each resource is exported through the respective file in /proc/pressure/ – cpu, memory, and io.
The format for CPU is as such:
some avg10=0.00 avg60=0.00 avg300=0.00 total=0
and for memory and IO:
some avg10=0.00 avg60=0.00 avg300=0.00 total=0 full avg10=0.00 avg60=0.00 avg300=0.00 total=0
The “some” line indicates the share of time in which at least some tasks are stalled on a given resource.
The “full” line indicates the share of time in which all non-idle tasks are stalled on a given resource simultaneously. In this state actual CPU cycles are going to waste, and a workload that spends extended time in this state is considered to be thrashing. This has severe impact on performance, and it’s useful to distinguish this situation from a state where some tasks are stalled but the CPU is still doing productive work. As such, time spent in this subset of the stall state is tracked separately and exported in the “full” averages.
The ratios (in %) are tracked as recent trends over ten, sixty, and three hundred second windows, which gives insight into short term events as well as medium and long term trends. The total absolute stall time (in us) is tracked and exported as well, to allow detection of latency spikes which wouldn’t necessarily make a dent in the time averages, or to average trends over custom time frames.
Monitoring for pressure thresholds¶
Users can register triggers and use poll() to be woken up when resource pressure exceeds certain thresholds.
A trigger describes the maximum cumulative stall time over a specific time window, e.g. 100ms of total stall time within any 500ms window to generate a wakeup event.
To register a trigger user has to open psi interface file under /proc/pressure/ representing the resource to be monitored and write the desired threshold and time window. The open file descriptor should be used to wait for trigger events using select(), poll() or epoll(). The following format is used:
<some|full> <stall amount in us> <time window in us>
For example writing “some 150000 1000000” into /proc/pressure/memory would add 150ms threshold for partial memory stall measured within 1sec time window. Writing “full 50000 1000000” into /proc/pressure/io would add 50ms threshold for full io stall measured within 1sec time window.
Triggers can be set on more than one psi metric and more than one trigger for the same psi metric can be specified. However for each trigger a separate file descriptor is required to be able to poll it separately from others, therefore for each trigger a separate open() syscall should be made even when opening the same psi interface file.
Monitors activate only when system enters stall state for the monitored psi metric and deactivates upon exit from the stall state. While system is in the stall state psi signal growth is monitored at a rate of 10 times per tracking window.
The kernel accepts window sizes ranging from 500ms to 10s, therefore min monitoring update interval is 50ms and max is 1s. Min limit is set to prevent overly frequent polling. Max limit is chosen as a high enough number after which monitors are most likely not needed and psi averages can be used instead.
When activated, psi monitor stays active for at least the duration of one tracking window to avoid repeated activations/deactivations when system is bouncing in and out of the stall state.
Notifications to the userspace are rate-limited to one per tracking window.
The trigger will de-register when the file descriptor used to define the trigger is closed.
Userspace monitor usage example¶
#include <errno.h> #include <fcntl.h> #include <stdio.h> #include <poll.h> #include <string.h> #include <unistd.h> /* * Monitor memory partial stall with 1s tracking window size * and 150ms threshold. */ int main() { const char trig[] = "some 150000 1000000"; struct pollfd fds; int n; fds.fd = open("/proc/pressure/memory", O_RDWR | O_NONBLOCK); if (fds.fd < 0) { printf("/proc/pressure/memory open error: %s\n", strerror(errno)); return 1; } fds.events = POLLPRI; if (write(fds.fd, trig, strlen(trig) + 1) < 0) { printf("/proc/pressure/memory write error: %s\n", strerror(errno)); return 1; } printf("waiting for events...\n"); while (1) { n = poll(&fds, 1, -1); if (n < 0) { printf("poll error: %s\n", strerror(errno)); return 1; } if (fds.revents & POLLERR) { printf("got POLLERR, event source is gone\n"); return 0; } if (fds.revents & POLLPRI) { printf("event triggered!\n"); } else { printf("unknown event received: 0x%x\n", fds.revents); return 1; } } return 0; }
Cgroup2 interface¶
In a system with a CONFIG_CGROUP=y kernel and the cgroup2 filesystem mounted, pressure stall information is also tracked for tasks grouped into cgroups. Each subdirectory in the cgroupfs mountpoint contains cpu.pressure, memory.pressure, and io.pressure files; the format is the same as the /proc/pressure/ files.
Per-cgroup psi monitors can be specified and used the same way as system-wide ones. | https://www.kernel.org/doc/html/v5.15/accounting/psi.html | CC-MAIN-2022-21 | refinedweb | 1,018 | 54.63 |
Graphing car metrics into the cloud with Raspberry Pi, OBD and Graphite19 Apr 2015
In this post we’ll see how you can grab car sensors data and turn them into some good loking and easy to watch graphs.
Motivation:
I’ve recently changed my car’s stock air filter with a performance one which really improved the car’s responsiveness. While driving back from Romania to Czech Republic I was thinking that this can’t just come for free and I wanted to see how it impacts the car’s working parameters. First thing I noticed has changed was the fuel consumption. Since the car board computer only provides instantaneous and average fuel consumption numbers I can’t really get to do an analysis of how it changed in time. Numbers are good but, at least for me, it’s hard to interpret them as absolute values and I need to get the whole picture where they stand. The first thought that came to mind was to turn metrics like rpm, speed and instantaneous fuel consumption into easy to read graphs. This would at least get me some more insight with historical data of the car’s working parameters.
So there kicked my doer spirit and I started thinking of ways of doing it. What did I need:
- Data source
I knew most of the cars have a diagnosis port called OBD which is used for reading data from most of the existing sensors in your car.
- Data destination
Once I got all the sensor data I needed to graph it somehow. This would be the easiest task since I had already used Graphite before and knew how easy sending the data and getting the graphs done was.
- Data processor
Now that I have the data source and destination I also needed the device that processes/forwards it. I had a Raspberry Pi standing on my desk for 2 or more years without turning it on so I thought that would be the ideal time to start using it.
- Put everything together
At this point we have the system’s individual components but we need to connect them somehow to get functionality out of it. After doing some searches I found out that there were some cheap Bluetooth OBD readers on the market and decided to go with that. Since I was going to use Bluetooth for connecting the Raspberry Pi to the OBD reader I also needed a USB Bluetooth dongle. The last step in getting the system done would be to get the Raspberry Pi connected to Graphite. Since I’m a cloudy guy I’m going to run Graphite on my Openstack lab so this means I’m going to need an Internet connection on the Pi. First thing that came to mind was getting a USB 3G modem. After doing some reading I found out that most of these modems require external power. I wanted to keep cabling as clean as possible by powering the Pi from the car’s USB port so I went for another approach. The solution I came up was to use my phone’s tethering capabilities and get the Pi connected via WiFi. By doing this I also required a USB WiFi dongle.
Diagram of how this is going to work:
Bill of materials:
- Raspberry Pi Model B
- Kingston 32GB SDHC Memory Card Class 10
- MicroUSB cable
- Asus USB-BT400 Bluetooth dongle
- Edimax EW-7811Un WiFi dongle
- Elm327 OBDII Bluetooth Scanner
- 3G Tethering capable phone
Before getting started:
- Get your Raspberry Pi installed.
- Make sure it’s connected via WiFi to the mobile phone
- Find its IP address and connect to it via SSH
- Install graphite and grafana. You can use these Ansible roles here:
TL;DR. Let’s get started:
- Connect the OBDII reader to your car
- Log in by SSH to the Pi
- Discover the OBDII mac address or read it from the case:
hcitool scan Scanning ... 00:0D:18:00:00:01 OBDII
- Add the MAC address to the Bluetooth conf file.
cat /etc/bluetooth/rfcomm.conf rfcomm99 { bind yes; device 00:0D:18:00:00:01; channel 1; comment "ELM327 based OBD II test tool"; }
- Write init script that will manage the Bluetooth connection through the /dev/rfcomm99 device.
cat /etc/init.d/elm327 #!/bin/bash ### BEGIN INIT INFO # Provides: elm327 # Required-Start: # Required-Stop: # Should-Start: # Should-Stop: $null # Default-Start: 3 5 # Default-Stop: 0 1 2 6 # Short-Description: Start elm327 # Description: starts the elm327 bluetooth device ### END INIT INFO DevNum=99 # DevNum is depending on the rfcom settings /etc/bluetooth/rfcom.cfg case $1 in start) rfcomm bind $DevNum ;; stop) rfcomm release $DevNum ;; status) rfcomm show $DevNum ;; *) cat<<EOF Usage: $0 [ start | stop | status ] EOF esac
- Create the device by running the init script
sudo /etc/init.d/elm327 start
- Install obd python module via pip
sudo pip install obd
- Write a script that reads sensor values and sends them to the graphite instance:
import platform import socket import time import obd CARBON_SERVER = 'graph.remote-lab.net' CARBON_PORT = 2003 DELAY = 2 # secs def send_msg(message): # print 'sending message:\n%s' % message sock = socket.socket() sock.connect((CARBON_SERVER, CARBON_PORT)) sock.sendall(message) sock.close() def get_rpms(): cmd = obd.commands.RPM response = connection.query(cmd) return response.value def get_speed(): cmd = obd.commands.SPEED response = connection.query(cmd) return response.value if __name__ == '__main__': node = platform.node().replace('.', '-') connection = obd.OBD("/dev/rfcomm99") while True: timestamp = int(time.time()) rpms = get_rpms() speed = get_speed() lines = [ 'system.%s.rpm %s %d' % (node, rpms, timestamp), 'system.%s.speed %s %d' % (node, speed, timestamp), ] message = '\n'.join(lines) + '\n' send_msg(message) time.sleep(DELAY)
- Run the script and you should start seeing the metrics graphed by Graphite. I’m using Grafana as a Graphite frontend and here’s how the graphs look like after a ride:
You can see that I only captured the RPM and speed sensor. The equation for calculating the instantaneous fuel consumptions includes a sensor that seems to be missing from my car or at least I don’t know how to read it. I need to dig further to see how I can get it.
I think this is a great example that demonstrates how easily you can leverage a physical measurement by software today. I really like it mostly because I have a general feeling that during our lifetime we could be missing important bits just because we’re not analyzing enough the world around us. As humans we have a limited set of receptors(sensors) and I guess making use of the available compute power on a general scale might at least show us some unknown patterns in the world arounds us.
- Live demo: | https://remote-lab.net/raspberry-pi-car-automation | CC-MAIN-2018-17 | refinedweb | 1,123 | 60.65 |
11-16-2011 06:48 PM
Hi,
We use JavaScript to create encryption module. It was working without issue until recently it was not working in Blackberry OS 7 (tested on Blackberry Bold Touch 9900). It was not throwing error but was generating encryption result that was unable to be decrypted in the server side. We have tested with old Blackberry browser (BB Bold 9700 running OS5) & it was working. We try to install BOLT browser in BB OS 7 device & the encryption also working there. So the issue is isolated to default browser in BB OS 7.
After debugging session by comparing the result from other browser to BB OS 7 browser, we found that the result is different because BB OS 7 browser sometime will generate different result for SHIFT RIGHT (>>) operation compared to other browser (tested in IE8 & Chrome).
Based on the snippet below:
/* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ function safe_add(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF); var msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); }
When passed with the following value x = -271733879 & y = -2160220835
Both browsers generate same value for lsw variable = 86246
Both browsers generate same value for (x >> 16) = -4147
BB OS 7 Browsers generate different value for (yy >> 16). BB = -32768 but other browser = 32573
Both browser generate same value for (lsw >> 16) = 1
Because of this both browser generate different value for msw variable & subsequently the return value.
Is this a bug in default browser for BB OS 7? If yes, any possible workaround for this? NOTE: the encryption logic use shift right in many place.
Thanks,
Willy
Solved! Go to Solution.
11-24-2011 03:16 PM
Hi Willy,
I've done a quick test with the sample you provided . Testing on my 9900 with 7.1, the result for y >> 16 was 32573; this was the same result as in my Firefox browser.
I'm loading up some 7.0 devices to see the behaviour there and was hoping you could confirm the exact OS version you are running (obtainable via: Options > Device > About Device Versions.)
If this is reproducible on that same 7.0 version, it very well looks to be an OS/Browser issue. The fact that I see the correct result on 7.1 makes me hopeful that this will have already been addressed in newer versions of 7.0 as well, but we'll need to do a few tests to double-check.
Erik Oros
BlackBerry Development Advisor
11-24-2011 03:28 PM
I confirmed also on a 9810 and 9930 running 7.0 and received consistent (good) results on both devices. Specifically, y >> 16 resulted in 32573 on both devices.
I have a hunch that this will only be an issue on the 9900 up to a certain OS version after which it will be fixed. If you can confirm your specific OS version I see if I am able to reproduce the issue.
Erik Oros
BlackBerry Development Advisor
11-24-2011 07:51 PM
Hi Erik,
Thanks for the reply. My BB version (from About window) are:
Blackberry 9900 (3G, WiFi)
7.0 Bundle 1346 (v7.0.0.261, Platform 5.0.0.464)
3G Bands 1,2,5.6
Cryptographic Kernal v3.8.7.0
11-25-2011 11:03 AM
Hello again,
I didn't have a 9900 running 7.0 available, however I did test on a 9930 running 7.0, Bundle 1346 and the value for y >> 16 resulted in -32768.
So it does appear that this is an OS issue on Bundle 1346, however has been resolved on a subsequent 7.0 OS.
Depending on your carrier, a newer version than Bundle 1346 may be available. The best recommendation at this point would be to grab the newest release available at the following URL and test with that:
For instance, Verizon has Bundle 1739 available; but this will be dependant on the carrier.
I did test Bundle 1739 myself and still saw -32768 returned for y >> 16, so there is the possibility that the fixed OS version has not been accepted by carriers yet.
As a workaround, I was able to write:
var yrshift = y >> 16;
As the following instead:
var yrshift = (y & 0xFFFF0000) / 65536;
In essence this does the same thing; takes the top 16-bits and shifts 16 bits to the right (2^16 = 65536.) With this approach, I receieved the correct value 32573 on Bundle 1739 and believe this would also work on the earlier versions.
If a new OS does not resolve your issue, or you require this functionality on the identified broken OS versions, the above should hopefully meet your needs.
Erik Oros
BlackBerry Development Advisor
11-27-2011 10:23 PM
11-27-2011 11:21 PM
Hi Erik,
I think the workaround works for >>> (Shift Right Zero Fill) operator but not for >> (Shift Right with Sign) operator. For >> operator need to add "| 0xFFFF0000" to fill as per the sign value if value in decimal < 0.
However I just notice that -2160220835 is not a valid 32-bit integer value. Most likely this is the reason why the calculation was orignally wrong.
Thanks,
Willy
11-28-2011 02:46 AM
Hi Erik,
I created this workaround based on the assumption that the error only occured if we use >> on a value that is > 32 bit integer range.
<script> function ShiftRight(x, noOfBits) { return (x >> noOfBits); } var powerOfTwo = [ 0x00000001, 0x00000002, 0x00000004, 0x00000008, 0x00000010, 0x00000020, 0x00000040, 0x00000000400000, 0x00800000, 0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000, 0x20000000, 0x40000000, 0x80000000 ] var bitMaskArray = null; function ShiftRight2(n, noOfBits) //NOTE: int must be 32-bit so max noOfBits = 32 { if (bitMaskArray == null) { bitMaskArray = new Array(32); for(i = 0; i < 32; i++) { if (i > 0) { bitMaskArray[i] = bitMaskArray[i-1] + powerOfTwo[i]; } else { bitMaskArray[i] = powerOfTwo[i]; } } } if (n >= -2147483648 && n <= 2147483647) //if within normal 32-bit range just use the same logic (FASTER & MORE RELIABLE) { return (n >> noOfBits); } else { if (noOfBits < 32) { return ( ((n & (~bitMaskArray[noOfBits-1])) / powerOfTwo[noOfBits]) //as >> n basically can be read as faster way to do "1/(2^noOfBits)" that's why the clean up result; (n & (~bitMaskArray[noOfBits-1]) will remove the low digit value so that the divide result will always be integer value | ((n&powerOfTwo[31])==(powerOfTwo[31])?(~bitMaskArr>
I will test this logic & see whether still got problem with BB OS7 earlier build. Once the good OS7 build is fixed, by right it should be reverted to the old function.
11-28-2011 04:15 AM
12-14-2011 03:44 AM
Hi Erik,
Currently I am facing the similar problem. And after doing some investigation we found out that the result of the shift right operator was different when performing shift right operator (>>) by using variable.
If passing the value directly the result will be the same with other browser.
Following is the code snipped that used for testing:
var y = -2160220835;
alert('A: ' + (y>>16));
alert('B: ' + (-2160220835>>16));
the result:
A: -32768
B: 32573 (same with other browser)
Is there any suggestion to fix this issue and I wonder would it be possible to know whether the behavior will impact the other operation or not?
Thank you and regards,
Teguh | http://supportforums.blackberry.com/t5/Web-and-WebWorks-Development/Blackberry-OS7-JavaScript-shift-right-gt-gt-operator-issue/m-p/1430863 | CC-MAIN-2014-10 | refinedweb | 1,224 | 69.21 |
im_flood, im_flood_blob - flood a area
#include <vips/vips.h> int im_flood( im, x, y, ink, dout ) IMAGE *im; int x, y; PEL *ink; Rect *dout; int im_flood_blob( im, x, y, ink, dout ) IMAGE *im; int x, y; PEL *ink; Rect *dout;
im_flood() fills an enclosed area from a starting point, painting ink into 4-way connected pels whose colour is not equal to ink. im_flood_blob() floods with the ink colour, finding pels 4-way connected to the start pel which are the same colour as the start pel. It is useful for changing the colour of a blob of pels which all have the same value.
All functions return 0 on success and -1 on error.
im_insertplace(3), im_smudge(3). 30 October 1992 IM_FLOOD(3) | http://huge-man-linux.net/man3/im_flood_blob.html | CC-MAIN-2017-17 | refinedweb | 125 | 85.32 |
I'm trying to build a method that queries a SQL table and assigns the values it finds to a new list of objects. Here's a quick example of how it works (assume the reader and connection are set up and working properly):
List<MyObject> results = new List<MyObject>();
int oProductID = reader.GetOrdinal("ProductID");
int oProductName = reader.GetOrdinal("ProductName");
while (reader.Read())
{
results.Add(new MyProduct() {
ProductID = reader.GetInt32(oProductID),
ProductName = reader.GetString(oProductName)
});
}
MyObject
if
DbNull
if
ProductID = reader.GetInt32(oProductID) ?? null,
ProductName = reader.GetString(oProductName) ?? null
string
Operator '??' cannot be applied to operands of type 'int' and '<null>'
string
int
if
Null from a database is not "null", it's DbNull.Value. ?? and ?. operators won't work in this case. GetInt32, etc. will throw an exception if the value is null in the DB. I do a generic method and keep it simple:
T SafeDBReader<T>(SqlReader reader, string columnName) { object o = reader[columnName]; if (o == DBNull.Value) { // need to decide what behavior you want here } return (T)o; }
If your DB has nullable ints for example, you can't read those into an int unless you want to default to 0 or something like. For nullable types, you can just return null or default(T).
Shannon's solution is both overly complicated and will be a performance issue (lots of over the top reflection) IMO. | https://codedump.io/share/ZPtwuqT7rSu8/1/inline-null-check-for-sqldatareader-objects | CC-MAIN-2016-50 | refinedweb | 229 | 50.43 |
C|Net haspublished a
story about the recent release of KDE 3.1, with a focus on the Kroupware project. Other new features
particularly beneficial for those considering rolling KDE out in an enterprise
setting are mentioned as well, including remote desktop administration, KDE's kiosk framework and the KHTML improvements that made their way into KDE as result of the cooperation with Apple.
Has anyone else had stability problems with Konqueror? It worked fine for me with Release Candidate 6, but the final 3.1 crashed twice while I was giving it a test-drive.
I think Apple's improvements should have all gone into 3.1, or they should have all waited until the next release. I suspect the partial port is what's causing the problems.
> Has anyone else had stability problems with Konqueror? It worked fine for me with Release Candidate 6, but the final 3.1 crashed twice while I was giving it a test-drive.
Nope. It's been rock solid for me. I had rc5 on one machine and rc6 on the other. They both have 3.1 final now and one khtml crash on rc5. These systems get a fair amount of use in our home business day and night.
> I think Apple's improvements should have all gone into 3.1, or they should have all waited until the next release. I suspect the partial port is what's causing the problems.
Suspect all you want... but compiling with --enable-debug and pointing to it is a lot better than wild speculation. Unfounded rumors start with wild speculation. A good question is if you compiled it yourself, what your optimizations are and so on, or was it precompiled in an RPM. In my experience both supporting my network, friends and thousands of users RPM packages can sneak in some nasty bugs. Even Mandrake and SuSE have released some real duds on new version releases.
FYI mine is built with Gentoo for my processor with mild optimizations using gcc 3.2.1. I typically have tabbed browsers on several of my 12 desktops at any time. Hats off to Dirk and the rest of the guys! KDE 3.1 is awesome!
Very stable here since rc6.
Derek
I have with rc5,6 and 3.1 but only when using it as a filemanager.
Well, Konqueror looks less stable on my system, somehow KHTML is not loaded, calling DOCP does not work properly.
Must be the rpm's of SuSE I installed, will check later if they have updated packages, or compile it myself :o)
Rinse
The SuSE 8.1 RPMs for 3.1 work fine for me. I noticed a real speed increase over the RPMs shipped with 8.1. Also 3.1 is stable for me. No crashes yet on my two systems: the one mentioned and a SuSE 8.0 system on which I compiled from sources with the default konstruct settings.
Some annoying bugs that had me worried in rc6 have gone.
In my opinion 3.1 is pretty stable and I haven't found any really annoying bugs.
Hi everybody,
I had stability problems with konqueror since 3.0 (I thought), but in the end it all boiled down to kbear. I never had kbear running smoothly, and it attaches itself to konqueror when installed (or its sitemanager does...). So, I had regular crahses when opening a new windows by clicking a link with the middle mouse button. But after removing kbear it runs without a hickup. So you might want to check whether you have kbear installed.
My system is SuSE 8.1 running the rpms from, the system also runs WinXP via vmware and is normally up from Mon 8:00 to Fri 18:00, with quite a bit of load to handle.
Cheers
NoName
yeap, i also had RC5 before and it worked just fine, but the crashed several times since i installed it ...
also some programs that compiled and ran fine under RC5 don't compile any more or crashes. also kget doesn't work.
.costin
correction : ... but the *final version* crashed ....
Kroupware is really a horrible name. I know that it is only a project name and not supposed to be a final name, but now that it gets reviewed by major news sites it is important to change the name.
There was some discussion on the dot about the final name of the project recently. Just take the 10 best proposals from there and let the dot.kde.org users choose the winner. Or make a poll at kde-look.org. Or pick one at random.
*Everything* is better than Kroupware.
Please note that this is meant as constructive criticism. I downloaded the 3.1 release and I am extremely happy with it. But names are more important than most developers think.
regards,
A.H.
The Server is called Kolab and so is the client (for the time Kroupware Projekt). The Clinet application that will go into KDE 3.2 is called Kontact.
So what we end up with is Kolab Server and Kontact client. No more Kroupware.
Cheers,
Daniel
> So what we end up with is Kolab Server and Kontact client. No more Kroupware
I guess the server doesn't depend on KDE. Does the name then have to start with "K" ?
Bye
Alex
Why should it have to start with a K? Other KDE apps (like Noatun and Quanta) dont. It is just a tradition and makes it easier to categorize apps.
If this whole K-naming is going to continue, it would make sense if the icon search dialogs sorted by the second initial letter. As it is, finding an icon for say, KOffice, is quite irritating. You type 'k' which will take you to the beginning of the K icons, which is basically all of them. Typing in 'o' moves you to the icons that begin with 'o'.
Hmm......... are you sure? For file/icon selectors in KDE, I have always been able to type the entire name of the file to find it if it's there (not that you really need to go beyond the first few letters). Koffice is a bad example in itself, since there is no "koffice" icon (only kword, kspread, etc), so as soon as you type the first "f" it goes to "f" icons. For me, though, getting the kword icon is as easy as K-W-O :)
I think you're thinking the wrong way round here.
Not all kde apps start with a K, and reversely, we have no reason to forbid non-kde apps from starting with a K :)
Kolab comes from Kollaborieren which is German for Collaborate.
Nothing to do with K==KDE indeed.
And then: I don't see people complain about the 'x' in xteddy, xpinguin, xbill, xedit, xless, xgamma, xbanner ... It's a kind of namespace identifier, and helps to avoid name clashes.
(Gnome will never let any of their programs start with a 'k'. ;-)
Hi All
Well I myself have had a couple of crashes on SuSE Professional 8.1, using RPMs as my install approach. Personally though I think this is very good.
My use of Konqueror is extreme, it is open by default at all times on Desktop 1 as a file manager, and on Desktop 2 & 3 as a web browser, for remote administration tasks and also local development testing. This means on average that Konqueror is up and running for anything between 14 & 18 hours day in day out, 2 crashes to me given that sort of use equals ROCK SOLID (Hell even rocks break sometimes !! ).
A very very BIG thank you to all of the KDE developers, 3.1 has a damned near perfect balance of new features and massive bug fixes right across the application spectrum.
I am very impressed and immensly grateful to you all, also I must just say Quanta team keep it up it is getting better and better. I now use it as my default Code editor, but I will admit I still use Dreamweaver MX for layout and management..
Much respect and gratitude
Paul
>.
There is some support for meta data already. You can read and manipulate (as possible) meta data of all kinds of fileformats through a generic interface. You can't attach any kind of metadata to any kind of file yet, tho. Currently, you can utilize some fileformat's structures, like Jpeg EXIF data, mp3 ID3 tags etc.
Attaching data to any kind of file requires support in the filesystem (see lengthy discussions on lists.kde.org, kde-look).
It crashes and you call it ''rock solid''. Now what does that tell us about the state of software?
That's great!
The German government now funds two projects, Ägypten () and Kroupware. Maybe some parts of the German government will switch their Desktops to KDE, when both projects are finished.
Many parts of the Ägypten project have actually been merged into the Kroupware project. It is from Ägypten that KMail now has SMIME support.
Hi everybody!
The C|Net article claims that "the first elements [of Kroupware] have appeared in the new KDE 3.1"[1]. That's (unfortunately) wrong. As you can check yourself cvs was "frozen for feature commits that are not listed in the planned-feature document"[2] on July 1, 2002 while the Kroupware "project began in September."[1]. So it wasn't possible to include anything from the Kroupware project in KDE 3.1.
In particular the article claims:
"Two elements of the client work are in the new KDE 3.1, released Tuesday: the KMail software can handle encrypted e-mail attachments, and the KOrganizer calendar software can communicate with Exchange 2000 servers."
Both elements are not part of the Kroupware project.
The KMail improvements, i.e. support for PGP/MIME (RFC 3156) and S/MIME, were made by the Ägypten project[3] (which incidentally also was ordered by Germany's agency for information technology security).
The KOrganizer plugin[4] for connections to Microsoft Exchange 2000® servers was written by Jan-Pascal van Best completely independant of the Kroupware project.
Anyway, you can all look forward to KDE 3.2 which will include most (if not all) of the client side elements of the Kroupware project.
Regards,
Ingo
[1]
[2]
[3]
[4]
I tested KDE 3.1 from RC5 through current and konqueror still doesn't honor nowrap in elements. I would think that this is important. I have voted for a bug report that was submited to bugs.kde.org and 4 other people have also voted for this. The real kicker (no pun intended) is that this is a backward step from KDE 3.0, it works just fine with nowrap. Not having this makes some webpages just plain unusable. Please read the bug report and test for yourself, you will see what I mean.
Thank you.
Bret.
Reference:
How about using instead?
That does not work.
Anyone tried this site :
To look up a telephonenumber it is requiered to start
the name and the placename with a capital , but konqueror
seems to inetrpret the pressing of the shift-key is an "enter-key",
all other browsers work fine with this site.
Next problem site:
It is not capable of rendering it correctly , all other browsers do.
These are only a few examples of the many usefull sites in the Netherlands
that simply don't render/work correctly in konqueror while mozilla, phoenix opera etc. do a fine job of rendering them. What's wrong with konqueror??
I had none of your problems when visiting these two sites.
Can you tell what exactly doe not work on the second one ?
The first one worked well, what's wrong with your KDE install ?
My mistake, you are right ...
The second site doesn't render completely in konqueror.
Only the background comes up.
1. Page checked by w3c-validator as html 4.01 Transitional: 324 HTML-Errors in 780 lines, wow!
2. Page as html 4.01 Frameset, 28 HTML-Errors in 33 lines (Frameset only)
This pages are extremely broken. | http://dot.kde.org/comment/36085 | CC-MAIN-2014-10 | refinedweb | 2,027 | 75.4 |
From: Steven Watanabe (watanabesj_at_[hidden])
Date: 2008-02-05 01:35:25
AMDG
Gennadiy Rozental wrote:
> The formal review of Logging library, proposed by John Torjo, begins today and
> will run till Feb 13:
>
Here's part 1 of my review from reading the docs only.
More to follow after I look through the implementation.
in main_intro.html there is a line that says
Click to see the code
which sounds like it ought to be a link but isn't.
scenarios_code.html#scenarios_code_mom:
I don't think that write is the correct name:
g_l()->writer().write("%time%($hh:$mm.$ss.$mili) [%idx%] |\n", "cout
file(out.txt) debug");
This doesn't write anything. It seems like this should be
called something more like set_format_and_destination()
I don't like the idea of two stage initialzation implied by
g_l()->mark_as_initialized();
Is there any way that the initialization can be done where
the log is defined?
Concepts as Namespaces:
I strongly dislike this way of expressing it. What you mean is
that you put implementations of that concept in a specific
namespace. The concept, per se, has no relation to the namespace.
This description is very misleading, IMO.
What does the suffix ts stand for? Oh. I see. Thread Safety.
Could this be spelled out completely? It's not going to appear
all over the code so there is no reason to make the name as short
as possible.
boost::logging::formatter::idx:
Please! don't abbreviate this. "index" is only *two* characters longer.
Workflow.html:
You'll use this when you want a optimize string class. Or, when using tags
s/optimzed/optimized/
s/a/an/
Is there a way to have destination specific formatters?
Throughout the docs some #include's directives are links to the
corresponding headers and other are not.
I find the use of preprocessor directives vs. templates for customization
not very intuitive. For example, the options controlling caching are
macros.
I'm not convinced that this should be a global setting. The fast and
slow compile time options make sense I think because they are
transparent to the user. (BTW, would I need to #ifdef out the
#include <boost/logging/format.hpp> to have the compile times improve?)
AT the bottom of macros.html:
#define BOOST_LOG_TSS_USE_CUSTOM = my_thread_specific_ptr
The "=" is wrong I think.
If BOOST_LOG_NO_TSS is defined is it an error to use the
thread-specific-storage filters?
filter::debug_enabled/release_enabled: How is debug/release determined.
NDEBUG?
in namespaceboost_1_1logging_1_1manipulator.html there is
a reference to destination::shared_memory - writes into shared
memory (using boost::shmem::named_shared_object) is this obsolete?
namespaceboost_1_1logging_1_1manipulator.html#manipulator_share_data:
It doesn't look like the example here will compile.
Second, is there any particular reason not to use shared_ptr directly?
structboost_1_1logging_1_1manipulator_1_1is__generic.html:
I'm don't understand the reference to the template operator=.
namespaceboost_1_1logging_1_1formatter_1_1convert.html
"explain that you can extend the following - since they're
namespaces!!! so
that you can "inject" your own write function in the
convert_format::prepend/or
whatever namespace, and then it'll be automatically used!"
I'm almost certain that this is wrong. In order to be found by a template
the overloads need to be declared by the point where the template is
defined,
although if I remember correctly not all compilers implement this correctly.
If you're going to rely on overloading for customization do it
via ADL.
Concepts:
For the following concepts I either couldn't figure them out
or had to hunt all over the documentation. This information
should be specified in the Concepts section
Filter: There is some way to get a boolean out of a filter. All the
details are
specified by the logging macro.
Level: I can't figure out from the documentation what I would need to do
to model this concept.
Writer: Seems to be a specialization of a Unary Function Object?
Scenario: This doesn't seem like a concept. I'm a little confused now.
In addition I don't understand why ts and usage are disjoint.
There seems to be significant overlap between the two. Is there
any way that they could be merged?
Gather: What exactly are the requirements? The docs say "a function
that will
gather the data - called .out()" What are the requirements on the
return type? Further in scenarios_code.html#scenarios_code_mon
there
is the definition void *out(const char* msg) { m_msg = msg;
return this; }
Is out() called implicitly or not? Why is "this" returned as a
void*?
Confused...
Tag: The only requirement on a tag is that it must be CopyConstructable
(Is it
Assignable, too?). tag::holder is a effectively a fusion::set of tags.
It's not clear from either the tag or holder documentation how to
extract
tags in a formatter.
One final comment about the Concepts:
Manipulators: I think this framework is overly complex. It would be
better to
make manipulators Equality Comparable Unary Function Objects.
In the case of destinations the return type is ignored, for
for formatters, the result type should be the same as the
argument
type. For both the argument type is determined from the
logger.
You can use type erasure to allow them to be treated
polymorphically
at runtime.
In Christ,
Steven Watanabe
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk | https://lists.boost.org/Archives/boost/2008/02/132994.php | CC-MAIN-2021-39 | refinedweb | 886 | 59.3 |
Introduction: Home Made - One Hand - Nitrox Analyser Arduino Based
Hello readers,
In this instructable, I will show you how I built this Arduino based oxygen analyser.
*** WARNING - This is the kind of material that can be used to control your dive mix composition. Diving may be dangerous and everything you do with this is at your own risk. ***
This note is composed of two parts
1) I will describe how I built the box, because building a circuit on a breadboard is one thing, building a finished product is another one.
2) I will provide you the source code
Every parts I used are available on Ebay, from China or Hong Kong.
Here is the details of what I used :
- 9V battery (IKEA one because i like the color)
- 9V battery connector
- PVC enclosure.
> after thinking a lot, I found one in wich the battery can enter and is "naturally locked" by its dimension
- Arduino board
- LCD display
- Two switch.
One for on/off.
Push to set the new mix to 21%. It must be "push and release"
- One oxygen sensor
- A cable to connect your oxygen sensor (here it terminate by a jack plug)
- ADS1115 to convert mV provided by the sensor to digital signal.
- Cables
Step 1: Display
The display is connected using a "Dupont" cable.
It is glued on the box cover
I used some "plastic foam" (the kind of stuff widely used to protect electronic component during post transfer). I cut a small part of it, glued it on the LCD and on the box cover.
This is working very good.
Step 2:
The box contains an ADS1115 with convert millivolt to digital signal. It is connected to the sensor via a jack audio cable.
Two button : one to switch the system on/off.
The second (the red one), once pressed, will set the system 21% oxygen.
The system automatically calibrates on 21% when started.
*** HOW DOES IT WORK - DETAILS***
In fact when there are no oxygen, the sensor delivers 0mV
When started, the system consider it is in 21% oxygen, measure the mV (let call it x ) provided by the sensor and store it.
Then it observe at rapid interval the potential provided by the sensor, and thus display the corresponding oxygen level.
0 mV ->0%
x mV -> 21%
<measure> mV -> ..
It display also the details potential and the slope used for the calculation (s= ... on the display)
It performs an quick average in order to avoid fuzzy display and Is able to display '--' if the sensor is HS.
I added a moving avery to smooth the variations.
(I leave you studying the code for this)
Step 3: And the Arduino
At the bottom, an arduino is also glued and powered directly but the 9V battery.
Step 4: And Now the Arduino Code
This is the arduino code :D
I have to tune it. contact me
Recommendations
We have a be nice policy.
Please be positive and constructive.
20 Comments
hi. i have another problem : Arduino: 1.8.1 (Windows 8), Плата:"Arduino Pro or Pro Mini, ATmega328 (5V, 16 MHz)"
D:\Diving\rebreather\po2\RunningAverage\RunningAverage\po2\po2.ino:16:28: fatal error: RunningAverage.h: No such file or directory
#include <RunningAverage.h>
^
compilation terminated.
exit status 1
Unzip the running average i provide and put the folder "running average" in your arduino library folder.
Hello EastCrow,
My code is using several external libraries (one for the display and for for the converter analog digital). I do not provide them because they are completely standard.
That's written in the beginning of the code but it seems you are not completely familiar with arduino.
They are also web available. If you want i sent you the zipped folder by mail.
#include
#include "U8glib.h"
Chris
Hi, i beginner for the ardunio. Please send me zipped folder to east_crow@mail.ru
another trouble : Arduino: 1.8.1 (Windows 8), Плата:"Arduino Pro or Pro Mini, ATmega328 (5V, 16 MHz)"
C:\Program Files (x86)\Arduino\RunningAverage\RunningAverage.ino:18:31: fatal error: Adafruit_ADS1015.h: No such file or directory
#include <Adafruit_ADS1015.h>
^
compilation terminated.
exit status 1
hello! what are the pin connect to The second (the red one), once pressed, will set the system 21% oxygen.
This is the pin2. Google arduino pro mini pinout to know exactly where is the pin2 on the board. You will get lot of beautiful diagram.
Hello, i am travelling and have no access to source. I will be back on 5/2 and take a look. Perhaps take abus look at the pin wich is inputpullup...
Hi! may you access to source?
Hello! what the ardunio bord need? | http://www.instructables.com/id/Home-Made-One-Hand-Nitrox-Analyser-Arduino-Based/ | CC-MAIN-2018-17 | refinedweb | 780 | 67.15 |
Understanding Ajax Helpers in ASP.NET MVC
Hi everyone in this blog I’m explaining about Ajax helper in mvc.
Ajax Helpers are used to create AJAX enabled elements like as Ajax enabled forms and links which performs request asynchronously. AJAX Helpers are extension methods of AJAXHelper class which exist in System.Web.Mvcnamespace.
AJAX-enabled link based on action/controller.
@Ajax.ActionLink("Load Products",
"GetProducts", new AjaxOptions {UpdateTargetId =
"Products-container", HttpMethod = "GET" })
Output: <a data-Load Products</a>
ASP.NET MVC supports unobtrusive Ajax which is based on jQuery. The unobtrusive Ajax means that you use helper methods to define your Ajax features, rather than adding blocks of code throughout your views.
The AjaxOptions class defines properties that allow you to specify callbacks for different stages in the AJAX request life cycle. There are following properties provided by AjaxOptions class for AJAX helpers.
URL: Specify the URL that will be requested from the server.
Confirm: Specify a message that will be displayed in a confirm dialog to the end user. When user clicks on OK button in the confirmation dialog, the Ajax call performs.
OnBegin: Specify a JavaScript function name which is called at the beginning of the Ajax request.
OnComplete: Specify a JavaScript function name which is called at the end of the Ajax request.
OnSuccess: Specify a JavaScript function name which is called when the Ajax request is successful.
OnFailure: Specify a JavaScript function name which is called if the Ajax request fails.
LoadingElementId: Specify progress message container’s Id to display a progress message or animation to the end user while an Ajax request is being made.
LoadingElementDuration: Specify a time duration in milliseconds that controls the duration of the progress message or animation.
UpdateTargetId: Specify the target container’s Id that will be populated with the HTML returned by the action method.
InsertionMode: Specify the way of populating the target container. The possible values are InsertAfter, InsertBefore and Replace (which is the default).
By default, web browsers allows AJAX calls only to your web application’s site of origin i.e. site hosted server. This restriction help us to prevent various security issues like cross site scripting (XSS) attacks. But, sometimes you need to interact with externally hosted API(s) like Twitter or Google. Hence to interact with these external API(s) or services your web application must support JSONP requests or Cross-Origin Resource Sharing (CORS). By default, ASP.NET MVC does not support JSONP or Cross-Origin Resource Sharing. For this you need to do a little bit of coding and configuration.
in my next post i'll explain about ASP.NET MVC 4 Bootstrap 3.3.2 in 2 Steps | https://www.mindstick.com/blog/821/understanding-ajax-helpers-in-asp-dot-net-mvc | CC-MAIN-2017-04 | refinedweb | 448 | 58.48 |
Asked by:
Assembly.Load, PropertyGrid and generic class related problem
Question
- OK, this is a complicated case (at least for me). Let me try to describe it as clearly as I can -I have an assembly contains a Form (Form1) with a PropertyGrid and associate its SelectedObject to a class:
propertyGrid1.SelectedObject = new MyWrapper(); public class MyWrapper { Class3 m_class3 = new Class3(); public MyWrapper() { } [Category("Category1"), DisplayName("DisplayName1")] [TypeConverter(typeof(MyConverter<int>))] public Class3 Property1 { get { return m_class3; } set { m_class3 = value; } } }
Property1 has a TypeConverterAttribute -
<span> public class MyConverter<T> : TypeConverter { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { //it is null when Assembly.Load from byte array if (ABC.abc == null) System.Windows.Forms.MessageBox.Show("abc is null"); else System.Windows.Forms.MessageBox.Show("abc is not null"); } }</span>
ABC is a static class hold a static member variable -
public static class ABC { public static Class2 abc; }
ABC.abc is initialized in another class -
<span> public class Class1 { public void method1() { ABC.abc = new Class2(); Form1 form = new Form1(); form.ShowDialog(); } }</span>
I had another console application which will load above assembly and create a Class1 instance and invoke method1. Now the problem comes - if I read the assembly to byte array and load it by Assembly.Load(byte[]), ABC.abc is always null. But if I load it by Assembly.LoadFrom, everything is OK. Is it strange? And I found if I change the generic class MyConverter<T> to a simple class MyConverter. It works well for both cases.
assem = Assembly.Load(assemStream); Type t = assem.GetType("Class1"); object addin = System.Activator.CreateInstance(t); Type rt = addin.GetType(); Type[] emptyParam = new Type[0]; // get the method System.Reflection.MethodInfo macroMethod = rt.GetMethod( "method1", BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.Public, null, emptyParam, null); macroMethod.Invoke(addin, null);
Please help.
All replies
Hi TauYoung,
Welcome to the MSDN forum!
I think the problem is caused by the byte array that you convert the assembly to. Since the link that you provide source code is not available, we can’t see how you do the converting and how do you define the Class2. So we need more information about that.
Have a nice day!
Paul Zhou [MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
Hi Paul,
Thanks for your reply.
You can find the source files here - (the attachment).
The issue still exists with .NET 4. | https://social.msdn.microsoft.com/Forums/en-US/a11f6557-c9e5-4a08-ace1-fde10c3d2aca/assemblyload-propertygrid-and-generic-class-related-problem?forum=clr | CC-MAIN-2020-45 | refinedweb | 426 | 52.36 |
This section highlights some common points among the classes in the Essential Tools Module.
The Essential Tools Module provides implementation, not policy. Hence, it consists mostly of a large and rich set of concrete classes that are usable in isolation and independent of other classes for their implementation or semantics. They can be pulled out and used just one or two at a time. Concrete classes are the heart of the Essential Tools Module.
The Essential Tools Module also includes a rich set of abstract base classes, which define an interface for persistence, internationalization, and other issues, and a number of implementation classes that implement these interfaces.
Some Essential Tools Module classes are further categorized as collection classes, or collections, as explained in Section 2.2.4.
Collection classes generally follow the Smalltalk naming conventions and semantical model: SortedCollection, Dictionaries, Bags, Sets, and so on. They use similar interfaces, allowing them to be interchanged easily. The template-based and generic collections will hold any kind of object; the Smalltalk-like collections require that all collected items inherit from RWCollectable.
Choosing which collection classes to use in your programs is not a trivial task. Appendix A can help you decide which class is the best for your purposes. Section 3.1, "Public Classes," in the Essential Tools Module Reference Guide shows the class hierarchy of all the public Essential Tools Module classes. In addition to these public classes, the Essential Tools Module contains other classes for its own internal use.
The concrete classes consist of:
The simple classes representing dates, times, strings, and so on, discussed in Chapter 3, "Date and Time Classes," and Chapter 4, "String Processing Classes."
The template-based collection classes, discussed in Section 6.7, "Collection Class Templates."
The generic collection classes using the preprocessor <generic.h> facilities, discussed in Chapter 7, "Generic Classes (deprecated)."
The Essential Tools Module provides a rich set of lightweight simple classes. By lightweight, we mean classes with low-cost initializers and copy constructors. These classes include RWDate, RWDateTime, and RWTime (for dates and times, with support for various time zones and locales); RWCString (for single and multibyte strings); and RWWString (for wide character strings). Most instantiations of these classes can be stored in four bytes or less, and have very simple copy constructors (usually just a bit copy) and no virtual functions. The Essential Tools Module Reference Guide provides additional information on these classes.
Template-based collection classes, or templates, give you the advantages of speed and type-safe usage. When templates are used sparingly, their code size can be quite small. When templates are used with many different types, however, their code size can become large because each type effectively generates a whole new class. If you have the Standard C++ Library, you can use the Essential Tools Module template-based collections that are based on the Standard C++ Library. If you do not have the Standard C++ Library, you can use a subset of the templates, described in Section 6.9.1 and Section 6.14.
Generic collection classes, which are deprecated, are those which use the <generic.h> preprocessor macros supplied with your C++ compiler. Because they depend heavily on the preprocessor, it can be difficult to use a debugger on code that contains them. Chapter 7, "Generic Classes (deprecated)," provides additional information.
The Essential Tools Module includes a set of abstract base classes and corresponding specializing classes that provides a framework for many issues. The list below identifies some of these issues and associates them with their respective abstract base classes. The description of each class in the Essential Tools Module Reference Guide indicates if it is an abstract base class.
Rogue Wave and SourcePro are registered trademarks of Quovadx, Inc. in the United States and other countries. All other trademarks are the property of their respective owners.
Contact Rogue Wave about documentation or support issues. | http://www.xvt.com/sites/default/files/docs/Pwr%2B%2B_Reference/rw/docs/html/toolsug/2-3.html | CC-MAIN-2017-51 | refinedweb | 649 | 55.84 |
“Brand New Brilliant Uncirculated”
These alternative suggestions have been selected for you by eBay's recommendation engine.Sellers: Learn more about how to get the most benefit from cross-merchandising.
1/2 oz Silver Australian
Perth Mint 2012 Lunar Year of the Dragon Colorized Coin .999 Fine Silver + Free Copper Dragon
You will receive a 1/2 troy oz Silver Red Dragon and a 1 Av oz Copper Dragon. order
to save you money as best I can. Most orders can be combined up to 20
BU coins and 4 proofs. In most cases shipping can be combined for $1
per oz for additional items ($1.50). If you do happen to buy
multiple items and pay extra shipping, I will refund any shipping overcharges. Also, you are responsible for any tariffs or
import fees that may apply to your order
Coin Information
2012 1/2 oz Silver Australian Year of the Dragon Colorized Coin
The craftsmanship of the Lunar Coins Series, the popularity of the
Chinese Zodiac, and the bullion prices at which these coins are
generally offered have made the Perth Mint’s Lunar series highly
desirable by investors and collectors.
The reverse of each 2012 silver dragon coin depicts a long, scaled, obverse of each 2012 silver dragon coin displays Ian Rank-Broadley’s effigy of Her Royal Majesty Queen Elizabeth II.
The Perth Mint Lunar gold and silver series are issued as legal tender under the Australian Currency Act of 1965.
OR | http://www.ebay.com.au/itm/1-2-oz-2012-Perth-Australian-Silver-Colorized-Red-Lunar-Year-of-Dragon-Copper-/111260664424?pt=LH_DefaultDomain_0&hash=item19e7a70268 | CC-MAIN-2015-22 | refinedweb | 246 | 58.11 |
The socket module supplies a factory function, also named socket, that you call to generate a socket object s. To perform network operations, call methods on s. In a client program, connect to a server by calling s.connect. In a server program, wait for clients to connect by calling s.bind and s.listen. When a client requests a connection, accept the request by calling s.accept, which returns another socket object s1 connected to the client. Once you have a connected socket object, transmit data by calling its method send socket supplies an exception class error. Functions and methods of socket raise error to diagnose socket-specific errors. Module socket also are as follows.
getdefault-timeout
geTDefaulttimeout( )
Returns a float that is the timeout (in seconds, possibly with a fractional part) currently set by default on newly created socket objects, or None if newly created socket objects currently have no timeout behavior.
getfqdn
getfqdn(host='')
Returns the fully qualified domain name string for the given host (a string that is most often a domain name that is not fully qualified). When host is '', returns the fully qualified domain name string for the local host.
gethostbyaddr
gethostbyaddr(ipaddr)
Returns a tuple with three items (hostname,alias_list,ipaddr_list). hostname is a string, the primary name of the host whose IP address you pass as string ipaddr. alias_list is a list of zero or more alias names for the host. ipaddr_list is a list of one or more dotted-quad addresses for the host.
gethostby-name_ex
gethostbyname_ex(hostname)
Returns the same results as gethostbyaddr, but takes as an argument a hostname string that can be either an IP dotted-quad address or a DNS name.
htonl
htonl(i32)
Converts the 32-bit integer i32 from this host's format into network format.
htons
htons(i16)
Converts the 16-bit integer i16 from this host's format into network format.
inet_aton
inet_aton(ipaddr_string)
Converts the IP address ipaddr_string to 32-bit network format; returns a 4-byte string.
inet_ntoa
inet_ntoa(packed_string)
Converts the 4-byte network-format string packed_string; returns IP dotted-quad string.
ntohl
ntohl(i32)
Converts the 32-bit integer i32 from network format into this host's format; returns int.
ntohs
ntohs(i16)
Converts the 16-bit integer i16 from network format into this host's format; returns int.
setdefault-timeout
setdefaulttimeout(t)
Sets float t as the timeout (in seconds, possibly with a fractional part) set by default on newly created socket objects. If t is None, sets newly created socket objects to have no timeout behavior.
socket
socket(family,type)
Creates and returns a socket object with the given family and type. family is usually attribute AF_INET of module socket, indicating you want an Internet (TCP/IP) kind of socket. Depending on your platform, family may also be another attribute of module socket. AF_UNIX, on Unix-like platforms only, indicates that you want a Unix-like socket. (This book does not cover non-Internet sockets, since it focuses on cross-platform Python.) type is one of a few attributes of module socketusually SOCK_STREAM for a TCP (connection) socket, or SOCK_DGRAM for a UDP (datagram) socket.
A socket object s supplies many methods.
The commonly used ones are as follows.
accept
s.accept( )
Accepts a connection request and returns a pair (s1,(ipaddr,port)). s1 is a new connected socket; ipaddr and port are the IP address and port number of the counterpart. s must be SOCK_STREAM; you must have previously called s.bind and s.listen. If no client is trying to connect, accept blocks until some client tries to connect.
bind
s.bind((host,port))
Binds socket s to accept connections from host host on port number port. host can be the empty string '' to accept connections from any host. It's an error to call s.bind twice on any socket object s.
s.close( )
Closes the socket, terminating any listening or connection on it. It's an error to call any other method on s after s.close.
connect
s.connect((host,port))
Connects socket s to the server on the given host and port. Blocks until the server accepts or rejects the connection attempt, and raises an exception in case of errors.
getpeername
s.getpeername( )
Returns a pair (ipaddr,port) with the IP address and port number of the counterpart. s must be connected, either because you called s.connect or because s was generated by another socket object's accept method.
getsockname
Returns a pair (ipaddr,port) with the IP address and port number of this socket on the local machine.
getsockopt
s.getsockopt(level,optname[,bufsize])
Returns the current value of an option on s. level can be any of four constants supplied for the purpose by module socket: SOL_SOCKET, for options related to the socket itself, or SOL_IP, SOL_TCP, or SOL_UDP, for options related to protocols IP, TCP, and UDP, respectively. optname can be any of many constants supplied by module socket to identify each socket option, with names starting with SO_. bufsize is normally absent, and then getsockopt returns the int value of the option. However, some options have values that are structures, not integers. In these cases, pass as bufsize the size of the appropriate structure, in bytesgetsockopt returns a binary string of bytes suitable for unpacking with module struct, covered in "The struct Module" on page 227.
For example, here is how to find out if by default sockets are allowed to reuse addresses:
import socket s = socket.socket( )
print s.getsockopt(s.SOL_SOCKET, s.SO_REUSEADDR)
# emits 0, meaning that by default sockets do not reuse addresses
gettimeout
s.gettimeout( )
Returns a float, which is the timeout (in seconds, possibly with a fractional part) currently set on s, or None if s currently has no timeout behavior.
listen
s.listen(maxpending)
Listens for connection attempts to the socket, allowing up to maxpending queued attempts at any time. maxpending must be greater than 0 and less than or equal to a system-dependent value, which on all contemporary systems is at least 5.
makefile
s.makefile(mode='r')
Creates and returns a file object f (as covered in "File Objects" on page 216) that reads from and/or writes to the socket. You can close f and s independently; Python closes the underlying socket only when both f and s are closed.
recv
s.recv(bufsize)
Receives up to bufsize bytes from the socket and returns a string with the data received. Returns an empty string when the socket is disconnected. If there is currently no data, blocks until the socket is disconnected or some data arrives.
recvfrom
s.recvfrom(bufsize)
Receives up to bufsize bytes from the socket and returns a tuple (data,(ipaddr,port)). data is a string of the data received, and ipaddr and port are the IP address and port number of the sender. Useful with datagram sockets, which can receive data from many senders. If there is no data in the socket, blocks until data arrives.
send
s.send(string)
Sends the bytes of string on the socket. Returns the number n of bytes sent. n may be lower than len(string); you must check for this, and resend substring string[n:] if needed. If there is no space in the socket's buffer, blocks until space appears.
sendall
s.sendall(string)
Sends the bytes of string on the socket, blocking until all the bytes are sent.
sendto
s.sendto(string,(host,port))
Sends the bytes of string on the socket to destination host and port, and returns the number n of bytes sent. Useful with datagram sockets, which can send data to many destinations. You must not have called method s.bind. n may be lower than len(string); you must check for this, and resend string[n:] if it is nonempty.
Example 20-1 shows a TCP server that listens for connections on port 8881. When connected, the server loops, echoes all data back to the client, and goes back to accept another connection when the client is done. To terminate the server, hit the interrupt key with focus on the server's terminal window (console). The interrupt key, depending on your platform and settings, may be Ctrl-Break (typical on Windows) or Ctrl-C.
import socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('', 8881))
sock.listen(5)
# loop waiting for connections
# terminate with Ctrl-Break on Win32, Ctrl-C on Unix try:
while True:
newSocket, address = sock.accept( )
print "Connected from", address
while True:
receivedData = newSocket.recv(8192)
if not receivedData: break
newSocket.sendall(receivedData)
newSocket.close( )
print "Disconnected from", address finally:
sock.close( )
The argument passed to the newSocket.recv call, here 8192, is the maximum number of bytes to receive at a time. Receiving up to a few thousand bytes at a time is a good compromise between performance and memory consumption, and it's usual to specify a power of 2 (e.g., 8192==2**13) since memory allocation tends to round up to such powers anyway. It's important to close sock (to ensure we free its well-known port 8881 as soon as possible), so we use a try/finally statement to ensure we call sock.close. Closing newSocket, system-allocated on any suitable free port, is not as crucial, so we do not use a TRy/finally for it, although it would be fine to do so.
Example 20-2 shows a simple TCP client that connects to port 8881 on the local host, sends lines of data, and prints what it receives back from the server.
import socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', 8881))
print "Connected to server"
data = """A few lines of data to test the operation of both server and client."""
for line in data.splitlines( ):
sock.sendall(line)
print "Sent:", line
response = sock.recv(8192)
print "Received:", response sock.close( )
Run the Example 20-1 server in a terminal window and try a few runs of Example 20-2.
Examples 20-3 and 20-4 implement an echo server and client with UDP (i.e., using datagram rather than stream sockets).
import socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('', 8881))
# loop waiting for datagrams
(terminate with Ctrl-Break on Win32, Ctrl-C on Unix)
try:
while True:
data, address = sock.recvfrom(8192)
print "Datagram from", address
sock.sendto(data, address)
finally:
sock.close( )
import socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
data = """A few lines of data to test the operation of both server and client."""
for line in data.splitlines( ):
sock.sendto(line, ('localhost', 8881))
print "Sent:", line
response = sock.recv(8192)
print "Received:", response sock.close( )
Run the server of Example 20-3 on a terminal window and try a few runs of Example 20-4. Examples 20-3 and 20-4, as well as Examples 20-1 and 20-2, can run independently at the same time. There is no interference or interaction, even though all are using port number 8881 on the local host, because TCP and UDP ports are separate. If you run Example 20-4 when the server of Example 20-3 is not running, you don't receive an error message: the client of Example 20-4 hangs forever, waiting for a response that will never arrive. Datagrams are not as robust and reliable as connections.
Standard C-level sockets, on most platforms, have no concept of timing out. By default, each socket operation blocks until it either succeeds or fails. There are advanced ways to ask for nonblocking sockets and to ensure that you perform socket operations only when they can't block (such as relying on module select, covered in "The select Module" on page 533). However, explicitly arranging for such behavior, particularly in a cross-platform way, can sometimes be complicated and difficult.
It's often simpler to deal with socket objects enriched by a timeout behavior.
Each operation on such an object fails, with an exception indicating a timeout condition, if the operation has neither succeeded nor failed after the timeout period has elapsed. Such objects are internally implemented by using nonblocking sockets and selects, but your program is shielded from the complexities and deals only with objects that present a simple and intuitive interface. Functions getdefaulttimeout and setdefaulttimeout in the socket module, and methods gettimeout and settimeout on socket objects, let you set sockets' timeout behavior: the timeout value of each socket can be a floating-point number of seconds (thus you can also use a fraction of a second) or None to have a "normal" socket that doesn't time out.
With "normal" sockets (ones whose timeout value t is None), many methods, such as connect, accept, recv, and send, may block and wait "forever." When you call such methods on a socket s whose timeout value t is not None, if t seconds elapse since the call and the wait is still going on, then s stops waiting and raises socket.error. | http://books.gigatux.nl/mirror/pythoninanutshell/0596100469/pythonian-CHP-20-SECT-1.html | CC-MAIN-2018-22 | refinedweb | 2,177 | 55.95 |
[
]
Joel Koshy commented on KAFKA-249:
----------------------------------
Thanks for the reviews. Further comments inline.
Jun's comments:
> 1. For future extension, I am thinking that we should probably unifying
> KafkaMessageStream and KafkaMessageAndTopicStream to sth like
> KafkaMessageMetadataStream. The stream gives a iterator of Message and its
> associated meta data. For now, the meta data can be just topic. In the
> future, it may include things like partition id and offset.
That's a good suggestion. I'm not sure if it is better to factor that change
for the existing createMessageStreams into 0.8 instead of trunk, because it
is a fundamental API change that would break existing clients (at compile
time). I can propose this to the mailing list to see if anyone has a
preference. If no one objects, then we can remove it.
> 2. ZookeeperConsumerConnector: 2.1 updateFetcher: no need to pass in
> messagStreams
Will do
> 2.2 ZKRebalancerListener: It seems that kafkaMessageStream can be
> immutable.
It is mutable because it is updated in consumeWildcardTopics.
> 2.3 createMessageStreamByFilter: topicsStreamsMap is empty when passed to
> ZKRebalanceListener. This means that the queue is not cleared during
> rebalance.
Related to previous comment. The topicsStreamsMap is bootstrapped in
consumeWildCardTopics and updated at every topic event if there are new
allowed topics. So it will be populated before any rebalance occurs.
> 2.4 consumeWildCardTopics: I find it hard to read the code in this method.
> Is there a real benefit to use implicit conversion here, instead of
> explicit conversion? It's not clear to me where the conversion is used.
> The 2-level tuple makes it hard to figure out what the referred fields
> represent. Is the code relying on groupedTopicThreadIds being sorted by
> (topic, threadid)? If so, where is that enforced.
The map flatten method is a bit confusing. I'm using (and hopefully not
misusing) this variant:
def flatten [B] (implicit asTraversable: ((A, B)) ⇒ TraversableOnce[B]): Traversable[B]
Converts this map of traversable collections into a map in which all element
collections are concatenated.
It basically allows you to take the KV pairs of a map and generate some
traversable collection out of it. Here is how I'm using it: We have a list
of queues (e.g., List(queue1, queue2)) and a map of
consumerThreadIdsPerTopic (e.g.,
{ "topic1" -> Set("topic1-1", "topic1-2"),
"topic2" -> Set("topic2-1", "topic2-2"),
"topic3" -> Set("topic3-1", topic3-2") } ).
>From the above I need to create pairs of topic/thread -> queue, like this:
{ ("topic1", "topic1-1") -> queue1,
("topic1", "topic1-2") -> queue2,
("topic2", "topic2-1") -> queue1,
("topic2", "topic2-2") -> queue2,
("topic3", "topic3-1") -> queue1,
("topic3", "topic3-2") -> queue2 }
This is a bit tricky and I had trouble finding a clearer way to write it.
However, I agree that this snippet is hard to read - even I'm having
difficulty reading it now, but I think keeping it concise as is and adding
comments such as the above example to explain what is going on should help.
> 3. KafkaServerStartable: Should we remove the embedded consumer now?
My original thought was that it would be good to keep it around for
fall-back, but I guess it can be removed.
> 4. Utils, UtilsTest: unused import
Will do.
--------------------------------------------------------------------------------
Neha's comments:
> 1. It seems awkward that there is a MessageStream trait and the only API
> it exposes is clear(). Any reason it doesn't expose the iterator() API ?
> From a user's perspective, one might think, since it is a stream, it would
> expose stream specific APIs too. It will be good to add docs to that API
> to explain exactly what it is meant for.
The only reason it was added was because I have two message stream types
now. Anyway, this will go away if we switch to the common
KafkaMessageMetadataStream.
> 3. There is some critical code that is duplicated in the
> ZookeeperConsumerConnector. consume() and consumeWildcardTopics() have
> some code in common. It would be great if this can be refactored to share
> the logic of registering session expiration listeners, registering watches
> on consumer group changes and topic partition changes.
Will do
> 4. Could you merge all the logic that wraps the wildcard handling in one
> API ? Right now, it is distributed between createMessageStreamsByFilter
> and consumeWildcardTopics. It will be great if there is one API that will
> pre process the wild cards, create the relevant queues and then call a
> common consume() that has the logic described in item 5 above.
Slightly involved, but it is worth doing.
> 5. There are several new class variables called wildcard* in
> ZookeeperConsumerConnector. I'm thinking they can just be variables local
> to createMessageStreamsByFilter ?
Related to above. consumeWildcardTopics actually needs to access these so
that's why it's global - in this case global makes sense in that you really
wouldn't need to (and currently cannot) make multiple calls to
createMessageStreamsByFilter. However, it would be good to localize them if
possible to make the code easier to read.
> 6. There is a MessageAndTopic class, that seems to act as a container to
> hold message and other metadata, but only exposes one API to get the
> message. Topic is exposed by making it a public val. Would it make sense
> to either make it a case class or provide consistent APIs for all fields
> it holds ?
Ok, but this will likely go away due to the MessageMetadata discussion.
> 7. Since now we seem to have more than one iterators for the consumer,
> would it make sense to rename ConsumerIterator to MessageIterator, and
> TopicalConsumerIterator to MessageAndMetadataIterator ?
Makes sense, but it could break existing users of KafkaMessageStream. Also,
if we can get rid of KafkaMessageStream and just go with
KafkaMessageAndMetadataStream we will have only one iterator type.
> 8. rat fails on this patch. There are some files without the Apache header
Good catch and reminder that reviews should ideally include running rat. I
do need to add the header for some files.
>: | https://mail-archives.apache.org/mod_mbox/kafka-dev/201203.mbox/%3C496890682.30110.1332969931037.JavaMail.tomcat@hel.zones.apache.org%3E | CC-MAIN-2020-10 | refinedweb | 979 | 65.73 |
There are two sections that get added to VS 2008 after you install the add-in from MSR to test Code Contracts. The first one is simply called 'Contracts'.
The second tab is named 'Code Contracts'.
The MSR team did a presentation at PDC08 about Code Contracts and the Pex automated-testing tool.
In the area of contract-based coding at Microsoft, there is also Spec#. Sample shown below.
using System;
using Microsoft.Contracts;
public class Program
{
static void Main(string![]! args)
{
Console.WriteLine("Spec# says hello!");
}
public int Add(int i, int j)
requires i > 5;
requires j < 3;
{
int r = i + j;
return r;
}
}
Have you had time to look at contract-based coding? What do you think about it? | http://blogs.msdn.com/b/socaldevgal/archive/2008/12/28/trying-out-code-contracts-from-microsoft-research.aspx?Redirected=true | CC-MAIN-2014-15 | refinedweb | 122 | 77.94 |
In this series, we are creating a Hangman game for the Android platform. In the first tutorial, we set the application up to present two screens to the user and we also made a start with the user interface elements, the images and shape drawables to be precise. In the second tutorial, we will zoom in on the game's layout.
Introduction
Creating the game's layout will involve using an adapter to create letter buttons and positioning the body parts we will display when users select incorrect letters. We will also store the player's answers in XML, retrieve them, and choose a random word using Java.
To refresh your memory, this is what the final game will look like.
1. Position the Body Parts
Step 1
In the previous tutorial, we created images for the gallows and for the six body parts. We will place these inside the game's layout in this tutorial. The positions you set for these elements need to be determined by the image elements that you are using. One approach is to import the images into a image editor, such as Adobe's Photoshop, position them manually, and then use their
x and
y positions relative to the gallows image to work out the correct positions to apply to each image in the XML layout. If you are starting with the demo images we included in the previous tutorial, you can use the values listed in this tutorial.
Start by opening activity_game.xml. Inside the linear layout that we added in the previous tutorial, enter a relative layout to hold the seven images that will make up the gallows area.
<RelativeLayout android: </RelativeLayout>
Step 2
Inside the relative layout you just created, start by adding the gallows image as shown below.
<ImageView android:
Remember to modify the drawable name if the image you're using is named differently. We set the image's left and top padding to
0 so that we can position the other images relative to its position. We'll add string resources for the content descriptions a bit later in this tutorial. Next up is the head.
<ImageView android:
If you're using your own images, you'll need to alter the left and top padding accordingly. We use an
id attribute so that we can refer to the image in code. This is necessary to make it appear and disappear depending on the user's input. The next image we add is the body.
<ImageView android:
This looks very similar to what we did for the head and, as you can see below, the arms and legs are pretty similar.
<ImageView android: <ImageView android:
<ImageView android: <ImageView android:
Open the project's res/values strings XML file and add the content description strings that we've used in the above code snippets.
<string name="gallows">The Gallows</string> <string name="head">The Head</string> <string name="body">The Body</string> <string name="arm">An Arm</string> <string name="leg">A Leg</string>
Go back to the layout file and switch to the Graphical Layout tab to see the result of our work. Adjust the top and left padding of each image to adjust their position if necessary.
Whenever a new game is started, the body parts need to be hidden. Each body part is revealed if the player chooses a letter that is not present in the target word.
2. Store the Answer Words
The game will use a collection of predefined words, which we will store in XML. In your project resources values folder, add a new file and name it arrays.xml.
Switch to the XML tab, create an array, and add a few words to it.
<resources> <string-array <item>CHARGER</item> <item>COMPUTER</item> <item>TABLET</item> <item>SYSTEM</item> <item>APPLICATION</item> <item>INTERNET</item> <item>STYLUS</item> <item>ANDROID</item> <item>KEYBOARD</item> <item>SMARTPHONE</item> </string-array> </resources>
3. Choose and Present a Word
Step 1
Back in your game's activity layout file, add a linear layout immediately after the relative layout we added for the gallows area. The linear layout is reserved for the answer area.
<LinearLayout android: </LinearLayout>
We store each character of the target word within its own text view so that we can reveal each letter separately. We will use the
id of the linear layout in code to add the text views each time a new word is chosen.
Step 2
Open the
GameActivity class and start by adding the following import statements at the top.
import android.content.res.Resources; import android.graphics.Color; import android.view.Gravity; import android.view.ViewGroup.LayoutParams; import android.widget.LinearLayout; import android.widget.TextView;
Inside the class declaration, add an
onCreate method as shown below.
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_game); }
We set the content view to the layout file we created a moment ago.
Step 3
Before we move on, we need to declare a few instance variables. Add the declaration immediately before the
onCreate method.
private String[] words; private Random rand; private String currWord; private LinearLayout wordLayout; private TextView[] charViews;
The collection of words are stored in an array and the application uses the
rand object to select a word from the array each time the user starts a new game. We keep a reference to the current word (
currWord), the layout we created to hold the answer area (
wordLayout), and an array of text views for the letters (
charViews). Back in
onCreate, after setting the content view, request the application's resources, read the collection of words, and store them into the
words instance variable.
Resources res = getResources(); words = res.getStringArray(R.array.words);
Note that we use the name we gave the word array in XML. Initialize the
rand object and
currWord string.
rand = new Random(); currWord = "";
Get a reference to the layout area we created for the answer letters.
wordLayout = (LinearLayout)findViewById(R.id.word);
Step 4
A number of tasks need to be performed every time a new game is started by the player. Let's create a helper method to keep everything organized. After the
onCreate method, add the following method outline.
private void playGame() { //play a new game }
Inside the
playGame method, start by choosing a random word from the array.
String newWord = words[rand.nextInt(words.length)];
Because the
playGame method is invoked when the user chooses to play again after winning or losing a game, it is important that we make sure we don't pick the same word two times in a row.
while(newWord.equals(currWord)) newWord = words[rand.nextInt(words.length)];
Update the
currWord instance variable with the new target word.
currWord = newWord;
Step 5
The next step is to create one text view for each letter of the target word. Still inside our helper method, create a new array to store the text views for the letters of the target word.
charViews = new TextView[currWord.length()];
Next, remove any text views from the
wordLayout layout.
wordLayout.removeAllViews();
Use a simple
for loop to iterate over each letter of the answer, create a text view for each letter, and set the text view's text to the current letter.
for (int c = 0; c < currWord.length(); c++) { charViews[c] = new TextView(this); charViews[c].setText(""+currWord.charAt(c)); }
The string is stored as an array of characters. The
charAt method allows us to access the characters at a specific index. Still inside the
for loop, set the display properties on the text view and add it to the layout.
for (int c = 0; c < currWord.length(); c++) { charViews[c] = new TextView(this); charViews[c].setText(""+currWord.charAt(c)); charViews[c].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); charViews[c].setGravity(Gravity.CENTER); charViews[c].setTextColor(Color.WHITE); charViews[c].setBackgroundResource(R.drawable.letter_bg); //add to layout wordLayout.addView(charViews[c]); }
We set the text color to white so that the user will not be able to see it against the white background. If they guess the letter correctly, the text color property is se to black to reveal it to the player. Back in the
onCreate method, call the helper method we just created.
playGame();
We'll expand both the
onCreate and the helper method a bit later.
4. Create the Letter Buttons
Step 1
The next step is to create an area for the player to choose letters to guess. Revisit the game's activity layout and add the following grid view to hold the letter buttons. Insert the grid view immediately after the linear layout we added for the answer word.
<GridView android:
We're going to use an adapter to map the letters of the alphabet to buttons in the grid view. We lay out seven buttons per row as you can see from the
numColumns attribute.
Step 2
Each letter is going to be a button added to the layout using an adapter. Add a new file in your project layout folder, name it letter.xml, and populate it with the following code snippet.
<Button xmlns:
We use one of the drawable shapes we created last time as background and set an
onClick method we will implement next time. If you are enhancing the application to target different screen densities, you can consider tailoring the height attribute accordingly.
Step 3
Add a new class to your project's src package, name it
LetterAdapter, and choose
android.widget.BaseAdapter as its superclass.
As you'll see, an adapter class includes a series of standard methods we will implement. Add the following import statements to the new class.
import android.content.Context; import android.view.LayoutInflater; import android.widget.Button;
Inside the class declaration, add two instance variables as shown below.
private String[] letters; private LayoutInflater letterInf;
The
letters array will store the letters of the alphabet and the layout inflater will apply the button layout we defined to each view handled by the adapter. After the instance variables, add a constructor method for the adapter.
public LetterAdapter(Context c) { //setup adapter }
Inside the constructor, instantiate the alphabet array and assign the letters A-Z to each position.
letters=new String[26]; for (int a = 0; a < letters.length; a++) { letters[a] = "" + (char)(a+'A'); }
Each character is represented as a number so that we can set the letters A to Z in a loop starting at zero by adding the value of the character A to each array index. Still inside the constructor method, specify the context in which we want to inflate the layout, which will be passed from the main activity later.
letterInf = LayoutInflater.from(c);
Eclipse should have created a
getCount method outline. Update its implementation as follows.
@Override public int getCount() { return letters.length; }
This represents the number of views, one for each letter. We don't call the methods in the adapter class explicitly within the application. It's the operating system that uses them to build the user interface element we apply the adapter to, which in this case will be the grid view.
Update the implementation of
getView as shown in the code snippet below.
@Override public View getView(int position, View convertView, ViewGroup parent) { //create a button for the letter at this position in the alphabet Button letterBtn; if (convertView == null) { //inflate the button layout letterBtn = (Button)letterInf.inflate(R.layout.letter, parent, false); } else { letterBtn = (Button) convertView; } //set the text to this letter letterBtn.setText(letters[position]); return letterBtn; }
Take a moment to let everything sink in. Essentially, this method builds each view mapped to the user interface element through the adapter. We inflate the button layout we created and set the letter according to the position in the alphabet that the view represents. We have stated that there will be 26 views being mapped, with the position of each reflecting its position in the alphabet array. You can leave the other methods in the adapter class as they are.
@Override public Object getItem(int arg0) { return null; } @Override public long getItemId(int arg0) { return 0; }
Step 4
Revisit the game's activity class and add an instance variable for the grid view and the adapter.
private GridView letters; private LetterAdapter ltrAdapt;
You also need to add another import statement.
import android.widget.GridView;
In the
onCreate method, before the line in which you call the
playGame helper method, get a reference to the grid view.
letters = (GridView)findViewById(R.id.letters);
Append the
playGame's current implementation with the following snippet. In this snippet, we instantiate the adapter and set it on the grid view.
ltrAdapt=new LetterAdapter(this); letters.setAdapter(ltrAdapt);
Run the application in the emulator and you should see the user interface. However, you won't be able to interact with the buttons yet. That's what we will focus on in the third and final installment of this series.
Conclusion
If you run your application at this point, it will present you with the game's interface, but it won't respond to user interaction yet. We will implement the remaining functionality in the final part of this series.
When a player clicks the letter buttons, the application needs to verify if the selected letter is included in the target word and update the answer and gallows accordingly. We will also present a dialog to the player if they win or lose, and we'll also add a help button. Finally, we'll add basic navigation through an action bar.
Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
| http://code.tutsplus.com/tutorials/create-a-hangman-game-user-interface--mobile-21853 | CC-MAIN-2015-27 | refinedweb | 2,279 | 55.44 |
#include <sys/ddi.h> #include <sys/sunddi.h> int devmap_do_ctxmgt(devmap_cookie_t dhp, void *pvtp, offset_t off, size_t len, uint_t type, uint_t rw, int (*devmap_contextmgt)devmap_cookie_t, void *, offset_t, size_t, uint_t, uint_t);
Solaris DDI specific (Solaris DDI).
An opaque mapping handle that the system uses to describe the mapping.
Driver private mapping data.
User offset within the logical device memory at which the access begins.
Length (in bytes) of the memory being accessed.
The address of driver function that the system will call to perform context switching on a mapping. See devmap_contextmgt(9E) for details.
Type of access operation. Provided by devmap_access(9E). Should not be modified.
Direction of access. Provided by devmap_access(9E). Should not be modified.
Device drivers call devmap_do_ctxmgt() in the devmap_access(9E) entry point to perform device context switching on a mapping. devmap_do_ctxmgt() passes a pointer to a driver supplied callback function, devmap_contextmgt(9E), to the system that will perform the actual device context switching. If devmap_contextmgt(9E) is not a valid driver callback function, the system will fail the memory access operation which will result in a SIGSEGV or SIGBUS signal being delivered to the process.
devmap_do_ctxmgt() performs context switching on the mapping object identified by dhp and pvtp in the range specified by off and len. The arguments dhp, pvtp, type, and rw are provided by the devmap_access(9E) entry point and must not be modified. The range from off to off+len must support context switching.
The system will pass through dhp, pvtp, off, len, type, and rw to devmap_contextmgt(9E) in order to perform the actual device context switching. The return value from devmap_contextmgt (9E) will be returned directly to devmap_do_ctxmgt().
Successful completion.
An error occurred.
devmap_do_ctxmgt() must be called from the driver's devmap_access(9E) entry point.
The following shows an example of using devmap_do_ctxmgt() in the devmap_access(9E) entry point.
. . . _access(9E), devmap_contextmgt (9E), devmap_default_access(9F)
Writing Device Drivers for Oracle Solaris 11.2 | http://docs.oracle.com/cd/E36784_01/html/E36886/devmap-do-ctxmgt-9f.html | CC-MAIN-2016-18 | refinedweb | 322 | 51.24 |
SDHash
This article talks about the SDHash package, which is a Python library for computing hashes of images which ignore perceptual differences.
As humans, it’s very easy to spot if two images are “the same”. Unfortunately, the same thing can’t be said of computers. A simple approach such as comparing two images pixel by pixel will fail in all but the most simple of cases. Even a more sophisticated method such as computing an \(\mathcal{L}_1\) or \(\mathcal{L}_2\) mean distance between the images and taking a small value to imply similarity is not much better.
For example, given an original image A, the following should produce equivalent images:
- Scaling with the same aspect ratio.
- Scaling with a very similar aspect ratio.
- Adding high frequency noise.
- Small blurring / high pass filtering.
- Lossy compression and reconstruction.
The previous set of transformations can be said to be natural, that is, they will most certainly occur in any systen, as images get moved around, edited etc . However, there’s an even bigger class of transformations which are adversarial, that is, somebody is trying to trick the system to believe one image is original when it is in fact not. User generated content sites face this problem, regardless of the mode of the content (text, image, audio, video).
The following adverserial transformations should produce equivalent images, as well:
- Removing a small area from the borders.
- \(90\), \(180\), \(270\) degrees rotation.
- Horizontal or vertical flipping.
- Adding or removing a watermark.
- Alteration of color planes, but not of the luminance one.
- Grayscale conversion.
- Large-scale editing restricted to a small area (replacing some text with another, for example)
SDHash tries to solve the problem of whether two images are identical or not, modulo all the transformations in the first group, and some (removing of borders and color plane lterations) from the second.
The API it exposes is simple. The
test_duplicate method receives two PIL images as
input and returns either
True or
False depending on whether it considers the
images as equivalent or not. The
hash_image method returns a base64 encoded md5
hash of “stable” image contents. The
test_duplicate method is essentially a test
of whether the hashes of the arguments are equal. For more advanced usage, the second
method is the tool of choice.
For example, a database table of the hashes can be used, with the result of
hash_image
as a primary key. Whenever new image needs to be added it can be checked first against the
table and only if it is not found already, inserted. This allows \(O(1)\) comparisons to
be performed for each insertion, instead of \(O(n)\). Similarly, a MapReduce job can
compute the hashes of images in the map stage, which will result in all identical images
being grouped together with the same key in the reduce stage. This allows an \(O(n)\)
algorithm for deuplicating a large dataset.
As a bonus, SDHash works with GIF animations. It treats them as a sequence of frames. Only the first, fifth, tenth etc. frames are considered. The same basic approach is used, but all the frames are considered at once.
Usage
import sdhash from PIL import Image i1 = Image.open('test1.png') i2 = Image.open('test1_noise.png') i3 = Image.open('test2.png') h = sdhash.Hash() h.test_duplicate(i1, i2) # True h.test_duplicate(i1, i3) # False h.hash_image(i1) # [ an md5 output ]
Algorithm
The core algorithm is straightforward:
- The input image is converted to a single plane of high-precision grayscale.
- This plane is resized to a standard width, while maintaing the aspect ratio.
- The DCT is computed on the plane.
- An MD5 hash is computed from a stream which starts with the width and height of the image, and continues with the top-left most significant DCT coefficients, in row major order, clamped to an interval and precision.
All details of the process can be controlled via arguments to the hasher object constructor, although their effect is somewhat esoteric. Good defaults have been provided.
Installation
The main dependencies are on the Python image library and NumPy/SciPy etc. As such, depending on SDHash brings along a lot of baggage. Ideally and since it only depends on a very small piece of functionality, the library would just include the DCT code directly. Feel free to contribute a well tested implementation.
Installation is simple, via
pip:
pip install sdhash | https://horia141.com/sdhash.html | CC-MAIN-2020-45 | refinedweb | 731 | 57.57 |
SummerSchedule2008
Contents
- 1 Vacation Schedule
- 2 Work Schedule
- 2.1 Project Webpages
- 2.2 To-do List
- 2.3 Week 1, May 27 - May 30, 2008
- 2.4 Week 2, June 2 - June 6, 2008
- 2.5 Week 3, June 9 - June 13, 2008
- 2.6 Week 4, June 16 - June 20, 2008
- 2.7 Week 5, June 23 - June 27, 2008
- 2.8 Week 6, June 30 - July 4th, 2008
- 2.9 Week 7, July 7th - July 11th, 2008
- 2.10 Week 8, July 14 - July 18th, 2008
- 2.11 Week 9, July 21 - July 25th, 2008
- 2.12 Week 10, July 28th - August 1st, 2008
Vacation Schedule
- Doug
Work Schedule
Meena : 27 May - 1 August, 2008 (10:00 am - 5:00 pm, with hour lunch break)
Project Webpages
Kerstin and Priscy: Neural Networks and Robot Attention
Meena : Humanoid Robotics
Teyvonia: Designing, Building and Programming a Hexapod: From King Spider to TevBot
To-do List
- Doug: fix startpython.pyw for Mac.
- Becca: work on Ruby, Scheme, Dinah interface's code blocks
Week 1, May 27 - May 30, 2008
I did this...
- Becca (27 May 2008): I have Myro loaded, though not TK Snack (stuck) or XMPPPY (no directions anywhere). Here are some links to websites with instructions for creating installer packages:
- Meena (27 May 2008): Started reading about differences between C# and Java (to prep for translation of pyro code); read through the Pyro tutorials; ended on the "PyroModuleDirectControl" module; edited the code at the end like so:
from pyrobot.brain import Brain class WallFollow(Brain): # follows walls on its left, ignores sonar sensors on its right def wallFollow(self, dist): frontLeft < dist: print "wall in front" self.move(0,-0.5) elif (sideLeftA < dist or sideLeftB < dist or diagBackLeft < dist): (sideRightA < dist or sideRightB < dist or diagBackRight < dist): step(self): self.wallFollow(1) def INIT(engine): return WallFollow('WallFollow', engine)
- Becca (28 May 2008): Directions to load xmpppy on an Intel-based Mac: Download xmpppy from link and unzip. cd to correct directory, then same install line as for other packages.
- It turns out that TK Snack doesn't work on Intel-based Macs yet.
- I made installers for Myro, but need a Mac to test them on.
- I read the Pyro article, and am partway through the IronPython book. See the Mac OS X installation page for everything else I've done all day.
- Kerstin: I read the first 8 Pyro tutorials (up through Neural Networks) and I am wondering about the advantages of having several references to the same robot: robot, engine.robot, engine.brain.robot. I also read the article Bringing up robot: Fundamental mechanisms for creating a self-mativated, self-organizing architecture by D. Blank, D. Kumar, L. Meeden and J. Marshall, and I started reading up on C#. There does not seem to be a C# compiler installed on Windows so I cannot experiment with actual code right now. I will try to find Mr. Rice to get my Fedora password so that I can work with Linux. Update: It turned out that the robot references make a lot of sense when the program controls several robots with different brains.
- Meena (28 May 2008): Read "Bringing up robot: Fundamental mechanisms for creating a self-mativated, self-organizing architecture" article (Blank, D., Kumar, D., Meeden, M., and James Marshall) to get an idea of research already done; read most of "Pyro: A Python-based Versatile Programming Environment for Teaching Robotics" article (Blank, D., Kumar, D., Meeden, M., and Holly Yanco) to learn about background of Pyro project; finished reading up on C# vs Java comparison (will probably try writing test programs tomorrow); read some more of the Pyro tutorial; made the following behaviors after the Vertical Behaviors section:
#class Wander(SubsumptionBehavior): # def update(self): # self.move( .2, random.random() * 2 - 1) #class Avoid(SubsumptionBehavior): # def update(self): # if min([s.value for s in self.robot.range["front-all"]]) < 1: # self.move(-.2, 0) ##New Behaviors class Spin(SubsumptionBehavior): def update(self): self.move(0,1) class ForwardFromWall(SubsumptionBehavior): def update(self): if min([s.value for s in self.robot.range["back-all"]]) < 1: self.move(0.3,0) class ForwardToWall(SubsumptionBehavior): def update(self): if min([s.value for s in self.robot.range["front-all"]]) > 3: self.move(0.3,0) class WanderAvoidFollowWall(SubsumptionBehavior): def update(self): min([s.value for s in self.robot.range["front-all"]]) > 3: self.move( .2, random.random() * 2 - 1) elif min([s.value for s in self.robot.range["front-all"]]) < 0.5: self.move( -.2, 0) elif min([s.value for s in self.robot.range["front-all"]]) < 1: if frontLeft < 1: print "wall in front (left)" self.move(0,-0.5) elif (sideLeftA < 1 or sideLeftB < 1 or diagBackLeft < 1): frontRight < 1: print "wall in front (right)" self.move(0, 0.5) elif (sideRightA < 1 or sideRightB < 1 or diagBackRight < 1): INIT(engine): subsumption = SubsumptionBrain( engine ) # add behaviors, lowest priorities first: # subsumption.add( Wander() ) subsumption.add( Spin() ) subsumption.add( ForwardToWall() ) subsumption.add( ForwardFromWall() ) # subsumption.add( Avoid() ) subsumption.add( WanderAvoidFollowWall() ) return subsumption
Tried to make the sim robot dance, but couldn't figure out how to create three separate movements for it (might look at code again tomorrow to modify for multiple movements during updates, if that is the problem); read partway through Horizontal Behavior section
- Becca (29 May 2008): Finished reading about IronPython. Started reading about C# and discovered a good online tutorial ([1]) which gets straight to the point.
- Meena (29 May 2008): Finished reading articles; continued reading Pyro tutorials online (reached second part of Neural Networks section); edited multiple bits of code for exercises (won't paste all of them here to conserve page space); planning on downloading a compiler for C# on laptop and trying some programs tomorrow, since compiler on Park computer's apparently out of date
- Kerstin: I experimented a bit with Conx. I tried to teach a network to recognize a triangle: given the coordinates of a point, decide whether that point lies inside (output=0), outside (1) or on the edge (0.5) of the triangle. I started with 260 training points, 100 inside, 100 outside and 60 on the edge. I was surprised how much trouble a multi-layered network had with this task. For the number of nodes I used (between 4 and 100 in one hidden layer, and two hidden layers with 6 nodes each), the network never managed to recognize more than 70% of the training points (w/ tolerance = 0.2) after several thousand epochs. More interestingly, the performance of the network dropped over time. The peak performance of ~70% correct points was reached after a few hundred epochs and then the performance dropped down to and stayed stable at 40-50% correct points, regardless of the number of nodes used. The main problem seemed to have been the points on the edge of the triangle. After removing those points from the training set, a three layer network with 4 hidden nodes recognized 100% of the 200 training points after about 80 epochs. It was also able to make generalizations: the network correctly identified 98% of a cross-validation set of 500 points.
- Becca (30 May 2008): Read enough about C# to write a few sample programs. I should be able to just look up anything else I need to know about the language as I need it. I started loading Myro 3, but got stuck at the 'make' command.
Week 2, June 2 - June 6, 2008
- Kerstin: I have read (or re-read) a few papers today: The Multiple Roles of Anticipation in Developmental Robotics by D.S. Blank, J.M. Lewis and J.B. Marshal , An Emergent Framework for Self-Motivation in Developmental Robotics by D.S. Blank, L. Meeden and J.B. Marshall, and The Governor Architecture: Avoiding Catastrophic Forgetting in Robot Learning by D.S. Blank, J. Stober and L. Meeden. I also read (or skimmed) the Wikipedia articles on Neural Networks, Neural Gas, Machine Learning, Developmental Robotics and Artificial Intelligence.
- Meena (2 June 2008): Read rest of Pyro tutorial (PyroModuleComputerVision, PyroModuleMapping, PyroModuleMultirobot); read some of the related articles under the Community section (namely "Python AI", "A Framework for Reactive Intelligence through Agile Component-Based Behaviors", and "AI Expert Newsletter").
A section about chat bots in the "Python AI" article reminded me of a Japanese robotics project I read about awhile ago, where researchers were trying to use humanoid robots to interact vocally with people by interpreting what they said and outputting appropriate responses (I think the robot in that article was doing a physics lecture or a scientific Q&A session). Might be worth simplifying into a project for this summer. The article also mentioned a GuessLang program that can analyze a webpage and figure out what language it's in; this could probably be modified to work with an interactive robot that could work in different languages, or could simulate a fluent speaker for language students needing to be immersed in the language. Maybe.
The dissertation ("A Framework for Reactive Intelligence through Agile Component-Based Behaviors") pointed out some interesting things about different languages and efficiency/speed. C++ (and I would guess other "system programming languages") take less time to process information in (on average C++ is 20x faster than Python and can get up to 100x faster in common applications), so it would make sense to try programming in one of these system programming languages. We'll already be using C# to translate Pyro, so we might as well use it for further experimentation as well, or try using Java or C++ for the fun of it.
- Kerstin: After thinking about the Governor and its ARAVQ implementation, I started wondering if there are different ways of storing learned information (very broadly speaking) in some sort of long-term memory to avoid catastrophic forgetting. The ARAVQ Governor solves this problem by continually rehearsing the old input, but can a network-controlled robot remember the correct behavior in a situation without continually rehearsing it?
- Becca (2 June 2008): I discovered that I could load Gnome Sharp (which is needed for Myro 3) with MacPorts, but even though I managed to load another MacPorts program (TexMath. It's way too much fun.), Gnome Sharp kept hanging and wouldn't load. Other than that, I connected the Mac to a Scribbler and started thinking of programs and concepts to share at the workshop next week. I have a few sample programs and will work on more, as well as a robot that's been taken apart to show people.
- Meena (3 June 2008): Read some articles pertaining to android AI, recent research in humanoid robotics, and other related topics. Looked over the code for an ELIZA-based program called Therapist (program that simulates a discussion with a therapist by responding to human input/responses). Could probably make such a program better by transferring it to a neural network-like format, where program/robot could learn how to respond to different questions or statements (or at least tell the user to stop asking/saying whatever's causing the program/robot trouble). Could have certain keywords also act as reinforcement values, maybe. Will mess with some chat bots on my laptop to gauge their limitations, and will see if I can find out how they are implemented and what makes them better than ELIZA (maybe they're already using networks). Also downloaded, installed, and started messing with Microsoft Robotics Developer Studio 2008. Messed with the VPL (visual programming language) approach to programming. Trying to figure out how to use more complicated loops than if statements (for loops and while loops aren't included as draggable programming parts). Looks like lists/2D arrays are also the only data structures readily available for the visual programmer to use; trying to figure out if other structures are useable, and if so how exactly they can be implemented. Coding by dragging icons feels restrictive, annoying; feel like it would take less time just to type out the commands (it would definitely take less time to include things like while loops or dictionaries, if I wanted to include them for some reason). Wondering whether it's possible to textually code somewhere and import the code into the rest of the program; seems MRDS2008 can work with Visual Studio C# for some applications, so I might install that and see if I can use it instead of VPL.
- Meena (4 June 2008): Went through tutorials on how to use the MRDS simulation program, looked up videos and articles about the Robonova-1 (the robot that's coming in soon). Downloaded a zip file that had files for simulating the Robonova-1, will look at it tomorrow.
- Becca (5 June 2008): Oops, forgot to update for a few days. I've installed Myro on an XO laptop and set up the bluetooth so the robot could connect to it (OLPC-XO). I'm still working on ways to make it easier and faster to set it up each time the computer is restarted. I've gone through the new textbook for the intro class and have written a few exercises to go along with the new chapters (read the extra credit one. You will laugh. Exercises). I've started looking up Scheme to get a general idea of what it is about.
- Meena (5-6 June 2008): Tried running zip files; didn't work. Considered making own mesh files and project for creating robot in simulation, realized learning how to use the art program alone (Blender) could take weeks, decided to see what I could so about the zip file. Got the references to work, but for some reason it can't connect to the Microsoft servers. Posted about it on the Development Forums, will check later to see if I got a reply. If necessary will try connecting to different server.
In the meantime, read through shiny new book, Programming Microsoft Robotics Studio (Sara Morgan); learning how to set up a service that will allow for "autonomous roaming" on a LEGO NXT; hoping to get this into a simulator and see if it works, then learn how to get other robots working in the same manner (right now it seems services are meant for REAL robots, not simulated robots, so I'll have to look up info about that; might have to eventually modify sim environment itself). Also looked at old Myro game I made in CS110 to see if it was presentable for the conference; started on modifications to make it playable by up to 4 people (now only supports 2), but dunno if it will matter, since it has to be played with game controllers and they are in limited supply as far as I know.
Week 3, June 9 - June 13, 2008
- Becca (9-10 June 2008): I made (thankfully with help) 29 robot kits for the conference. We seem to be missing one lunchbox somewhere.
- Meena (9-10 June 2008): Found out the zip for the robot was just for the model of the robot, not for moving or anything. Couldn't connect to a server because it didn't have any services in its code. Still looking for something to explain how to use behaviors on sim robots instead of real robots. Looking for code online that will help override whatever code Microsoft uses for movement in simulations (since Microsoft doesn't do a good job of explaining the code that isn't directly discussed in the tutorials). Also looked through random classes to try and find out what might need altering. Will have to look at robot to figure out what sensors it has/joint movement/etc so I can make a behavior that is specific to that robot.
- Becca (11 June 2008): Gnome Sharp is still not loaded. I seem to get a different error message every time I try installing it through MacPorts, after it hangs for a while.
Week 4, June 16 - June 20, 2008
- Becca (16 June 2008): I'm looking at Alice and Scratch, two graphical programming languages, to see what features we might want to have for our own graphical programming language in Myro. So far, I like Scratch a lot more because it is much more intuitive, supports more than just videos, and corresponds more to the code it represents.
- Kerstin: I have been trying to reproduce the follow-the-wall neural network experiment and I have run into several problems. The network simulation crashes after a certain time on Linux, which seems to be a memory issue. I tried deleting the network every now and then and then using the 'gc' module for cyclical garbage collection but it didn't help. Now I moved to Windows and it works just fine. My second problem is with the governor network class. Whenever I try using it (on Windows), it seems to be less efficient than a regular network; after several thousand training periods the error is still significantly larger than the error of a normal network with the same topology. I might have not implemented the governor network correctly, the version on Windows might be outdated or I might not be giving it enough time.
I finally managed to train a network with 25 hidden nodes and I was quite surprised when I tested it: the robot went the exact same path that I wanted it to go (until it got stuck), but backwards. I am 99.9% sure that I am not converting the network units back to robot units correctly, but I cannot find the error. Finally, I am not quite sure how many hidden nodes in how many layers I should use. With 25 hidden nodes in one layer I got a cumulative TSS error of about 200 for a data set of 20,000 points. I am currently training a network with 50 nodes in one layer and I am down to a TSS error of about 180 after 4000 epochs. I would like to try to train a network with significantly more nodes but I am afraid that would currently not be feasible computing-power-wise. I tried training a network with 2 hidden layers of 8 nodes each and had it run over the weekend, but after ~2000 epochs it still had a TSS error above 1,000. The error had not decreased over the last 100 epochs so I stopped the training.
- Meena (16 June 2008): Found out that partial cause of my problems with MRDS. Stuff works fine now. Looking at code from this site to get idea of how to make robots move on their own in the simulator.
Also worked a little with the Robonova-1. Think it has a short battery life; not sure how long it needs to be charged because LED light on the charger always changes to green after maybe twenty minutes, but the robot loses power shortly after (10-20 mins). Will charge for a few hours tomorrow to see if the battery can last for an hour, at least. Can't try fancy robot moves at the moment anyway because of lack of space.
- Becca (17 June 2008): I started learning Ruby, in addition to Scheme. I created a spreadsheet in Google Docs listing my ideas so far on what features from Alice and from Scratch would make a good graphical programming language for us to use. I looked up some of what had been done with the two languages to see what we might want to make it easy or harder to do. I will be preparing a talk on Turing tests for a workshop on June 30th and will make up 15 robot kits for the workshop as well.
- Meena (18 June 2008): Back to Pyro (MRDS too complicated for current purposes). Have spent enough time with MRDS to have forgotten parts of Pyro tutorials, so will start with a review.
Robonova-1's battery lasted about an hour when charged for 5 hours and left standing with the power on. Will see how long battery lasts when robot is moving a bit. Realized sensors I thought were already in the robot are optional additions; only sensor robot has now is the IR for the remote control. Wondering whether the sensor might be usable for other things; unfortunately it's broken, so this can't be tested.
- Kerstin: After two frustrating weeks I have officially given up on the wall-following. Instead I trained a neural network to avoid obstacles, which went surprisingly smoothly. I will shift my focus to 'attention' now, and if I have a creative moment I might start writing my abstract.
- Meena (19 June 2008): Tried out the "catch-and-play" features of the Robonova (is indeed as easy to do as the package claimed). Tried out walking program; pretty good but sort of wobbly/non-fluid. Will examine it again after battery has charged (lasted about 40 mins after charging for a long long time) and see if better movements can be created (maybe more human-like walking motions). Also tried out the fighting and dancing moves, because I couldn't help myself. Robot is surprisingly stable when the battery's mostly charged.
Also wrote abstract, read a little about available sensors for the Robonova (can purchase sound sensors, touch sensors, light sensors, and IR sensors), Bluetooth compatibility, trying to use other languages other than Robobasic for programming the robot (a bit trickier; will probably require an interpreter to be created to translate Python/whatever code into Robobasic or something). Will read a little more about the latter, then will see about installing Pyro on me laptop cause the liveCD uses a different sort of Linux. May also try seeing just how stable the Robonova can be. Hah hah.
- Becca (18-19 June 2008): I wrote my abstract. I also read about Turing tests for the presentation I'm giving on June 30th, read through part of The Ruby Programming Language, went through several online tutorials for Ruby, and learned more about Scheme. I've done lists and recursion now. I added more ideas to my spreadsheet about the graphical language, now named Dinah for Alice's cat in Alice in Wonderland (it pays tribute both to Alice and to Scratch, which has a cat as its main character). I don't know what to do with the spreadsheet once I have it more detailed and more organized, but I guess I can figure that out.
- Becca (19 June 2008): Forgot to say that I also tested my dmg/mpkg file on the MacBook. It works fine, and I have added Numpy and PIL to it. Currently, it should download and install Numpy, PIL, Myro, xmpppy, and pyserial.
- Meena (20 June 2008): Came up with initial list of functions that can be used for doing stuff with Robonova in Myro/Pyro:
#Commands #stepForward() #stepBackward() #moveOneLeg("leg","direction") ##leg = left, right ##direction = forward, back, left, right, forOut, backOut, lOut, rOut, bend #bend() #moveArm("arm", "direction") ##arm = left, right ##direction = front, back, up, horiz, toChest #standardPose() #kick("direction") ##directon = left, right #chop("direction") ##directon = left, right #dance() #fly() #punch("direction") ##directon = left, right #read<sensor>() //no sensors to read yet :/ #playSound(pitch, length) #playMusic([listOfNotes]) ##notes = A-G ##T = tempo; ##L = low octave; ##M = mid octave; ##H = high octave; ##+,# = sharp; ##$,- = flat ##. = dotted note ##P,<sp>,(rest) = rest ##<,L = drop an octave ##>,H = raise an octave ##1 = whole note; 2 = half note, 4 = quarter note, 8 = eighth note ##6 = sixteenth note; 0 = thirty-second note
Haven't actually written them yet; read some BASIC tutorials to get a better feel for the language so I could try and figure out how to make easy Python code that will also easily translate into a BASIC format. Read some info about hardware on Robonova and think RoboBasic does something to its code to make it recognizable to the software on the robot, and that this thing can't be emulated with other languages or compilers. There is a possible way to program in C, but the steps to getting to this point went over my head since I'm not familiar enough with hardware/software engineering, and procedure was potentially harmful to the robot if not carried out correctly. Also would not necessarily make the Python problem less of a problem. Problem might be able to be resolved with new chip that can accept languages like Python, but read that they might not work as quickly as the one included due to the amount of servos they have to control simultaneously. Also would require doing a lot of things I would rather not have to do (changing boards and stuff).
Week 5, June 23 - June 27, 2008
Meena (23 June 2008): No sensors to test out; will read through Myro code to figure out how robots are connected to the computer with Myro; test out more features of Robonova and maybe see if I can make the motions more fluid and/or "human-like."
Becca (23 June 2008): Worked with Scheme. Attempted to test broken code from workshop participant, but the bluetooth kept disconnecting. Tried to update the fluke but the command prompt in Windows said the command was not a proper command. Will try it in Linux tomorrow.
Meena (24 June 2008): Was going to install Pyro on my laptop, but instructions didn't explain how to install on Ubuntu-like OSes. Will mess around with it to see if it can be installed, since installing it on my comp will make debugging/learning easier. Will continue trying to get robot to walk more convincingly.
Kerstin: I needed a break from readings and simulations, so I wrote a program that probably works much like RAVQs (I don't know much about RAVQs though, so I might be wrong). My program takes vectors with numerical entries (preferably on the same scale) as input and arranges them in a list such that the (Euclidean) distance between neighboring list elements is minimal. Once the length of the list reaches a certain threshold it is split into two lists of variable length such that the total deviation of the elements in each list from the average (arithmetic mean) vector of that list is minimal. I implemented several ways to estimate the ideal cutoff for the list split, and finally settled with the exact but computationally expensive one. Then I tested the program with real pictures. I built a "playground" for a Scribbler robot that I laid out with white paper to reduce the background noise and put several items in it (pink ball, another Scribbler etc). I programmed one Scribbler to move through the playground with an obstacle avoidance behavior for about 1000 steps, taking a color picture at each step. I fed these pictures into my program, and I was quite surprised when the program sorted the pictures by object and not by background. The endeavor didn't have a whole lot to do with robot attention, but I had a good time and I finally know what I took statistics for. Tomorrow I will get back on track and start reading the books that you (Doug) gave me.
Meena (26 June 2008): Myro code leaves me to believe that software on Scribbler flukes is specifically designed to be able to receive whatever's sent in Python, so it won't help with getting Robonova to work with Python. RoboBasic apparently doesn't support any sort of inheritance, so I can't even make an abstract set of commands to use within RoboBasic. I borderline understand how to send byte commands in C while using a bluetooth device, but of course that doesn't help much here. :] Will just write a program that allows the person to write the commands in Python and then save a Robobasic-compatible file.
Becca (24-26 June 2008): The fluke is still not upgraded, but at least it's down to now knowing the serial port name now; the command for Linux works (add ./ to beginning). I made 12/15 robots kits for Monday's demo, and will make the other 3 on Friday. I read a lot more about Ruby and about Turing tests. I also organized my comments on Alice and Scratch into a list divided by subject. Some ideas depend on which age group Dinah is aimed at.
Week 6, June 30 - July 4th, 2008
Becca (30 June 2008): I helped with the workshop for high school girls through the morning and early afternoon. We taught them a good bit of the intro. course's syllabus, at their own pace, in a few hours. Maybe the kind of lab session we did would be effective in the intro. as well. I also installed Scratch on the XO laptop, and played with a Pico Cricket. It turns out that using a Pico Board (not included in the Cricket kit), you can add its sensors to Scratch and have them affect scripts. This sort of idea will probably be useful when incorporating the robots into Dinah. I added some more ideas to the Dinah list based on comments from educators on the Scratch website, for example, including the ability to comment code.
Meena (1 July 2008): Writing program to translate the simple Python commands into roboBasic. More annoying than previously expected, but almost done with recognizing if/else statements correctly (problem comes with the "end" statement that's got to come at the end of the whole block, instead of just after if blocks or just after else blocks).
Meena (2 July 2008): Finished program. Started on a GUI, and ended up with something resembling a grey chatroom window. Looking around to see if there's a(n easy) way of putting text boxes in a graphics window so I can make something that looks a tad nicer (I could do it with JAVA >__>;;; ). Made a short help dictionary for the GUI when it gets finished. Also looked at sensors again and picked out a few that seemed cool; lurked the RoboSavvy forums to see what bluetooth devices seemed most popular. Should get some sensors in soon.
Becca (1-2 July 2008): Got more ideas for Dinah, put together an initial GUI, which has now been trashed. I think it's going to be a regular programming language that just happens to be pieced together with blocks, rather than one which focuses on graphics and doing rather than returning. Read half of the article on programming languages designed to help beginners; noticed that most of them are graphics heavy or focused on a robot, with a few that just correct syntax. I prefer the graphics heavy/robot approach.
Priscy (3 July 2008): To reiterate what I said at the meeting on Tuesday, I've been reading the Pyro tutorial online at and some articles on Developmental Robotics at. While reading the tutorial, I've been doing a couple of sample programs and exercises. Currently, I'm reading up the neural networks section of the tutorial.
Week 7, July 7th - July 11th, 2008
Meena (7 July 2008): Will be working on GUI and the robot movements; see if I can make some original ones that could be useful for general programs, as well as make the existing movements better, nicer-looking.
Becca (7-8 July 2008): Read lots of articles about Alice, including a dissertation which gave me a lot of ideas about how to implement the graphics of Dinah so that they are intuitive. Will read articles about Scratch next, as well as finish the article about the various intro languages that are used. I also designed the look of the "blocks" for Dinah, and had the idea of making them handle boxes instead of customized buttons to make them easier to work with. I think robots will be just another kind of sprite in Dinah, and a dialog asking for the com port will pop up when one is added. Hopefully, it will pop up in front of the window, instead of behind it.
Becca (10 July 2008): I drew out the initial set of code blocks to use in Dinah, other than the Myro ones (under Dinah, Robots). I also put most of them into the main Pyjama window. I combined the play/pause/stop buttons with the stepper, using tooltips to make it clear what the buttons do. I created the webpage for my project, Dinah (see higher up on this page for the link as well). I have also started looking at CodeDOM, which is a "base language" which enables translation between its included programming languages. Dinah will be linked to CodeDOM.
Becca (11 July 2008): I finished adding the code blocks to Dinah, renamed a lot of the widgets to make it easier to find them, and started writing a program in pygtk to run Pyjama. So far, it opens the window and destroys it when it's closed. I read enough about buttons and their signals to make a start on that.
Week 8, July 14 - July 18th, 2008
- Meena (16 July 2008): GUI got erased in freak Ubuntu accident, but apparently won't be needing it anyway.
Instead, have list of actions that will (as of now) be included in Myro (Along with their code letter. If you were interested.):
STANDARD_POSE 'A BEND 'B SIT 'C STEP_FORWARD 'D STEP_BACKWARD 'E STEP_LEFT 'F STEP_RIGHT 'G TURN_LEFT 'H TURN_RIGHT 'I LEFT_KICK 'J RIGHT_KICK 'K LEFT_CHOP 'L RIGHT_CHOP 'M FORWARD_STANDUP 'N BACKWARD_STANDUP 'O PUNCH_FRONT 'P PUNCH_LEFT 'Q PUNCH_RIGHT 'R TUMBLE_FORWARD 'S TUBLE_BACKWARD 'T CARTWHEEL_LEFT 'U CARTWHEEL_RIGHT 'V
Writing the Myro stuff now.
- Becca (14-16 July 2008): I figured out the drag and drop commands in GTK+ (after much banging of my head against an intangible wall), and set it up so that the four script blocks, when their "drag" button is dragged to the main script, appear in said script. It took a lot longer than it sounds like it took, and was much more complicated.
- Meena (17 July 2008): Most attempts to contact robot via serial cable and pySerial ended in failure (a few made the robot spazz and beep a lot, so they were at least successful on that note). Probably has something to do with the serial cable; bluetooth should make this process work.
Learned the art of soldering; set up the fluke to be connected to the robot via wires. Battery on the robot wasn't enough to power fluke; had to use external power source for fluke. Then fluke was able to take a picture; robot does a bit of spazzing still when turned on/off, which is strange given no program loaded on it recently should be making it move unless it receives a special character telling it to do so. Is probably reading some real old programs; have to find a way to erase what's stored on the board so I can load the command program and test the bluetooth.
- Meena (18 July 2008): Cleared old programs (hopefully). Robot having trouble with receiving commands through Bluetooth (unsure whether it has to do with hardware, Myro setup, or the pre-loaded RoboBASIC program).
EDIT: Robot was reading in binary, not ASCII. >___>
- Becca (17-18 July 2008): I got a hello world program working--initially, it ran when you clicked on 'print', but I changed it to run when you click on 'play'. I also started writing up my Dinah notes for whoever gets this project next, added the project files to svn, started working on my poster, and updated the Dinah webpage. Finally, I added a lot of the Myro blocks to the Dinah window and changed all of the existing blocks to a format which would support the drag and drop. Next week I will start setting up the drag and drop for more blocks than just the scripts and print blocks.
Week 9, July 21 - July 25th, 2008
- Meena (21 July 2008): Given the larger nature of the Robonova's present head, the fancy tumbling/cartwheel moves will not be included in the final Myro code after all.
Turned on robot with fluke; fluke started feeding all those bytes we'd sent it trying to get the bluetooth to work and the robot wouldn't stop bowing/bending until the fluke was unplugged. Was going to let the commands go through until they'd finished, but fluke and robot started running out of battery power. Will figure out problem so I can try doing something other than watching it bow repeatedly. Worked on a Powerpoint manual for Robonova; will include stuff it has, stuff it can have, and basics of how to program it to do stuff. Idea is to create something that the next person will be able to easily understand (unlike the included Instruction Manuals, which are written in Engrish and aren't always clear).
Edit: Attached on/off switch to fluke power, in order to try and limit amount of junk sent to robot (previously was plugging/unplugging the power for the fluke, which seemed to cause problems.
- Becca (21 July 2008): Added many more buttons to the drag-and-drop. Also planned how to generate code (will just read line by line and execute code, instead of creating a file, using eval() and exec() methods).
- Becca (23 July 2008): Moved scripts to script window so can switch between them. Set up creation of new tabs and drag-and-drop/script switching if only 2 tabs. Started drafting a file format for saved files to have.
Week 10, July 28th - August 1st, 2008
- Meena (28 July 2008): Turns out robot uses TTL and fluke uses RS-232, which is why nothing worked. Teyvonia is finding way to make a converter for the fluke and robot; should be completed soon. Also improved instruction manual I started on, started reading about MRDS again, and reading about serial connections in more detail.
- Becca (28 July 2008): Got multiple lines of code to drag and drop. Added more blocks to dnd, made drag_drop code a little bit prettier, and got one block to drop onto another (point onto line). | http://wiki.roboteducation.org/index.php?title=SummerSchedule2008&oldid=5324 | CC-MAIN-2020-29 | refinedweb | 6,384 | 59.13 |
Info |
Community |
Development |
myReactOS |
0000
00167 /* basic functions */
00168
00169 /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
00170 If the first character differs, the library code actually used is
00171 not compatible with the zlib.h header file used by the application.
00172 This check is automatically made by deflateInit and inflateInit.
00173 */
00174
00175 /*
00176 ZEXTERN(int) deflateInit OF((z_streamp strm, int level));
00177
00178 Initializes the internal stream state for compression. The fields
00179 zalloc, zfree and opaque must be initialized before by the caller.
00180 If zalloc and zfree are set to Z_NULL, deflateInit updates them to
00181 use default allocation functions.
00182
00183 The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
00184 1 gives best speed, 9 gives best compression, 0 gives no compression at
00185 all (the input data is simply copied a block at a time).
00186 Z_DEFAULT_COMPRESSION requests a default compromise between speed and
00187 compression (currently equivalent to level 6).
00188
00189 deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
00190 enough memory, Z_STREAM_ERROR if level is not a valid compression level,
00191 Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
00192 with the version assumed by the caller (ZLIB_VERSION).
00193 msg is set to null if there is no error message. deflateInit does not
00194 perform any compression: this will be done by deflate().
00195 */
00196
00197
00198 /*
00199 deflate compresses as much data as possible, and stops when the input
00200 buffer becomes empty or the output buffer becomes full. It may introduce some
00201 output latency (reading input without producing any output) except when
00202 forced to flush.
00203
00204 The detailed semantics are as follows. deflate performs one or both of the
00205 following actions:
00206
00207 - Compress more input starting at next_in and update next_in and avail_in
00208 accordingly. If not all input can be processed (because there is not
00209 enough room in the output buffer), next_in and avail_in are updated and
00210 processing will resume at this point for the next call of deflate().
00211
00212 - Provide more output starting at next_out and update next_out and avail_out
00213 accordingly. This action is forced if the parameter flush is non zero.
00214 Forcing flush frequently degrades the compression ratio, so this parameter
00215 should be set only when necessary (in interactive applications).
00216 Some output may be provided even if flush is not set.
00217
00218 Before the call of deflate(), the application should ensure that at least
00219 one of the actions is possible, by providing more input and/or consuming
00220 more output, and updating avail_in or avail_out accordingly; avail_out
00221 should never be zero before the call. The application can consume the
00222 compressed output when it wants, for example when the output buffer is full
00223 (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
00224 and with zero avail_out, it must be called again after making room in the
00225 output buffer because there might be more output pending.
00226
00227 If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
00228 flushed to the output buffer and the output is aligned on a byte boundary, so
00229 that the decompressor can get all input data available so far. (In particular
00230 avail_in is zero after the call if enough output space has been provided
00231 before the call.) Flushing may degrade compression for some compression
00232 algorithms and so it should be used only when necessary.
00233
00234 If flush is set to Z_FULL_FLUSH, all output is flushed as with
00235 Z_SYNC_FLUSH, and the compression state is reset so that decompression can
00236 restart from this point if previous compressed data has been damaged or if
00237 random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
00238 the compression.
00239
00240 If deflate returns with avail_out == 0, this function must be called again
00241 with the same value of the flush parameter and more output space (updated
00242 avail_out), until the flush is complete (deflate returns with non-zero
00243 avail_out).
00244
00245 If the parameter flush is set to Z_FINISH, pending input is processed,
00246 pending output is flushed and deflate returns with Z_STREAM_END if there
00247 was enough output space; if deflate returns with Z_OK, this function must be
00248 called again with Z_FINISH and more output space (updated avail_out) but no
00249 more input data, until it returns with Z_STREAM_END or an error. After
00250 deflate has returned Z_STREAM_END, the only possible operations on the
00251 stream are deflateReset or deflateEnd.
00252
00253 Z_FINISH can be used immediately after deflateInit if all the compression
00254 is to be done in a single step. In this case, avail_out must be at least
00255 0.1% larger than avail_in plus 12 bytes. If deflate does not return
00256 Z_STREAM_END, then it must be called again as described above.
00257
00258 deflate() sets strm->adler to the adler32 checksum of all input read
00259 so far (that is, total_in bytes).
00260
00261 deflate() may update data_type if it can make a good guess about
00262 the input data type (Z_ASCII or Z_BINARY). In doubt, the data is considered
00263 binary. This field is only for information purposes and does not affect
00264 the compression algorithm in any manner.
00265
00266 deflate() returns Z_OK if some progress has been made (more input
00267 processed or more output produced), Z_STREAM_END if all input has been
00268 consumed and all output has been produced (only when flush is set to
00269 Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
00270 if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
00271 (for example avail_in or avail_out was zero).
00272 */
00273
00274
00275 /*
00276 All dynamically allocated data structures for this stream are freed.
00277 This function discards any unprocessed input and does not flush any
00278 pending output.
00279
00280 deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
00281 stream state was inconsistent, Z_DATA_ERROR if the stream was freed
00282 prematurely (some input or output was discarded). In the error case,
00283 msg may be set but then points to a static string (which must not be
00284 deallocated).
00285 */
00286
00287
00288 /*
00289 ZEXTERN(int) inflateInit OF((z_streamp strm));
00290
00291 Initializes the internal stream state for decompression. The fields
00292 next_in, avail_in, zalloc, zfree and opaque must be initialized before by
00293 the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
00294 value depends on the compression method), inflateInit determines the
00295 compression method from the zlib header and allocates all data structures
00296 accordingly; otherwise the allocation will be deferred to the first call of
00297 inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
00298 use default allocation functions.
00299
00300 inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
00301 memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
00302 version assumed by the caller. msg is set to null if there is no error
00303 message. inflateInit does not perform any decompression apart from reading
00304 the zlib header if present: this will be done by inflate(). (So next_in and
00305 avail_in may be modified, but next_out and avail_out are unchanged.)
00306 */
00307
00308
00309 ZEXTERN(int) inflate OF((z_streamp strm, int flush));
00310 /*
00311 inflate decompresses as much data as possible, and stops when the input
00312 buffer becomes empty or the output buffer becomes full. It may some
00313 introduce some output latency (reading input without producing any output)
00314 except when forced to flush.
00315
00316 The detailed semantics are as follows. inflate performs one or both of the
00317 following actions:
00318
00319 - Decompress more input starting at next_in and update next_in and avail_in
00320 accordingly. If not all input can be processed (because there is not
00321 enough room in the output buffer), next_in is updated and processing
00322 will resume at this point for the next call of inflate().
00323
00324 - Provide more output starting at next_out and update next_out and avail_out
00325 accordingly. inflate() provides as much output as possible, until there
00326 is no more input data or no more space in the output buffer (see below
00327 about the flush parameter).
00328
00329 Before the call of inflate(), the application should ensure that at least
00330 one of the actions is possible, by providing more input and/or consuming
00331 more output, and updating the next_* and avail_* values accordingly.
00332 The application can consume the uncompressed output when it wants, for
00333 example when the output buffer is full (avail_out == 0), or after each
00334 call of inflate(). If inflate returns Z_OK and with zero avail_out, it
00335 must be called again after making room in the output buffer because there
00336 might be more output pending.
00337
00338 If the parameter flush is set to Z_SYNC_FLUSH, inflate flushes as much
00339 output as possible to the output buffer. The flushing behavior of inflate is
00340 not specified for values of the flush parameter other than Z_SYNC_FLUSH
00341 and Z_FINISH, but the current implementation actually flushes as much output
00342 as possible anyway.
00343
00344 inflate() should normally be called until it returns Z_STREAM_END or an
00345 error. However if all decompression is to be performed in a single step
00346 (a single call of inflate), the parameter flush should be set to
00347 Z_FINISH. In this case all pending input is processed and all pending
00348 output is flushed; avail_out must be large enough to hold all the
00349 uncompressed data. (The size of the uncompressed data may have been saved
00350 by the compressor for this purpose.) The next operation on this stream must
00351 be inflateEnd to deallocate the decompression state. The use of Z_FINISH
00352 is never required, but can be used to inform inflate that a faster routine
00353 may be used for the single inflate() call.
00354
00355 If a preset dictionary is needed at this point (see inflateSetDictionary
00356 below), inflate sets strm-adler to the adler32 checksum of the
00357 dictionary chosen by the compressor and returns Z_NEED_DICT; otherwise
00358 it sets strm->adler to the adler32 checksum of all output produced
00359 so far (that is, total_out bytes) and returns Z_OK, Z_STREAM_END or
00360 an error code as described below. At the end of the stream, inflate()
00361 checks that its computed adler32 checksum is equal to that saved by the
00362 compressor and returns Z_STREAM_END only if the checksum is correct.
00363
00364 inflate() returns Z_OK if some progress has been made (more input processed
00365 or more output produced), Z_STREAM_END if the end of the compressed data has
00366 been reached and all uncompressed output has been produced, Z_NEED_DICT if a
00367 preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
00368 corrupted (input stream not conforming to the zlib format or incorrect
00369 adler32 checksum), Z_STREAM_ERROR if the stream structure was inconsistent
00370 (for example if next_in or next_out was NULL), Z_MEM_ERROR if there was not
00371 enough memory, Z_BUF_ERROR if no progress is possible or if there was not
00372 enough room in the output buffer when Z_FINISH is used. In the Z_DATA_ERROR
00373 case, the application may then call inflateSync to look for a good
00374 compression block.
00375 */
00376
00377
00378 ZEXTERN(int) inflateEnd OF((z_streamp strm));
00379 /*
00380 All dynamically allocated data structures for this stream are freed.
00381 This function discards any unprocessed input and does not flush any
00382 pending output.
00383
00384 inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
00385 was inconsistent. In the error case, msg may be set but then points to a
00386 static string (which must not be deallocated).
00387 */
00388
00389 /* Advanced functions */
00390
00391 /*
00392 The following functions are needed only in some special applications.
00393 */
00394
00395 /*
00396 ZEXTERN(int) deflateInit2 OF((z_streamp strm,
00397 int level,
00398 int method,
00399 int windowBits,
00400 int memLevel,
00401 int strategy));
00402
00403 This is another version of deflateInit with more compression options. The
00404 fields next_in, zalloc, zfree and opaque must be initialized before by
00405 the caller.
00406
00407 The method parameter is the compression method. It must be Z_DEFLATED in
00408 this version of the library.
00409
00410 The windowBits parameter is the base two logarithm of the window size
00411 (the size of the history buffer). It should be in the range 8..15 for this
00412 version of the library. Larger values of this parameter result in better
00413 compression at the expense of memory usage. The default value is 15 if
00414 deflateInit is used instead.
00415
00416 The memLevel parameter specifies how much memory should be allocated
00417 for the internal compression state. memLevel=1 uses minimum memory but
00418 is slow and reduces compression ratio; memLevel=9 uses maximum memory
00419 for optimal speed. The default value is 8. See zconf.h for total memory
00420 usage as a function of windowBits and memLevel.
00421
00422 The strategy parameter is used to tune the compression algorithm. Use the
00423 value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
00424 filter (or predictor), or Z_HUFFMAN_ONLY to force Huffman encoding only (no
00425 string match). Filtered data consists mostly of small values with a
00426 somewhat random distribution. In this case, the compression algorithm is
00427 tuned to compress them better. The effect of Z_FILTERED is to force more
00428 Huffman coding and less string matching; it is somewhat intermediate
00429 between Z_DEFAULT and Z_HUFFMAN_ONLY. The strategy parameter only affects
00430 the compression ratio but not the correctness of the compressed output even
00431 if it is not set appropriately.
00432
00433 deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
00434 memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
00435 method). msg is set to null if there is no error message. deflateInit2 does
00436 not perform any compression: this will be done by deflate().
00437 */
00438
00439 /*
00440 Initializes the compression dictionary from the given byte sequence
00441 without producing any compressed output. This function must be called
00442 immediately after deflateInit, deflateInit2 or deflateReset, before any
00443 call of deflate. The compressor and decompressor must use exactly the same
00444 dictionary (see inflateSetDictionary).
00445
00446 The dictionary should consist of strings (byte sequences) that are likely
00447 to be encountered later in the data to be compressed, with the most commonly
00448 used strings preferably put towards the end of the dictionary. Using a
00449 dictionary is most useful when the data to be compressed is short and can be
00450 predicted with good accuracy; the data can then be compressed better than
00451 with the default empty dictionary.
00452
00453 Depending on the size of the compression data structures selected by
00454 deflateInit or deflateInit2, a part of the dictionary may in effect be
00455 discarded, for example if the dictionary is larger than the window size in
00456 deflate or deflate2. Thus the strings most likely to be useful should be
00457 put at the end of the dictionary, not at the front.
00458
00459 Upon return of this function, strm->adler is set to the Adler32 value
00460 of the dictionary; the decompressor may later use this value to determine
00461 which dictionary has been used by the compressor. (The Adler32 value
00462 applies to the whole dictionary even if only a subset of the dictionary is
00463 actually used by the compressor.)
00464
00465 deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
00466 parameter is invalid (such as NULL dictionary) or the stream state is
00467 inconsistent (for example if deflate has already been called for this stream
00468 or if the compression method is bsort). deflateSetDictionary does not
00469 perform any compression: this will be done by deflate().
00470 */
00471
00472 /*
00473 Sets the destination stream as a complete copy of the source stream.
00474
00475 This function can be useful when several compression strategies will be
00476 tried, for example when there are several ways of pre-processing the input
00477 data with a filter. The streams that will be discarded should then be freed
00478 by calling deflateEnd. Note that deflateCopy duplicates the internal
00479 compression state which can be quite large, so this strategy is slow and
00480 can consume lots of memory.
00481
00482 deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
00483 enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
00484 (such as zalloc being NULL). msg is left unchanged in both source and
00485 destination.
00486 */
00487
00488 /*
00489 This function is equivalent to deflateEnd followed by deflateInit,
00490 but does not free and reallocate all the internal compression state.
00491 The stream will keep the same compression level and any other attributes
00492 that may have been set by deflateInit2.
00493
00494 deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
00495 stream state was inconsistent (such as zalloc or state being NULL).
00496 */
00497
00498 /*
00499 Dynamically update the compression level and compression strategy. The
00500 interpretation of level and strategy is as in deflateInit2. This can be
00501 used to switch between compression and straight copy of the input data, or
00502 to switch to a different kind of input data requiring a different
00503 strategy. If the compression level is changed, the input available so far
00504 is compressed with the old level (and may be flushed); the new level will
00505 take effect only at the next call of deflate().
00506
00507 Before the call of deflateParams, the stream state must be set as for
00508 a call of deflate(), since the currently available input may have to
00509 be compressed and flushed. In particular, strm->avail_out must be non-zero.
00510
00511 deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
00512 stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
00513 if strm->avail_out was zero.
00514 */
00515
00516 /*
00517 ZEXTERN(int) inflateInit2 OF((z_streamp strm,
00518 int windowBits));
00519
00520 This is another version of inflateInit with an extra parameter. The
00521 fields next_in, avail_in, zalloc, zfree and opaque must be initialized
00522 before by the caller.
00523
00524 The windowBits parameter is the base two logarithm of the maximum window
00525 size (the size of the history buffer). It should be in the range 8..15 for
00526 this version of the library. The default value is 15 if inflateInit is used
00527 instead. If a compressed stream with a larger window size is given as
00528 input, inflate() will return with the error code Z_DATA_ERROR instead of
00529 trying to allocate a larger window.
00530
00531 inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
00532 memory, Z_STREAM_ERROR if a parameter is invalid (such as a negative
00533 memLevel). msg is set to null if there is no error message. inflateInit2
00534 does not perform any decompression apart from reading the zlib header if
00535 present: this will be done by inflate(). (So next_in and avail_in may be
00536 modified, but next_out and avail_out are unchanged.)
00537 */
00538
00539 /*
00540 Initializes the decompression dictionary from the given uncompressed byte
00541 sequence. This function must be called immediately after a call of inflate
00542 if this call returned Z_NEED_DICT. The dictionary chosen by the compressor
00543 can be determined from the Adler32 value returned by this call of
00544 inflate. The compressor and decompressor must use exactly the same
00545 dictionary (see deflateSetDictionary).
00546
00547 inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
00548 parameter is invalid (such as NULL dictionary) or the stream state is
00549 inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
00550 expected one (incorrect Adler32 value). inflateSetDictionary does not
00551 perform any decompression: this will be done by subsequent calls of
00552 inflate().
00553 */
00554
00555 /*
00556 Skips invalid compressed data until a full flush point (see above the
00557 description of deflate with Z_FULL_FLUSH) can be found, or until all
00558 available input is skipped. No output is provided.
00559
00560 inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
00561 if no more input was provided, Z_DATA_ERROR if no flush point has been found,
00562 or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
00563 case, the application may save the current current value of total_in which
00564 indicates where valid compressed data was found. In the error case, the
00565 application may repeatedly call inflateSync, providing more input each time,
00566 until success or end of the input data.
00567 */
00568
00569 ZEXTERN(int) inflateReset OF((z_streamp strm));
00570 /*
00571 This function is equivalent to inflateEnd followed by inflateInit,
00572 but does not free and reallocate all the internal decompression state.
00573 The stream will keep attributes that may have been set by inflateInit2.
00574
00575 inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
00576 stream state was inconsistent (such as zalloc or state being NULL).
00577 */
00578
00579
00580 /* utility functions */
00581
00582 /*
00583 The following utility functions are implemented on top of the
00584 basic stream-oriented functions. To simplify the interface, some
00585 default options are assumed (compression level and memory usage,
00586 standard memory allocation functions). The source code of these
00587 utility functions can easily be modified if you need special options.
00588 */
00589
00590 /*
00591 Compresses the source buffer into the destination buffer. sourceLen is
00592 the byte length of the source buffer. Upon entry, destLen is the total
00593 size of the destination buffer, which must be at least 0.1% larger than
00594 sourceLen plus 12 bytes. Upon exit, destLen is the actual size of the
00595 compressed buffer.
00596 This function can be used to compress a whole file at once if the
00597 input file is mmap'ed.
00598 compress returns Z_OK if success, Z_MEM_ERROR if there was not
00599 enough memory, Z_BUF_ERROR if there was not enough room in the output
00600 buffer.
00601 */
00602
00603 /*
00604 Compresses the source buffer into the destination buffer. The level
00605 parameter has the same meaning as in deflateInit. sourceLen is the byte
00606 length of the source buffer. Upon entry, destLen is the total size of the
00607 destination buffer, which must be at least 0.1% larger than sourceLen plus
00608 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
00609
00610 compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
00611 memory, Z_BUF_ERROR if there was not enough room in the output buffer,
00612 Z_STREAM_ERROR if the level parameter is invalid.
00613 */
00614
00615 /*
00616 Decompresses the source buffer into the destination buffer. sourceLen is
00617 the byte length of the source buffer. Upon entry, destLen is the total
00618 size of the destination buffer, which must be large enough to hold the
00619 entire uncompressed data. (The size of the uncompressed data must have
00620 been saved previously by the compressor and transmitted to the decompressor
00621 by some mechanism outside the scope of this compression library.)
00622 Upon exit, destLen is the actual size of the compressed buffer.
00623 This function can be used to decompress a whole file at once if the
00624 input file is mmap'ed.
00625
00626 uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
00627 enough memory, Z_BUF_ERROR if there was not enough room in the output
00628 buffer, or Z_DATA_ERROR if the input data was corrupted.
00629 */
00630
00631
00632 /*
00633 Opens a gzip (.gz) file for reading or writing. The mode parameter
00634 is as in fopen ("rb" or "wb") but can also include a compression level
00635 ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
00636 Huffman only compression as in "wb1h". (See the description
00637 of deflateInit2 for more information about the strategy parameter.)
00638
00639 gzopen can be used to read a file which is not in gzip format; in this
00640 case gzread will directly read from the file without decompression.
00641
00642 gzopen returns NULL if the file could not be opened or if there was
00643 insufficient memory to allocate the (de)compression state; errno
00644 can be checked to distinguish the two cases (if errno is zero, the
00645 zlib error is Z_MEM_ERROR). */
00646
00647 /*
00648 gzdopen() associates a gzFile with the file descriptor fd. File
00649 descriptors are obtained from calls like open, dup, creat, pipe or
00650 fileno (in the file has been previously opened with fopen).
00651 The mode parameter is as in gzopen.
00652 The next call of gzclose on the returned gzFile will also close the
00653 file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
00654 descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
00655 gzdopen returns NULL if there was insufficient memory to allocate
00656 the (de)compression state.
00657 */
00658
00659 /*
00660 Dynamically update the compression level or strategy. See the description
00661 of deflateInit2 for the meaning of these parameters.
00662 gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
00663 opened for writing.
00664 */
00665
00666 /*
00667 Reads the given number of uncompressed bytes from the compressed file.
00668 If the input file was not in gzip format, gzread copies the given number
00669 of bytes into the buffer.
00670 gzread returns the number of uncompressed bytes actually read (0 for
00671 end of file, -1 for error). */
00672
00673 /*
00674 Writes the given number of uncompressed bytes into the compressed file.
00675 gzwrite returns the number of uncompressed bytes actually written
00676 (0 in case of error).
00677 */
00678
00679 /*
00680 Converts, formats, and writes the args to the compressed file under
00681 control of the format string, as in fprintf. gzprintf returns the number of
00682 uncompressed bytes actually written (0 in case of error).
00683 */
00684
00685 /*
00686 Writes the given null-terminated string to the compressed file, excluding
00687 the terminating null character.
00688 gzputs returns the number of characters written, or -1 in case of error.
00689 */
00690
00691 /*
00692 Reads bytes from the compressed file until len-1 characters are read, or
00693 a newline character is read and transferred to buf, or an end-of-file
00694 condition is encountered. The string is then terminated with a null
00695 character.
00696 gzgets returns buf, or Z_NULL in case of error.
00697 */
00698
00699 /*
00700 Writes c, converted to an unsigned char, into the compressed file.
00701 gzputc returns the value that was written, or -1 in case of error.
00702 */
00703
00704 /*
00705 Reads one byte from the compressed file. gzgetc returns this byte
00706 or -1 in case of end of file or error.
00707 */
00708
00709 /*
00710 Flushes all pending output into the compressed file. The parameter
00711 flush is as in the deflate() function. The return value is the zlib
00712 error number (see function gzerror below). gzflush returns Z_OK if
00713 the flush parameter is Z_FINISH and all output could be flushed.
00714 gzflush should be called only when strictly necessary because it can
00715 degrade compression.
00716 */
00717
00718 /*
00719 Sets the starting position for the next gzread or gzwrite on the
00720 given compressed file. The offset represents a number of bytes in the
00721 uncompressed data stream. The whence parameter is defined as in lseek(2);
00722 the value SEEK_END is not supported.
00723 If the file is opened for reading, this function is emulated but can be
00724 extremely slow. If the file is opened for writing, only forward seeks are
00725 supported; gzseek then compresses a sequence of zeroes up to the new
00726 starting position.
00727
00728 gzseek returns the resulting offset location as measured in bytes from
00729 the beginning of the uncompressed stream, or -1 in case of error, in
00730 particular if the file is opened for writing and the new starting position
00731 would be before the current position.
00732 */
00733
00734 /*
00735 Rewinds the given file. This function is supported only for reading.
00736
00737 gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
00738 */
00739
00740 /*
00741 Returns the starting position for the next gzread or gzwrite on the
00742 given compressed file. This position represents a number of bytes in the
00743 uncompressed data stream.
00744
00745 gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
00746 */
00747
00748 /*
00749 Returns 1 when EOF has previously been detected reading the given
00750 input stream, otherwise zero.
00751 */
00752
00753 /*
00754 Flushes all pending output if necessary, closes the compressed file
00755 and deallocates all the (de)compression state. The return value is the zlib
00756 error number (see function gzerror below).
00757 */
00758
00759 /*
00760 Returns the error message for the last error which occurred on the
00761 given compressed file. errnum is set to zlib error number. If an
00762 error occurred in the file system and not in the compression library,
00763 errnum is set to Z_ERRNO and the application may consult errno
00764 to get the exact error code.
00765 */
00766
00767 /* checksum functions */
00768
00769 /*
00770 These functions are not related to compression but are exported
00771 anyway because they might be useful in applications using the
00772 compression library.
00773 */
00774
00775 ZEXTERN(uLong) adler32 OF((uLong adler, const Bytef *buf, uInt len));
00776
00777 /*
00778 Update a running Adler-32 checksum with the bytes buf[0..len-1] and
00779 return the updated checksum. If buf is NULL, this function returns
00780 the required initial value for the checksum.
00781 An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
00782 much faster. Usage example:
00783
00784 uLong adler = adler32(0L, Z_NULL, 0);
00785
00786 while (read_buffer(buffer, length) != EOF) {
00787 adler = adler32(adler, buffer, length);
00788 }
00789 if (adler != original_adler) error();
00790 */
00791
00792 /*
00793 Update a running crc with the bytes buf[0..len-1] and return the updated
00794 crc. If buf is NULL, this function returns the required initial value
00795 for the crc. Pre- and post-conditioning (one's complement) is performed
00796 within this function so it shouldn't be done by the application.
00797 Usage example:
00798
00799 uLong crc = crc32(0L, Z_NULL, 0);
00800
00801 while (read_buffer(buffer, length) != EOF) {
00802 crc = crc32(crc, buffer, length);
00803 }
00804 if (crc != original_crc) error();
00805 */
00806
00807
00808 /* various hacks, don't look :) */
00809
00810 /* deflateInit and inflateInit are macros to allow checking the zlib version
00811 * and the compiler's view of z_stream:
00812 */
00813 ZEXTERN(int) inflateInit2_ OF((z_streamp strm, int windowBits,
00814 const char *version, int stream_size));
00815 #define deflateInit(strm, level) \
00816 deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
00817 #define inflateInit(strm) \
00818 inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
00819 #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
00820 deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
00821 (strategy), ZLIB_VERSION, sizeof(z_stream))
00822 #define inflateInit2(strm, windowBits) \
00823 inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
00824
00825
00826 #ifdef __cplusplus
00827 }
00828 #endif
00829
00830 #endif /* _ZLIB_H */ | http://doxygen.reactos.org/d7/d8d/lib_23rdparty_2freetype_2src_2gzip_2zlib_8h_source.html | crawl-003 | refinedweb | 5,240 | 58.52 |
30 July 2010 09:43 [Source: ICIS news]
SHANGHAI (ICIS)--Revenue from China’s petroleum and chemical industries in the first six months of 2010 rose 41% year on year to yuan (CNY) 4,110bn ($607.1bn) as a result of rising output, prices and domestic demand, an industry organisation said on Friday.
According to a report released by the China Petroleum and Chemical Industry Federation (CPCIF), 74 of the 78 petrochemical products that the federation monitors showed year-on-year output gains in the first six months of this year.
China produced ?xml:namespace>
Ethylene output rose by 25.5% year on year to
Imports in China's petroleum and chemical industries rose by 71% year on year to $158.5bn (€122.04bn) and exports increased by 40% to $61.5bn.
Despite the gains, the industries' imports and exports had yet to return to levels seen before the global economic crisis, the federation said.
However, the industries were expected to slow down in the second half of the year amid a deceleration in China’s economy.
Full-year sales in the industries for 2010 were expected to rise by 29.3% from last year to CNY8,570bn, with sales growth in the third quarter predicted to increase by 25.2% year on year and that for the fourth quarter to go up by 16.5%, according to the report.
CPCIF, formerly known as the China Petroleum and Chemical Industry Association (CPCIA), changed to its present name on 7 May.
($1 = CNY6.77/$1 = €0.76)
For information on China-based producers like Sinopec, | http://www.icis.com/Articles/2010/07/30/9380721/china-petroleum-chemical-industries-post-41-rise-in-h1-revenue.html | CC-MAIN-2015-18 | refinedweb | 264 | 54.02 |
iEventQueue Struct Reference
[Event handling]
This interface represents a general event queue. More...
#include <iutil/eventq.h>
Detailed Description
This interface represents a general event queue.
Events may be posted to the queue by various sources. Listeners (implementing iEventHandler) can register to receive notification when various events are processed. Typically, one instance of this object is available from the shared-object registry (iObjectRegistry).
Main creators of instances implementing this interface:
Main ways to get pointers to this interface:
Definition at line 56 of file eventq.h.
Member Function Documentation
Clear event queue.
Implemented in csEventQueue.
Create an event with the broadcast flag set.
Draw from the pool if any are available, else create a new event in the pool and use it.
Implemented in csEventQueue.
Create an event, from the pool if there are any free events available.
Else create a new event in the pool and use it.
Implemented in csEventQueue.
Register an event plug and return a new outlet.
Any module which generates events should consider using this interface for posting those events to the queue. The module should implement the iEventPlug interface and register that interface with this method. In return, an iEventOutlet object will be created which can be used to actually post events to the queue. It is the caller's responsibility to send a DecRef() message to the returned event outlet when it is no longer needed.
Implemented in csEventQueue.
Dispatch a single event from the queue.
This is normally called by Process() once for each event in the queue. Events are dispatched to the appropriate listeners (implementors of iEventHandler) which have been registered via RegisterListener().
Implemented in csEventQueue.
Get next event from queue; returns a null reference if no events are present.
There is rarely any need to manually retrieve events from the queue. Instead, normal event processing via Process() takes care of this responsibility. iEventQueue gives up ownership of the returned iEvent.
Implemented in csEventQueue.
Get the event cord for a given category and subcategory.
This allows events to be delivered immediately, bypassing the normal event queue, to a chain of plugins that register with the implementation of iEventCord returned by this function. The category and subcategory are matched against the category and subcategory of each actual iEvent.
Implemented in csEventQueue.
Get a public event outlet for posting just an event.
In general most modules should create their own private outlet via CreateEventOutlet() and register as a normal event plug. However, there are cases when you just need to post one event from time to time; in these cases it is easier to post it without the bulk of creating a new iEventPlug interface. In these cases, you can post the event by obtaining the shared event outlet from GetEventOutlet(), and use it to post an event instead.
Implemented in csEventQueue.
Query if queue is empty.
Implemented in csEventQueue.
Place an event into queue.
In general, clients should post events to the queue via an iEventOutlet rather than directly via Post(), however there may be certain circumanstances where posting directly to the queue is preferred.
- Remarks:
- Post() takes ownership of the event. That means that you MUST NOT DecRef() the event after passing it to Post(). Instead, if you want to keep it, IncRef() it.
Implemented in csEventQueue.
Process the event queue.
Calls Dispatch() once for each event in the queue in order to actually dispatch the event. Typically, this method is invoked by the host application on a periodic basis (often from the host's own event loop) in order to give Crystal Space modules a chance to run and respond to events.
Implemented in csEventQueue.
Register a listener with the event scheduling subsystem.
The handler will name itself via the iEventHandler::GetGenericID() method.
Implemented in csEventQueue..
Implemented in csEventQueue.
Unregister a listener and drop all of its subscriptions.
It is important to call RemoveListener() before deleting your event handler!
Implemented in csEventQueue.
Subscribe an event listener to a given list of event subtrees.
The list shold be terminated with the CS_EVENTLIST_END token.
Implemented in csEventQueue.
Subscribe an event listener to a given event subtree.
For example, subscribers to "crystalspace.input.keyboard" will receive "crystalspace.input.keyboard.up" and "crystalspace.input.keyboard.down" events. csEventIDs should be retrieved from csEventNameRegistry::GetID().
Implemented in csEventQueue.
Unsubscribe an event listener from a particular set of event subtrees.
This should only be called on event names which were used as arguments to Subscribe or RegisterListener; otherwise, the results are undefined. It is important to call RemoveListener() before deleting your event handler!
Implemented in csEventQueue.
Unsubscribe an event listener from a particular event subtree.
This should only be called on an event name which was used as an argument to Subscribe or to RegisterListener; otherwise, the results are undefined.
Implemented in csEventQueue.
The documentation for this struct was generated from the following file:
Generated for Crystal Space 2.0 by doxygen 1.6.1 | http://www.crystalspace3d.org/docs/online/api-2.0/structiEventQueue.html | CC-MAIN-2015-06 | refinedweb | 819 | 60.61 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.