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 |
|---|---|---|---|---|---|
Bash by Example, Part 1
Fundamental programming in the Bourne again shell (bash)
Introduction
You.
Bash confusion.
Environment variables:
$ myvar='This is my environment variable!').
Note:
$ echo $myvar This is my environment variable!
By preceding the name of our environment variable with a $, we can cause bash to replace it with the value of myvar. In bash terminology, this is called "variable expansion". But, what if we try the following:
$ echo foo$myvarbar foo:
$ echo foo${myvar}bar fooThis is my environment variable!bar:
#include <stdio.h> #include <stdlib.h> int main(void) { char *myenvvar=getenv("EDITOR"); printf("The editor environment variable is set to %s\n",myenvvar); }
Save the above source into a file called myenv.c, and then compile it by issuing the command:
$ gcc myenv.c -o myenv
Now, there will be an executable program in your directory that, when run, will print the value of the EDITOR environment variable, if any. This is what happens when I run it on my machine:
$ ./myenv The editor environment variable is set to (null)
Hmmm... because the EDITOR environment variable was not set to anything, the C program gets a null string. Let's try setting it to a specific value:
$ EDITOR=xemacs $ ./myenv The editor environment variable is set to (null)
While you might have expected myenv to print the value "xemacs", it didn't quite work, because we didn't export the EDITOR environment variable. This time, we'll get it working:
$ export EDITOR $ ./myenv The editor environment variable is set to xemacs
So, you have seen with your very own eyes that another process (in this case our example C program) cannot see the environment variable until it is exported. Incidentally, if you want, you can define and export an environment variable using one line, as follows:
$ export EDITOR=xemacs
It works identically to the two-line version. This would be a good time to show how to erase an environment variable by using unset:
$ unset EDITOR $ ./myenv The editor environment variable is set to (null) /usr/local/share/doc/foo/foo.txt foo.txt $ basename /usr/home/drobbins drobbins
basename is quite a handy tool for chopping up strings. It's companion, called dirname, returns the "other" part of the path that basename throws away:
$ dirname /usr/local/share/doc/foo/foo.txt /usr/local/share/doc/foo $ dirname /usr/home/drobbins/ /usr/home
Note
Both dirname and basename do not look at any files or directories on disk; they are purely string manipulation commands.
Command substitution
One very handy thing to know is how to create an environment variable that contains the result of an executable command. This is very easy to do:
$ MYDIR=$(dirname /usr/local/share/doc/foo/foo.txt) $ echo $MYDIR /usr/local/share/doc/foo
What we did above is called command substitution. Several things are worth noticing in this example. On the first line, we simply enclosed the command we wanted to execute with $( ).
Note that it is also possible to do the same thing using backquotes, the keyboard key that normally sits above the Tab key:
$ MYDIR=`dirname /usr/local/share/doc/foo/foo.txt` $ echo $MYDIR /usr/local/share/doc/foo:
$ MYFILES=$(ls /etc | grep pa) $ echo $MYFILES pam.d passwd
It's also worth pointing out that $( ) is generally preferred over ` ` in shell scripts because it is more universally supported across different shells, is easier to type and read, and is less complicated to use in a nested form, as follows:
$ MYFILES=$(ls $(dirname foo/bar/oni)):
$ MYVAR=foodforthought.jpg $ echo ${MYVAR##*fo} rthought.jpg $ echo ${MYVAR#*fo} odforthought.j:
f fo MATCHES *fo foo food foodf foodfo MATCHES *fo foodfor foodfort foodforth foodfortho foodforthou foodforthoug foodforthought foodforthought.j foodforthought.jp foodforthought.jpg:
$ MYFOO="chickensoup.tar.gz" $ echo ${MYFOO%%.*} chickensoup $ echo ${MYFOO%.*} chickensoup.tar
As you can see, the % and %% variable expansion options work identically to # and ##, except they remove the matching wildcard from the end of the string. Note that you don't have to use the "*" character if you wish to remove a specific substring from the end:
MYFOOD="chickensoup" $ echo ${MYFOOD%%soup} chicken:
$ EXCLAIM=cowabunga $ echo ${EXCLAIM:0:3} cow $ echo ${EXCLAIM:3:7} abunga
This form of string chopping can come in quite handy; simply specify the character to start from and the length of the substring, all separated by colons.
Applying string chopping:
#!/bin/bash if [ "${1##*.}" = "tar" ] then echo This appears to be a tarball. else echo At first glance, this does not appear to be a tarball. fi
To run this script, enter it into a file called mytar.sh, and type chmod 755 mytar.sh to make it executable. Then, give it a try on a tarball, as follows:
$ ./mytar.sh thisfile.tar This appears to be a tarball. $ ./mytar.sh thatfile.gz At first glance, this does not appear to be a tarball.:
if [ condition ] then action fi
This one performs an action only if condition is true, otherwise it performs no action and continues executing any lines following the "fi".
if [ condition ] then action elif [ condition2 ] then action2 . . . elif [ condition3 ] then else actionx.
Next time!
Resources
- Read Bash by Example, Part 2
- Read Bash by Example, Part 3
- Visit GNU's bash home page | http://www.funtoo.org/Bash_by_Example,_Part_1 | CC-MAIN-2014-52 | refinedweb | 878 | 56.66 |
The Aspose.Words.Layout namespace provides classes that allow to access information such as on what page and where on a page particular document elements are positioned, when the document is formatted into pages.
Specifies the rendering mode for document comments.
Shows how to show comments when saving a document to a rendered format.
Represents different behaviors when computing page numbers in a continuous section that restarts page numbering.
Shows how to control page numbering in a continuous section.
Types of the layout entities.
Shows ways of traversing a document's layout entities.
A code of event raised during page layout model build and rendering. Page layout model is built in two steps. First, "conversion step", this is when page layout pulls document content and creates object graph. Second, "reflow step", this is when structures are split, merged and arranged into pages. Depending of the operation which triggered build, page layout model may or may not be further rendered into fixed page format. For example, computing number of pages in the document or updating fields does not require rendering, whereas export to Pdf does.
Shows how to track layout changes with a layout callback.
Allows to specify color of document revisions.
Shows how to alter the appearance of revisions in a rendered output document.
Allows to specify decoration effect for revisions of document text.
Shows how to modify the appearance of revisions.
Specifies which revisions are rendered in balloons.
Shows how to modify the appearance of revisions. | https://reference.aspose.com/words/cpp/namespace/aspose.words.layout | CC-MAIN-2022-27 | refinedweb | 247 | 50.63 |
A systems and the underlying infrastructure is no walk in the park. So it has taken some time to understand and thus, write about.
But in the spirit of learning in public and sharing my own experiences, it's time to share a bit.
In this post, I won't be running through the basics of K8s. I won't be laying out how I provision or maintain clusters within AWS. I also won't be diving into complex things you can run within a cluster.
Those are all great future blog posts. If those are ideas that inspire you to write your own posts, do it!
Instead, I'm going to start with a topic that is critical when it comes to working with any new technology, tooling. Without good tools in the eco-system surrounding a given technology, the worse it is to use.
So in this post, I am going to share the three tools I use when working with Kubernetes clusters. Major kudos to my coworkers that have often pointed me towards these tools. Disclaimer: these are my opinions on tools that work for me, your situation will be different.
1.
kubectx for managing many K8s clusters
When interacting with K8s clusters, you do so by using their
kubeconfig file.
kubectl uses the information inside of your
kubeconfig file to connect to the API server running within your cluster.
When only interacting with one cluster, your
kubeconfig is going to be straightforward. It only has one cluster inside of it. Thus
kubectl commands like
kubectl get ns will get all the namespaces inside of the one cluster.
But things get a more painful when you have more than one cluster. In that scenario, you have many clusters and contexts defined inside of your one
kubeconfig file.
Say you have two clusters with their respective contexts in your
kubeconfig,
foo and
bar. Now to list the namespaces in
foo you would run the following commands:
kubectl config use-context foo kubectl get ns
Then when you want to switch to the
bar cluster you have to run the
use-context command again.
This is where
kubectx comes in.
With
kubectx you can change to a different cluster context with relative ease.
kubectx foo
Furthermore, you can move through contexts in other ways. For example, I can move back to the previous context I was in by running
kubectx -. Need to list the different contexts? Use
kubectx to list all the cluster contexts in your
kubeconfig.
2.
kubens for managing namespaces within a cluster
Packaged with
kubectx is another tool,
kubens.
kubectx is for switching into and interacting with different Kubernetes contexts/clusters. Whereas
kubens is the same idea but focused on the namespaces within a single cluster.
This is a very handy tool to use when having to use a lot of
kubectl commands and you get tired of including
-n <namespace>.
You can run
kubens <namespace> to switch into a given namespace. Once you have selected your namespace you can run all your
kubectl commands without having to specify
-n with them.
# list the namespaces in the cluster kubens # switch into a specific namespace kubens my-namespace # run your usual kubectl commands within the selected namespace kubectl get deployments kubectl get ingress
3.
k9s for command center management of a cluster
Do you prefer a more centralized tool to interact with clusters, namespaces, and resources? I do.
kubectx and
kubens are great but they are often used to make using
kubectl more streamlined.
k9s is a streamlined CLI for managing K8s clusters.
It's actually an entire terminal dedicated to managing your Kubernetes clusters. You don't need
kubectx as it allows you to choose which cluster you want to manage. You don't need
kubens as you can select the namespace you want to operate in. It simplifies the amount of tooling you need to manage your clusters.
k9s has loads of keyboard shortcuts. The main one to know is
:<type-the-resource-name> to switch to the different K8s resource you want to view. For example, if I wanted to see the pods in a cluster I would type
:pods followed by hitting your
enter key. Now I can view all the pods in a given namespace or across the entire cluster.
You can also filter the resources by typing
/yourthing followed by the
enter key again.
Anything you can do with
kubectl you can often do a lot quicker in
k9s. Tailing the logs of a pod has a keyboard shortcut. Shelling into a running container has one to. Killing resources, editing them on the fly, etc, all available in
k9s.
Conclusion
Kubernetes is a complex system. It has dozens and dozens of resources that you often want to interact with at some point. This is in addition to actually deploying your applications and services within it.
Without solid tooling, it can be difficult to manage. Things like
kubens ease our pain a bit by allowing us to isolate our
kubectl calls to a single namespace.
kubectx allows us to lock ourselves to a single K8s cluster.
k9s harnesses the power of
kubectl,
kubens, and
kubectx into one command terminal.
Are these all the tools? Not even close. These are the ones I use on a daily basis. But this is a growing space and more tools are going to come along. If you have any tools you come across, feel free to drop them in the comments below. | https://practicaldev-herokuapp-com.global.ssl.fastly.net/kylegalbraith/the-three-terminal-tools-i-use-for-managing-kubernetes-clusters-58hj | CC-MAIN-2020-50 | refinedweb | 916 | 73.88 |
#include "ltwrappr.h"
L_INT LImageViewerCell::SetCellTag(uRow, uAlign, uType, pString, uFlags);
Sets a tag on a specific location in a specific cell.
The number of rows to count before placing the tag.:
Value that represents the type of tag to be added. Possible values are:
String containing a custom tag. This parameter is only used if uType is set to DISPWIN_TYPE_USERDATA.
Flags that determine whether to apply the feature on the one cell only, or more than one cell. This value can only be used when the cell is attached to the ImageViewer through the function LImageViewer::InsertCell. Possible values are:
If two tags are written to the same location, the second tag written will overwrite the first tag.
To change the quality of the tag text, call the LImageViewer::SetProperties function.
Required DLLs and Libraries
For an example, refer to LImageViewer::Create.
Direct Show .NET | C API | Filters
Media Foundation .NET | C API | Transforms
Media Streaming .NET | C API | https://www.leadtools.com/help/sdk/v22/imageviewer/clib/limageviewercell-setcelltag.html | CC-MAIN-2022-27 | refinedweb | 160 | 59.5 |
Asp.Net Interview Questions
Asp.Net 2.0/3.5 Sample Interview Questions and Answers. Interview Tips for a successful job Interview
Datagrid
Formatting the Data
We are
able to format the content of the datagrid cell by one of two simple methods,
dependant upon whether the column is a bound column or whether it is a template
column. In our example we shall format the column to have to digits after the
decimal point , followed by a...
Datagrid
Highlight a Row With Click Through
It is
relatively easy to add alternating colours to the rows in your datagrid.
However, when we move the mouse over the rows we may want to highlight this
row, and possibly to add the option of a click through based on the row
selected...
Add
a Delete Button to a Datagrid
To add
a delete button to a datagrid follows a similar process to adding an edit
button. In the datagrid header...
Add
an Edit Button to a Datagrid
The
datagrid has a predefined editColumn for handling the editing of a datagrid.
Adding this simple column definition to a datagrid adds a powerful feature.
When a row is not in edit mode the column item shows the word...
Making
a Datagrid Row Editable
Two of
the most popular methods of editing a datagrid in asp.net are to either select
the row and take the user off to a different presentation of the data, or to
change the formatting of the row presented in the database with appropriate
edit text boxes, checkboxes and...
Adding
Tooltips to Datagrid Rows
Adding
tooltips to datagrid rows is easy, assuming that you have already created the
code for adding row highlighting. In this article I shall assume that you have
already read the article entitled Datagrid Highlight a Row With Click
Through...
Binding
a Datagrid to an Access Database
This
list covers the full lifecycle of a content management system, from initially
creating the content, through to delivering it to end users...
Adding
Data to a DropDownList
The aim
of this article is to answer the question 'How do I add items to a
DropDownList?' Initially as part of the declaration for the DropDownList we can
also define a number of items, much in the same way as in classic ASP...
Getting
Current Date Time
In
classic ASP we had now() which would return the current date and time. For
asp.net this no longer exists. So what should we use...
Test
if File Exists
Sometimes,
in order to reduce our chance of error, when working with the filesystem in
ASP.NET, we need to determine wether a file exists before performing an action
on it. The following short piece of code will enable us to test whether a file
exists...
Using
Javascript with ASP.NET Form Elements
Adding
simple pieces of Javascript to an Asp.net page can be acheived by adding to the
attributes of the particular imagebutton or linkbutton. if its normal ASP.Net
Button then you can...
Regular
Expressions
In the table below we list the characters used in .Net
regular expressions, together with their meaning, But first...
Authentication
in Asp.net
Forms
authentication in ASP.Net is far more easier and safe than Asp 3. It is
possible to place a web.config file in any directory of a web site.Therefore,
we are able to make most of a web site public, whilst providing authentication
on, say, one directory...
General
ASP.NET
.Net
Programming
cSharp
Sql
Server Home
Javascript
/ Client Side Development
IT
Jobs
Ajax
Programming
Ruby
on Rails Development
Perl
Programming
C
Programming Language
C++
Programming
Python
Programming Language
Laptop
Suggestions?
TCL
Scripting
Fortran
Programming
Scheme Programming
To get the user ID of the user who is currently logged in, you would get it
using this: System.Web.HttpContext.Current.User.Identity.Name VB.NET
C#
Use the "<br>" tag to specify line breaks. For example:
VB.NET
Use namespace System.Web.HttpUtility
VB.NET
OneClick Control
Refer
Format DateTime Values in XML extracted from Dataset
The tilde (~) in front of URLs means that these URLs point to the root of your
web application.
Web developers are familiar with using relative paths for all links, including
hyperlinks, images, and stylesheets, to be able to move around web pages
collectively.
In ASP.NET when using User controls the relative paths can be difficult to use.
The typical solution to this is to use web-root absolute paths instead here,
resulting in the hard-coded sub-directories that are common on ASP.NET sites.
The correct solution to this problem is to use app-relative paths instead, which
ASP.NET nicely makes possible through the use of the tilde (~) prefix. Instead
of <a href="/UC/Page.aspx">, use <a href="~/Page.aspx"
runat="server">. The same ~ notation works for images also, as long as you
add runat="server". There is also a ResolveUrl method that allows you to use ~
in your own code, which is one possible way to get stylesheet paths
app-relative. Refer
Tilde: Reference the Application Root
You don't need a namespace to reference it; anything in the bin folder is
implicitly in the same namespace as the page being compiled. So if your class
looks like this:
Just set the locale to Japanese in the Page directive.
i. e Set the Culture= "ja-JP" for the Page Directive.
This.
Use the Namespace System.Text.RegularExpressions VB.NET
This error occurs if you are trying to fetch the recordset value as follows
To avoid this error try VB.NET
May be the path of the file you are giving is wrong or you do not have write
permissions on the specific folder.
ComboBox Control
Also an useful article by Khoi
ComboBox WebControl
Here are some interesting articles that talk about encryption and decryption:
Add this to the body element:
Also check out Andy Smith's
DefaultButton Control which triggers submit selectively on one of many
buttons based on the context.
To get the list of aspx files under your app directory:
Use namespace System.IO
VB.NET
The following aspx code will display the resultant files list in the DataGrid in
a proper format:
An HttpHandler is a class that handles HTTP requests. In ASP.Net a Page class,
for example, is the default HttpHandler for files with a .aspx extension. You
can map different file extensions to different HttpHandlers in ASP.Net. When
the web server receives a request for a file, it looks in its configuration to
find out whether a special HttpHandler has been designated for that file
extension. ASP.Net provides the HttpHandler class to extend the functionality
of ASP.net to be able to handle requests for other file types (extensions). In
IIS, you make ASP.Net the HttpHandler for the type of file that you desire, and
use the web.config file for your web to identify what DLL (Class Library) is
used to handle specific file extensions.
The HttpHandler is a class that handles the request. It has access to the same
HttpContext (Request, Response, Cookies, Session, Application, Server, etc)
that the Page class does. For more detailed information, see: HttpHandlers
You will have to create a Bitmap instance from the image file and then query
the Width and Height as follows:
When FormsAuthentication is used in ASP.NET, by default, it gets redirected to
the default.aspx page.
To redirect it to some other page other than default.aspx you have to use the
code below.
Use System.Net.HttpWebRequest
Try using "System.Web.HttpContext.Current.Request.Cookies" instead of
"Request.Cookies" in your code.
Use the namespaces
Note:For creating the file (in above case "temp.html") give appropriate rights
(modify and write) to the ASPNET user.
To specify the Encoding specify the second parameter of the StreamReader
accordingly
VB.NET
This usually happens when encryption is enabled for ViewState in all your pages
but the different server machines use different Validation Keys for encrypting.
Ensure that all the machines has the same validation key specified in their
machine.config file. For example, add the following key:
page1.aspx
page2.aspx
Specify the pageLayout of the Document from GridLayout to FlowLayout, this will
position the controls automatically and optimally.
Use the global.asax file and listen to the PostRequestHandlerExecute event of
the Global object.
In the handler Global_PostRequestHandlerExecute write the following code
VB.NET
Simply use the same handler for the different button Click events.
Set the SmartNavigation attribute to true.
You can make use of a DataReader.
Refer
How to display data in Textboxes using DataReader?
web.config
.aspx
Go to drive:\Program Files\Microsoft SQL Server\80\Tools\binn
Use OSQL, a command line tool.
Add reference -> COM tab ->Microsoft Excel 11.0 Object Library
To store in Session:
Pros:
Process of switching of User Interface between left to right i.e English,
German ...and right to left such as Hebrew/Arabic is called Mirroring.
To mirror a form
To mirror individual control in a form set dir=rtl for individual controls.
You can use Http Compression to compress static aspx files. Refer
Microsoft Knowledge Base Article - 322603
For security reasons, you can't force a user to run any executable.
Instead give user the option to click on it and download the executable, and
execute it if he wants to. All you can do is put .exe in a directory on your
web site and put a hyperlink to it on some page.
Note : Be sure to secure this directory by deactivating all execution
permissions both in the IIS console and in the directory ACL
For more details refer
INFO: Executing Files by Hyperlink and the File Download Dialog Box
The reason why the encrypted data couldn't be decrypted on another machine is
because the validation key in the original machine's machine.config is set to
AutoGenerate. This means that the generated keys are unique to each machine. A
better solution will be to specify the validation key, so you can decrypt it
across any machine with the same validation key. For more details on solutioon
refer following article :
You'll have to create an account in SQL Server for the aspnet user.
This will return the information of the server computer, not the client browser
computer.
Add reference to System.Windows.Forms.dll.
VB.NET
You can build a dll using the following command line .
Assuming your command window has the appropriate path set to use the following
exes:
VB.NET compiler vbc.exe
C# compiler csc.exe
To reference it within the .aspx page use the Import directive:
<%@ Import Namespace="SyncVB" %>
or
<%@ Import Namespace="SyncCS" %>
The .
VB.NET (Add reference to Microsoft Visual Basic .NET Runtime)
If Request.ServerVariables("LOGON_USER") is returning an empty string, the
problem is probably that your app allows anonymous users. To change this:
You can examine the Request.UserAgent to check if the browser was IE, define a
custom HtmlGenericControl type representing your stylesheet link and set the
href property on it depending on if the browser was IE.
Where LINK is a HtmlGenericControl. You could then do something like this:
In the web.config file add a key-value pair as follows:
Then you can access the settings as follows in code:
This could be because of security concerns. Please check this KB for
resolutions:
KB
316675
To access an MS Access database from your ASP.Net page, you must use the UNC
format in the path, like:
\\Servername\yourpath\your.mdb
To fully use the database, grant permissions to the ASPNet user account equal to
'modify', for the folder/directory where the database exists. | http://www.megasolutions.net/FAQ/aspnet/ASP_Net_Miscellaneous.aspx | CC-MAIN-2014-35 | refinedweb | 1,948 | 56.76 |
Since IMM uses Semantic Web technologies like RDF. OWL, and SPARQL, it is a requirement to first set up a useful and meaningful metadata model that can be expressed using the Web Ontology Language (OWL) as the first step in deploying an IMM solution.
The ontology is what defines and describes the data and relationships between everything that will be stored in the IMM Metadata Store. Once you have your ontology defined you can use the IMM Visual Studio tools to generate .NET classes that can be used to populate data in the IMM Metadata Store and also build custom forms to collect metadata in a workflow.
In order to create a new ontology for IMM, you must first have the IMM Core ontology and it's required imports available on your local machine. To do this, you can find all the core ontologies in the SDK folder of the IMM installation. This is by default found at %Program Files (x86)%\Microsoft Interactive Media Manager 2008\SDK\Ontologies.
You should copy the following core OWL files into a new working directory.
The reason you need the Dublin Core owl files, is that they are imported and used by the IMM Core Owl file.
Create a new directory in your working path. For this discussion lets say I created a new folder on my C drive called c:\Owl\Contoso. Now I will copy the core Owl files into this new directory. You should now have a folder that looks like this.
Next create a new OWL file. In this case I will create a new blank file called Contoso.owl. I recommend that you use Altova Semanticworks to do this, since that is what I will be using for the rest of this article to explain how to edit an OWL ontology.
In SemanticWorks, select File->New, then save the file as Contoso.owl into your working directory - in my case c:\Owl\Contoso.
Next we will begin to define our new ontology. In order to do this, we first need to set up a few things within SemanticWorks to make our lives easier.
Namespace imports are not automatic in SemanticWorks so we need to set then in Tools->Namespace Imports for RDF... menu. Once in the menu, click Add to create a new row. In this row you need to add the following to the Namespace column
In the Import File column, this should be the absolute path to your IMM Core.owl file. It should look similar to mine.
Now we need to make sure that all of the IMM Uri prefixes are set up in SemanticWorks so that it will collapse the Uris down to easy to read prefixes. To do this, go to the Tools->URIref Prefixes... menu. In this dialog box you should see 3 prefixes already set up - owl, rdf and rdfs. We will now add the IMM required prefixes. An easy way to do this is to open up the IMM Core.owl file and view the URIref Prefixes that are already configured there. Here are all the settings required:
Next you will need to define your own namespace for your custom ontology. This can be a URI that actually links to your OWL file on the Internet or just a reference urn if you like. For my example ontology I have defined this namespace.
The namespace for your ontology must end in either a "#" or a "/" to be valid. You should also add a prefix to the URIref Prefixes for your own namespace to make it easier to edit the ontology. In this case I added a cont prefix for my namespace to the above list.
Now we will define the Ontology name, version, and import the IMM Core ontology. To do this, switch back to your custom ontology file in SemanticWorks and go to the "Ontologies" tab in the UI.
From here create a new owl:Ontology from the button in the Ontologies tab and name it exactly the same as your namespace. In my case.
Select the button next to the namespace and right click on the new Ontology you defined. You will get a context menu with many options. From this menu select Add owl:imports. Right click on the new owl:imports and select Add resource object. In the new resource object, you will enter the URI for the IMM Core ontology.
Enter
It should now look like the following
Next right click on your Ontology name again and select Add owl:versionInfo then right click on the versionInfo node and select Add literal. Enter your desired version number here. In my case, I just used a simple "1.0" string.
Your completed Ontology definition and imports should look like this.
If you select from the menu RDF/OWL->Reload all imports you should see both your ontology and the IMM Core ontology listed in the Ontologies tab now. This means that you have successfully imported the core ontology. If you look at the source code in the Text tab at the bottom of the page, you should see this very simple OWL definition. Save your ontology so far.
<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF xmlns:
<rdf:Description rdf:
<rdf:type>
<rdf:Description rdf:
</rdf:type>
<rdfs:comment>This is my comment about my sample ontology</rdfs:comment>
<rdfs:label>Contoso Ontology</rdfs:label>
<owl:imports>
<rdf:Description rdf:
</owl:imports>
<owl:versionInfo>1.0</owl:versionInfo>
</rdf:Description>
</rdf:RDF>
Now that we have a new Ontology definition, version number, and the IMM Core imported, we are ready to begin to define our new Properties and Classes and extend the IMM Core classes where necessary.
Go back to the RDF/OWL view by selecting the RDF/OWL button at the bottom of the page, exit out of your Ontology by clicking the Up button and then select the Properties tab. Here you should see a list of all the imported Dublin Core, IMM, and MPEG21 namespaces that are a part of the IMM Core ontology.
There are two types of properties that can be defined in OWL. One is a DatatypeProperty, and the other is an ObjectProperty. It's easy to think about how these work -Datatype properties are used to store actual literal values such as strings, integers, booleans, decimal, etc.... ObjectProperties are used to point to other objects by URI.
To define a basic Datatype Property, select the owl:DatatypeProperty from the insert button in the Properties page. You should see a new owl:DatatypeProperty with a urn:unnamed-1 title on it.
Edit the title to be the name of the property that you desire. In this case I will create a new property of type string called Artist. To do so, I use my previously defined prefix, a colon, and then the name Artist like this.
cont:Artist
It is very important that you already added the URIref prefix to SemanticWorks as noted above, otherwise you will get an error later. Switch to Text view and make certain that the full URI has been expanded in the rdf:about property for this new item. If it has not been expanded, than you probably entered the property before properly setting up your URIRef prefixes. If it says just cont:Artist, then you will get serious errors later.
<rdf:Description rdf: <rdf:type> <rdf:Description rdf: </rdf:type> </rdf:Description>
Next we will define the datatype of this property. Click into the property and you will be able to right click and Add Range. The Range in OWL is what defines what is valid to be stored in this datatype property.
Right click the range node and select Add XML schema datatype, then select the schema type that you desire. In my case, I selected. Your property will now look like the following.
There are two ways in which to add a defined Property to a Class in Owl. One is Global, the other is local to the Class definition. I prefer to use the later, due to the fact that when you define it on a Global level you lose some control later.
I'll start with the recommended route to add a Property to an existing IMM Core Class.
Let's use the example of adding our new Artist property to the IMM Core AudioItem definition. Switch to the Classes tab in SemanticWorks and scroll down to the bottom past the Dublin Core imports to open up the the imm:AudioItem class definition.
Expand out the little plus sign (see red arrow below) at the top of the imm:AudioItem class. This will show you the imm:MediaItem node, which represents the fact that AudioItem derives from MediaItem.
Right click on the arrow that I circled above in blue above and select Add Restriction. In the drop down list select the property that you just created. This "restricts" the definition of AudioItem to now require a cont:Artist in my case. At this point, we have not restricted the cardinality of the property, so it is in fact a collection of cont:Artist - meaning, I can have as many cont:Artist properties attached to an AudioItem as I want. If this is the desired outcome, you are done and the owl.exe tool will automatically generate a Collection of strings for the cont:Artist property. If you want a single valued property you need to set the Max Cardinality. To do this in SemanticWorks, there is a tiny (barely visible) ".." under the property restriction. Set the right side of this to "1" as below. Your final property restriction should look like this. You have now defined a single property on the AudioItem. Repeat the process of defining properties and adding them to the classes to build out your objects and vocabulary.
In my next post I will go over how to define new classes in OWL.
PingBack from
Trademarks |
Privacy Statement | http://blogs.msdn.com/imm/archive/2007/11/21/creating-and-extending-owl-ontologies-in-imm.aspx | crawl-002 | refinedweb | 1,661 | 72.26 |
This program implements
a simple chat server (Example 16-10) that works with the chat applet from Section 15.11. It accepts connections from an arbitrary
number of clients; any message sent from one client is broadcast to
all clients. In addition to
ServerSockets, it
demonstrates the use of threads (see Chapter 24).
And since there are interactions among clients, this server needs to
keep track of all the clients it has at any one time. I use an
ArrayList (see Section 7.4) to
serve as an expandable list, and am careful to use the
synchronized keyword around all accesses to this
list to prevent one thread from accessing it while another is
modifying it (this is discussed in Chapter 24).
Example 16-10. ChatServer.java
/** Simple Chat Server to go with our Trivial Chat Client. * * Does not implement any form of "anonymous nicknames" - probably * a good thing, given how a few people have abused anonymous * chat rooms in the past. */ public class ChatServer { /** What I call myself in system messages */ protected final static String CHATMASTER_ID = "ChatMaster"; /** What goes between any handle and the message */ protected final static String SEP = ": "; /** The Server Socket */ protected ServerSocket servSock; /** The list of my current clients */ protected ArrayList clients; /** Debugging state */ private boolean DEBUG = false; /** Main just constructs a ChatServer, which should never return */ public static void main(String[] argv) { System.out.println("DarwinSys ...
No credit card required | https://www.safaribooksonline.com/library/view/java-cookbook/0596001703/ch16s07.html | CC-MAIN-2018-17 | refinedweb | 235 | 57 |
IRC log of cssns on 2011-06-17
Timestamps are in UTC.
15:53:23 [RRSAgent]
RRSAgent has joined #cssns
15:53:23 [RRSAgent]
logging to
15:53:51 [plinss]
zakim, this will be conf1
15:53:51 [Zakim]
ok, plinss; I see Team_(cssns)16:00Z scheduled to start in 7 minutes
15:55:36 [plh]
plh has joined #cssns
15:56:26 [ChrisL]
ChrisL has joined #cssns
15:57:38 [ChrisL]
rrsagent, here
15:57:38 [RRSAgent]
See
15:57:50 [plinss]
zakim, code?
15:57:50 [Zakim]
the conference code is 26631 (tel:+1.617.761.6200 tel:+33.4.26.46.79.03 tel:+44.203.318.0479), plinss
15:57:54 [ChrisL]
rrsagent, make logs public
15:58:18 [Zakim]
Team_(cssns)16:00Z has now started
15:58:25 [Zakim]
+plinss
15:58:41 [Zakim]
+Plh
15:58:49 [r12a]
r12a has joined #cssns
15:59:11 [Zakim]
+ChrisL
15:59:19 [ChrisL]
scribenick: ChrisL
15:59:58 [r12a]
zakim, dial richard please
15:59:58 [Zakim]
ok, r12a; the call is being made
15:59:59 [Zakim]
+Richard
16:01:07 [ChrisL]
chair: plh
16:01:41 [ChrisL]
Meeting: Normalisation and W3C with particular reference to CSS
16:02:36 [ChrisL]
plh: Primary goal is to move css selwsctors forward
16:02:39 [ChrisL]
16:02:47 [ChrisL]
16:02:59 [ChrisL]
16:03:42 [ChrisL]
peter, is dbaron's preserence for normalise-at-parse expressed somewhere other than his 2009 summary linked above?
16:05:32 [ChrisL]
was wikified (link above)
16:05:54 [ChrisL]
16:06:55 [plh]
16:07:34 [plh]
16:10:14 [plh]
16:14:31 [Zakim]
+ +1.408.790.aaaa
16:15:07 [ChrisL]
zakim, aaaa is addisson
16:15:07 [Zakim]
+addisson; got it
16:15:31 [ChrisL]
plh: css ns blocked on normalisation issue, which also blocks css selectors
16:15:48 [plh]
16:16:18 [aphillip]
aphillip has joined #cssns
16:16:21 [ChrisL]
16:16:54 [ChrisL]
plh: norm is not done on the identifier. implementors not willing to do so
16:17:08 [ChrisL]
plinss: yes
16:17:44 [ChrisL]
adisson: we dont require full normalisation of docs or stylesheets but we want normalised compare especially for identifiers and namespaces
16:18:09 [ChrisL]
... same ns or not should nor depend on source encoding or order of combining marks
16:18:27 [ChrisL]
plinss: so you said you dont want to normalise selectors?
16:18:45 [ChrisL]
ad: not require stylesheets to be in a particular form
16:18:56 [ChrisL]
... comparisons should be normalised
16:19:05 [ChrisL]
... but not random text selection
16:20:33 [ChrisL]
ChrisL: 'early' norm can men by content autors or at parse time; which do you mean
16:20:53 [ChrisL]
ad: content is not normalised all the time. so user agents are responsible.
16:21:29 [ChrisL]
... should they normalise at parse or compare
16:21:56 [ChrisL]
r12a:may be a reason to have denormalised text in content. but different for class selectors, id s etc which are compared
16:22:07 [ChrisL]
... may make sense to normalise just those
16:22:18 [ChrisL]
ad: interactions with dom and exmascript
16:22:50 [ChrisL]
... wg position is to focus on comparison being normalised. dont care how its done. normalising identifiers at parse time is one way
16:23:11 [ChrisL]
plinss: so you see that as just an implementation detail?
16:23:21 [ChrisL]
ad: there can be side effects from that choice
16:23:49 [ChrisL]
... harder to normalise individual tokens, but possible. then question is which tokens
16:24:03 [ChrisL]
plinss: and what does the dom see and what does script assume
16:24:26 [ChrisL]
ad: so yu can't make certain queries anymore
16:24:39 [ChrisL]
plinss: not sure how this is particular to nnamespaces
16:25:09 [ChrisL]
ad: ns is a token plus an IRI. want them to compare in a normlised fashion
16:25:25 [ChrisL]
... so can tell what ns is in use regardless of document encoding
16:25:37 [ChrisL]
r12a: mac vs pc normalisation ...
16:25:45 [ChrisL]
ad: mainly filenames there
16:26:20 [ChrisL]
... also vietnamese keyboard different on mac and pc wrt normalisation so you get two different strings that look the same
16:26:50 [ChrisL]
plinss: no namespaces in css are like xml - you take a uri and give it a prefix to use. you want to notmalise the prefix or the uri?
16:27:28 [ChrisL]
ad: uri has no non-ascii. iri has the rues in it (or will have) for how that works. so main concern is the prefix that has to be unique
16:28:02 [ChrisL]
plinss: prefix in css is an ident. so we would have to normalise all idents. but we have author deined idents - why pick on ns in particular
16:28:25 [ChrisL]
ad: coparisons should be normalising for identifiers
16:29:04 [ChrisL]
plh: so we just published css as a rec, and it defines an ident. so why does this apply to css ns and not css 2.1
16:29:12 [ChrisL]
ad: it does apply to css 2.1
16:29:54 [ChrisL]
ad: the horse has escaped. so i18n wg is in catch up. not been succesful so far.
16:30:22 [ChrisL]
... last vestige of attempt to normalise is to getidentifiers normalised. if we cant do that then we are done
16:30:46 [ChrisL]
... valid for us t question whether we are doing the right thing to put the onus on content authors to sort it out
16:31:03 [ChrisL]
plh; for styling, if the class or id does not match you will see right away
16:31:31 [ChrisL]
ad: stylesheet may be dynamically generated and separae from the doc. author can't see why it doesnt work
16:32:03 [ChrisL]
plinss: yes, but that does not apply here as ns prefixes are local to the scope of a single stylesheet. only the uri is matched internallt
16:32:33 [ChrisL]
... so there is a consistent normalisation. unrelated to any prefixes used in the document
16:32:48 [ChrisL]
... any unicode in an author defined ident is in the one document
16:32:59 [ChrisL]
ad: or if you use escapes
16:33:13 [ChrisL]
plinss: esapes should not be normalised anyway
16:33:20 [ChrisL]
ad: ok, thats not so ....
16:33:42 [ChrisL]
plinss: css ident is asci wit unicode escapes, we dont apllow random unicode in there
16:33:54 [ChrisL]
ad: think you allow a reasonable range
16:34:02 [ChrisL]
plinss: a small range
16:34:31 [ChrisL]
... i see classes as an issue certainly, but also attribute selectors. but none of that applies to namedspaces
16:34:34 [plh]
ident [-]?{nmstart}{nmchar}*
16:34:34 [plh]
name {nmchar}+
16:34:34 [plh]
nmstart [_a-z]|{nonascii}|{escape}
16:34:34 [plh]
nonascii[^\0-\237]
16:34:41 [ChrisL]
... and frankly that applies right back to css1
16:35:34 [ChrisL]
plinss: if we want norm we should require it all the places tat it matters. every place the author can type an ident. or nothing
16:35:47 [ChrisL]
... happy to support that but this is ot the place to make the stand
16:36:24 [ChrisL]
ad: our comments actually went to selectors first. its kind of a test case as someone has to do something to decisde which directionw e go
16:36:49 [ChrisL]
... are we going to normalise some important thins or not. if not then the guidelines need to be changed so people know what to avoid
16:37:01 [ChrisL]
.. didnt go to ns til the end. started with selectors
16:37:21 [ChrisL]
... this is a relaxation f out position 5 yerars ago which was noralise everything
16:37:30 [ChrisL]
.. realise this is problematic
16:37:42 [ChrisL]
r12a: and we need to get html to norm at the same time
16:37:57 [ChrisL]
plinss: lots of things do selection
16:38:49 [ChrisL]
ad: out position is that we recomend css wg , and we wont object to publishing css ns without it
16:38:57 [ChrisL]
r12a: yes
16:39:08 [ChrisL]
... but wanted to be sure we asked the question
16:39:37 [ChrisL]
ad: concerned about selectos. concern is we have a web tha is not normalised and not normalising
16:39:44 [ChrisL]
plh: bring it to the tag?
16:39:53 [ChrisL]
ad: yes (again)
16:40:18 [ChrisL]
ad: dont want to make recommendatins that are destructive and pointless
16:40:34 [ChrisL]
... started work towards fixing charmod to say the right thing
16:40:47 [ChrisL]
... only question mark is whether comparisons are normalised
16:40:58 [ChrisL]
plinss: csswg see this way outside scope of css
16:41:22 [ChrisL]
... normalising idents needs to have a norm story for comparing outside the stylesheet, so affects html
16:41:36 [ChrisL]
ad: and you shouldnt assume the docs are normalised
16:41:51 [ChrisL]
plinss: has implications on html
16:42:10 [ChrisL]
... if css normalises a class name but javascript doesnt then there is an issue
16:42:20 [ChrisL]
... needs to go tot tag and be consisten on all specs
16:42:43 [ChrisL]
... tag finding would be very useful. dont want to see a mismatch on identifier handling
16:43:00 [ChrisL]
plh: also orm on fragment identifiers
16:43:07 [ChrisL]
ad: potentially
16:43:18 [ChrisL]
... iri may require that but not currently
16:43:44 [ChrisL]
ad: speaking not as the chair,the horse is out so i suspect we wont do any of this
16:43:51 [ChrisL]
... too many leaks to fix
16:44:03 [ChrisL]
... want to avoid inconsistency
16:44:17 [ChrisL]
... wg thinks we should at least make an effort
16:44:24 [ChrisL]
... tag finding is best way
16:44:40 [ChrisL]
plh: css1 css 2.1 - its too late to change tat
16:44:48 [ChrisL]
cnt change selectors in css2
16:45:05 [ChrisL]
r12a: can start wt next version
16:45:08 [ChrisL]
plh: no
16:45:41 [ChrisL]
plh: css3 selectors have to be backward comat with css 2.1 as there is no versioning in css
16:46:06 [ChrisL]
r12a: in practical terms it would be backwards compar as only a handful of people would rely on this
16:46:29 [ChrisL]
ad: this isnt a hugely breaking change its a subtle change for almost everyone
16:46:39 [ChrisL]
plh: makes it even harder to sell
16:47:09 [ChrisL]
ChrisL: everyone will notice if all comparisons are slower
16:47:21 [ChrisL]
ad: only if its a major slowdown
16:47:41 [ChrisL]
plinss: this is why implementors prefer nortm at parse time. but that is a sepatrate detail
16:47:50 [ChrisL]
... main focus is what to do with namespaces
16:48:07 [ChrisL]
... takin it to tag is the right way to go. needs a champion on the tag
16:48:42 [ChrisL]
... once we have a stor thatgoes across html and dom and css then we can change thngs
16:49:00 [ChrisL]
plh: so .... what do we do
16:49:15 [ChrisL]
... brig it to tag with peter
16:49:32 [ChrisL]
... and css wg decides then moves to pr with css ns
16:49:41 [ChrisL]
... these could be done together
16:49:56 [ChrisL]
... its blocked since 2009 and is not productive
16:50:05 [ChrisL]
ad: formal objection is not productive
16:50:56 [ChrisL]
plh: want the issue t be looked into if css wg moves forward
16:51:44 [ChrisL]
ad: specially concerned abot nt impacting html5 more than needed
16:52:18 [Zakim]
-ChrisL
16:52:32 [ChrisL]
action: r12a to bring normalisation of idents to tag
16:52:59 [Zakim]
+ChrisL
16:53:24 [ChrisL]
plh; hw ln for a ransitin rewuest
16:53:30 [ChrisL]
plin: less than a week
16:53:33 [aphillip]
addison: i18n will not formally object to NS, but we very well could do so for Selectors
16:53:53 [ChrisL]
s/ad/aphillip/g
16:54:22 [ChrisL]
plinss: tag currently focussed on microdata vs rdfa. so at least a few weeks
16:54:44 [ChrisL]
r12a: i18n will require a lot longer than that
16:55:01 [ChrisL]
... and aftyer a tag ruig would require a lot more time than that
16:55:14 [ChrisL]
... so is it worth holding up css ns and selectors?
16:55:32 [ChrisL]
aphillip; if selectors is published without norm then its the end of the road
16:56:04 [ChrisL]
r12a: we have done ok without it so far. there wil be new versionsin the future
16:56:17 [ChrisL]
plinss: selectors level 4 is already being worked on
16:56:32 [ChrisL]
aphillip: more time that passes the harder it is to effect change here
16:56:43 [ChrisL]
... its selectos, ecmascript, dom etc
16:56:54 [ChrisL]
plh: this is already implemented in older browsers
16:57:53 [ChrisL]
plinss: selectos 3 added mainly pseudoclases it does not change the comparisons much
16:58:31 [ChrisL]
ad: we last published charmod-norm 6 years ago. the we got browbeaten into not requirin early normalisation
16:59:00 [ChrisL]
... its untenable then and we have worked on it for 1 years. so 16 years on we are no closer to accomplishig it
16:59:37 [ChrisL]
plinss: because css is modular, norm affect much more than jus selectors
16:59:54 [ChrisL]
... so we would want a normalisation update to 2.1 that covers all idents
17:00:14 [ChrisL]
ad: dont want the i18n wg focused on this corner case for all eternity
17:00:33 [ChrisL]
... not being helpful by hitting norm every couple of years
17:01:00 [ChrisL]
ad: we can ask for the tags attention and it may be thre weeks or so before we get even a reply
17:01:14 [ChrisL]
... will take us that long to get a discussion document
17:01:27 [ChrisL]
plh: counting on peter to advocate for this being on thw agenda
17:01:33 [ChrisL]
plinss: happy to do so
17:01:58 [ChrisL]
plh: ok so for ns, my sentiment is that we are better off letting css ns and selectors progress
17:02:13 [ChrisL]
... because a lot of chang eis needed and its not limited to just those two
17:02:34 [ChrisL]
.. so css wg shoudlrequest PR on both noting te issue is not closed byut asking to move forward
17:03:10 [ChrisL]
action: plinss request PR transition for css namespaces and css selectors, once tag is alerted
17:03:40 [ChrisL]
rrsagent, make minutes
17:03:40 [RRSAgent]
I have made the request to generate
ChrisL
17:04:14 [ChrisL]
plh: come back to this in a few weeks with the request i hand
17:04:17 [ChrisL]
adjourned
17:04:22 [ChrisL]
rrsagent, make minutes
17:04:22 [RRSAgent]
I have made the request to generate
ChrisL
17:04:41 [Zakim]
-ChrisL
17:04:43 [Zakim]
-Plh
17:04:46 [Zakim]
-addisson
17:04:48 [Zakim]
-Richard
17:04:49 [Zakim]
-plinss
17:04:49 [Zakim]
Team_(cssns)16:00Z has ended
17:04:50 [Zakim]
Attendees were plinss, Plh, ChrisL, Richard, +1.408.790.aaaa, addisson
17:05:07 [ChrisL]
rrsagent, make minutes
17:05:07 [RRSAgent]
I have made the request to generate
ChrisL
19:26:52 [Zakim]
Zakim has left #cssns
21:36:53 [r12a]
r12a has left #cssns | http://www.w3.org/2011/06/17-cssns-irc | CC-MAIN-2016-18 | refinedweb | 2,633 | 75.03 |
- Advertisement
pirate_dauMember
Content count160
Joined
Last visited
Community Reputation151 Neutral
About pirate_dau
- RankMember
Conditional Assignment Operator?
pirate_dau replied to ProgrammingHobbit's topic in General and Gameplay Programmingfoo = (foo < bar ? bar : foo);
[java] Problem with AWT listeners
pirate_dau replied to King of Men's topic in General and Gameplay Programmingextending MouseAdapter instead of implementing MouseListener will hide those empty methods from you. MouseAdapter is basically a blank implementation of MouseListener.
[java] Problem with AWT listeners
pirate_dau replied to King of Men's topic in General and Gameplay ProgrammingI have thought for a while on how to respond to this... I think basically you have a design problem (it does seem strange that neither is executed, but I don't think it's worth going into why that is). Does it make sense for your base class to have any implementation of MouseListener, though? Add your mouse listener where it makes sense -- in the specific class that extends MyButton. If you have several buttons that share WindowListener implementations, then make that its own class ala public class MyButtonMouseListener extends MouseAdapter { // Your shared implementation methods here } This doesn't really answer your question, but I'm pretty sure it would solve your problem.
[java] Execution flow...
pirate_dau replied to kino's topic in General and Gameplay ProgrammingEven if Y "is a thread", if you call someMethod() from the thread which X is running in, it's going to wait for Y to return before executing the next statement. Maybe this will explain things a bit... public class X { public static void main(String[] args) { Thread thread = new Thread(new Y()); thread.start(); System.out.println("foo"); new Y().someMethod(); System.out.println("bar"); } } public class Y implements Runnable { public void run() { someMethod(); } public void someMethod() { while(true) { // do something } } } "foo" should be printed, but "bar" will not. EDIT: Fixed source tags EDIT: Woops, meant thread.start() and not thread.run()
[java] Application never closes, I have to shut down VM to make it stop
pirate_dau replied to gcsaba2's topic in General and Gameplay ProgrammingI see that you have a WindowListener in there -- looks like you have a capitalization problem, though. Try windowClosing instead of WindowClosing. I think that should fix it. Also, using Swing you can simply setDefaultCloseOperation(EXIT_ON_CLOSE), but that isn't really applicable here, I guess. (Swing's API is a lot better than AWT IMO... even though both have some abstractions I would consider dumb).
[java] Blurry screen from commandline
pirate_dau replied to chris_j_pook's topic in General and Gameplay ProgrammingCrashTV didn't really work at all on my computer. It wasn't playable anyway -- the screen filled up with green things in about half a second. I didn't really do much more than load it up to see if the problem was reproducable, though. I tried running it on a 2.8 GHz P4 with 1 GB RAM. It shouldn't be a problem having multiple JREs/JDKs installed -- but it can make things more difficult to debug for the reason that you might not be running off the JVM you think you are.
[java] Blurry screen from commandline
pirate_dau replied to chris_j_pook's topic in General and Gameplay ProgrammingI tried CrashTV, and didn't get the blurry effect. You can check the version of java you're using by a quick "java -version" ("1.5.0" is the one I tested against since I don't have 1.4.X on this computer anymore). The java version you use from the command line *may* be different from the one your JCreator is using (so that's a definite possibility as the culprit). 1.4.01 is old also... in fact, I think you might be missing a .2 in there (1.4.2.01), but even so there's a more recent 1.4.2 if that is the case. Yes, it is definitely possible to uninstall java and install a fresh copy, and that's exactly what I'd recommend you try. If that still isn't fixing it, I would try a fresh video driver install also. Try that out, and let me know if you are still having issues.
[java] Blurry screen from commandline
pirate_dau replied to chris_j_pook's topic in General and Gameplay ProgrammingFirst off, let me say "WTF?". Very strange behavior. Putting that aside, though, I don't know that you've given enough information... maybe you could slap a sample case on a server somewhere for the rest of us to see? Try to find the smallest possible code snippet that exhibits this behavior. Also, what version of Java? What OS? I think a lot of times when very general problem is posted, that indicates a lack of digging for oneself -- if you look into this, you might find an obvious culprit. Still, the behavior is so strange that if you DO find it, I'd really like to hear what it was. If you can't find it, at least give us some details to work with and we'll go from there.
[java] how do you test for efficiency in java?
pirate_dau replied to davenirline's topic in General and Gameplay ProgrammingQuote:Original post by Darragh When I'm testing my code I noticed that after a few minutes or so that it suddenly speeds up for no apparent reason- usually running around 15-20% faster. I always attributed this to the garbage collector winding down a bit after cleaning up all the junk I create when my code starts. Guess i'm wrong there.. This could be due to your code being compiled into native form by the hotspot compiler.
- Advertisement | https://www.gamedev.net/profile/27261-pirate_dau/ | CC-MAIN-2018-09 | refinedweb | 944 | 64 |
java.lang.Object
org.netlib.lapack.Dlantrorg.netlib.lapack.Dlantr
public class Dlantr
Following is the description from the original Fortran source. For each array argument, the Java version will include an integer offset parameter, so the arguments may not match the description exactly. Contact seymour@cs.utk.edu with any questions.
* .. * * Purpose * ======= * * DLANTR returns the value of the one norm, or the Frobenius norm, or * the infinity norm, or the element of largest absolute value of a * trapezoidal or triangular matrix A. * * Description * =========== * * DLANTR returns the value * * D diagonal. * = 'N': Non-unit diagonal * = 'U': Unit diagonal * * M (input) INTEGER * The number of rows of the matrix A. M >= 0, and if * UPLO = 'U', M <= N. When M = 0, DLANTR is set to zero. * * N (input) INTEGER * The number of columns of the matrix A. N >= 0, and if * UPLO = 'L', N <= M. When N = 0, DLANTR is set to zero. * * A (input) DOUBLE PRECISION. * * ===================================================================== * * .. Parameters ..
public Dlantr()
public static double dlantr(java.lang.String norm, java.lang.String uplo, java.lang.String diag, int m, int n, double[] a, int _a_offset, int lda, double[] work, int _work_offset) | http://icl.cs.utk.edu/projectsfiles/f2j/javadoc/org/netlib/lapack/Dlantr.html | CC-MAIN-2017-51 | refinedweb | 188 | 60.72 |
We saw that on creating an Android Application Project, a skeleton “Hello World” application is created. The “Hello World” module is always the first step to learning anything. I’m sure you did a Hello World program when you were learning your first programming language. Quite boring isn’t it? Well, let’s get a bit creative.
We will add a few elements to our application and see how they work.
Create a new application project or edit the Hello World Application. Open up the MainActivity.java file and activity_main.xml and get ready for some coding.
If you have a problem while adding code snippets to you code, please have a look at the complete code at the bottom.
In the activity_main.xml follow the below steps:
- Drag and drop an EditText from the Palette on the left.
- Drag and drop a Button from the Palette on the left.
- Click on the EditText and it’s properties should appear on the Properties tab to the right. If it doesn’t, Right Click->Show In->Properties.
- Edit the Id attribute of the EditText to “@+id/et” and click Yes/OK on any dialog that appears. Remember the name.
- Click on the Button and it’s properties should appear on the Properties tab to the right. If it doesn’t, Right Click->Show In->Properties.
- Edit the Id attribute of the Button to “@+id/but” and click Yes/OK on any dialog that appears. Remember the name.
- For now, leave the EditText and the Button in their respective places. We will concentrate on how to make them work and not how to place them in the layout.
Save the activity_main.xml.
Now follow the below steps carefully:
- Navigate to <yourpackagename> -> src. Right Click on <com.yourname.yourappname> and select New -> Class.
- You are creating a new Class. In the Name field enter Second.
- In the Superclass browse and type Activity. Select the android.app.activity. This makes your class an Activity.
- Hit Finish and you the class opens up.
- Navigate to <yourpackagename> -> res -> layout. Right Click on <com.yourname.yourappname> and select New -> Android XML File.
- Name it second and choose relative layout from the Root Element list.
- Hit Finish and the XML file opens up.
In the Second.java file add the following code inside the class.
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.second); }
If you have read my previous posts you will know exactly what we are doing here.
Now open second.xml and follow the below steps:
- Drag and drop a TextView and change the Id attribute to “@+id/tv”.
- Enter in the Text attribute – “This is the second Activity.”
Save second.xml. Switch over to MainActivity.java and add the following code in the onCreate() function.
Button but = (Button) findViewById(R.id.but); EditText et = (EditText) findViewById(R.id.et); but.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent intent = new Intent(MainActivity.this,Second.class); startActivity(intent); } } );
As you type in the first statement, you’ll notice that Eclipse places a small cross so as to indicate there is an error in that line. What is the error? We have not imported the Android Button widget in our activity and so Eclipse doesn’t know what we mean when we type in “Button”. Hit Ctrl+1 on your keyboard. This is a shortcut to bring up suggested fixes to the errors. Select Import ‘Button’ (android.widget). You will now see that the statement just after the ‘=’ symbol is now erroneous. Hit Ctrl+1 again and select Add cast to ‘Button’. This way we have used type casting and import statements with which you must already be familiar from your Java knowledge. Do the same for the EditText statement.
- OnClickListener() : This adds a listener to the button that triggers when it is clicked
- OnClick() : Holds the set of instructions that need to be executed when the button is clicked
- Intent : This is a very important feature of Android. For the time being, it’ll be sufficient for you to know that an Intent is used to call other Activities. We can also pass data using this across activities. We’ll see this in a while. The syntax of the constructor is new Intent(<currentactivityobject>, <destinationactivityclass>). The object of current activity is MainActivity.this and the class of the destination activity is Second.class.
- startActivity() : It is used to start off a new activity while pushing the current one to the Back Stack. It takes an intent as an argument.
What we’ve done is we’ve added a button and configured it to fire the Second Activity when clicked. Run this application using the emulator. When the MainActivity is up and you click the button to go to the second Activity, your application will crash unexpectedly. Why? Because we have not added the Second activity to the AndroidManifest.xml file.
How do you get to know what went wrong? Well, here’s how. On the top right you can see Java and DDMS. DDMS (Dalvik Debug Monitor Server) tells you exactly what went wrong. Click on it and scroll to the top of the group of lines in red. You will see ActivityNotFoundException. It also says – “Have you declared this activity in your AndroidManifest.xml?”. So that’s how we know that we haven’t declared the Second activity in the Android Manifest file.
The Android Manifest file needs to recognize each and every activity in your application.
- Open up AndroidManifest.xml file from the project contents list and from the tabs at the bottom select AndroidManifest.xml
- Just before </application> add this – <activity android:name=”.Second” />
- Save.
Launch the application again and this time it should work just fine. 🙂
You must be wondering why we did not make use of the EditText that we added to the layout. I told you before that we can send data across activities using Intents. That is preciseld what this EditText is for. Here we go.
- Add this line in the MainActivity.java before the startActivity() function :-
intent.putExtra("data", et.getText().toString());
- Add the following lines in Second.java after the setContentView() function :
TextView tv = (TextView) findViewById(R.id.tv); tv.setText(getIntent().getStringExtra("data"));
As you can see we can set the text to be displayed in the TextView from java too and this takes precedence over the xml.
What we have done here is that we will be displaying whatever text the user enters in the MainActivity in the Second Activity. Launch the application and see it work.
COMPLETE SOURCE CODE :
MainActivity.java
package com.nero.myfirstapp; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class Main extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button but = (Button) findViewById(R.id.but); final EditText et = (EditText) findViewById(R.id.et); but.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Main.this,Second.class); intent.putExtra("data", et.getText().toString()); startActivity(intent); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
Second.java
package com.nero.myfirstapp; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class Second extends Activity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.second); TextView tv = (TextView) findViewById(R.id.tv); tv.setText(getIntent().getStringExtra("data")); } }
activity_main.xml
<RelativeLayout xmlns: <EditText android: <requestFocus /> </EditText> <Button android: </RelativeLayout>
second.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns: <TextView android: </RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns: <uses-sdk android: <application android: <activity android: <intent-filter> <action android: <category android: </intent-filter> </activity> <activity android: </application> </manifest> | http://www.codemarvels.com/2013/07/multiple-screen-support-for-android-using-intents/ | CC-MAIN-2020-34 | refinedweb | 1,346 | 53.68 |
My prof is touching on information hiding, and good programming techniques. He said it's a good idea to keep as much of the user interface (i.e., couts) in main, and then modify object variables through the use of functions.
Here's what I want to do:
I'm starting on a program that lets the user input the type of pizza (hand tossed, pan, deep dish), the size (s, m, l) and the toppings they want.
So far, here's what I've setup in my class:
#pragma once #include <iostream> using namespace std ; const double SMALL = 10.00 const double MEDIUM = 14.00 const double LARGE = 17.00 const double TOPPING = 2.00 class Pizza { public: void set ( ) ; void outputDesc ( ) ; double computePrice ( ) ; private: char type ; char size ; int toppings[7] ; } ;
For the toppings, I figured the easiest way is to do a loop of some sort until they're finished inputting toppings (maximum of 7). The reason I'm using an array is because I have to include a function that outputs the object data, including each topping.
My question is this: How can I allow the user to input the toppings they want in main(), and then put that data into the array in my object without creating a temp array for user input? | https://www.daniweb.com/programming/software-development/threads/88541/passing-arrays-updating-object-arrays | CC-MAIN-2017-17 | refinedweb | 218 | 69.52 |
Java applet
This content was COPIED from BrainMass.com - View the original, and get the already-completed solution here!
Your team period). Make sure you initialize (implement init()) your applet.
You need the code that does the calculation of the interest.
You need to handle the event of pressing the button.
Please create an HTML page that contains the applet tag. In addition to your mortgage calculator commented Java code, you need to provide the HTML page.
Here is an example given to me from a facilitator to create an applet:
--------------------------------------------------------------------------------
mport java.applet.*;
import java.awt.*;
/**
* The HelloWorld class implements an applet that
* simply displays "Hello World!".
*/
public class HelloWorld extends Applet {
public void paint(Graphics g){
// Display "Hello World!"
g.drawString("Hello world!", 50, 25);
}
}
--------------------------------------------------------------------------------
Then you would compile the class and create an HTML page called Hello.htm (ignore the periods, they're there to make the HTML code viewable):
--------------------------------------------------------------------------------
<.HTML>
<.HEAD>
<.TITLE>A Simple Program<./TITLE>
<./HEAD>
<.BODY>
Here is the output of my program:
<.APPLET CODE="HelloWorld.class" WIDTH=150 HEIGHT=25>
<./APPLET>
<./BODY>
<./HTML>
Solution Preview
Please see the attachment.
RESolutions.java is an application. It ...
Solution Summary
Write a java applet for their web site that would enable customers to figure out their monthly mortgage payments. | https://brainmass.com/computer-science/java/java-applet-119715 | CC-MAIN-2021-25 | refinedweb | 213 | 60.92 |
Logic Errors in Lambda Functions
Now that we’ve setup error logging for our API, we are ready to go over the workflow for debugging the various types of errors we’ll run into.
First up, there are errors that can happen in our Lambda function code. Now we all know that we almost never make mistakes in our code. However, it’s still worth going over this very “unlikely” scenario.
Create a New Branch
Let’s start by creating a new branch that we’ll use while working through the following examples.
In the project root for your backend repo, run the following:
$ git checkout -b debug
Push Some Faulty Code
Let’s trigger an error in
get.js by commenting out the
noteId field in the DynamoDB call’s Key definition. This will cause the DynamoDB call to fail and in turn cause the Lambda function to fail.
Replace
services/notes/get.js with the following.
import handler from "./libs/handler-lib"; import dynamoDb from "./libs/dynamodb-lib"; export const main = handler(async (event, context) => { const params = { TableName: process.env.tableName, // 'Key' defines the partition key and sort key of the item to be retrieved // - 'userId': Identity Pool identity id of the authenticated user // - 'noteId': path parameter Key: { userId: event.requestContext.identity.cognitoIdentityId, // noteId: event.pathParameters.id } }; const result = await dynamoDb.get(params); if ( ! result.Item) { throw new Error("Item not found."); } // Return the retrieved item return result.Item; });
Note the line that we’ve commented out.
Let’s commit our changes.
$ git add . $ git commit -m "Adding some faulty code" $ git push --set-upstream origin debug
Deploy the Faulty Code
Head over to your Seed dashboard and select the prod stage in the pipeline and hit Deploy.
Select the debug branch from the dropdown and hit Deploy.
This will deploy our faulty code to production.
Head over on to your notes app, and select a note. You’ll notice the page fails to load with an error alert.
Debug Logic Errors
To start with, you should get an email from Sentry about this error. Go to Sentry and you should see the error showing at the top. Select the error.
You’ll see that our frontend error handler is logging the API endpoint that failed.
You’ll also get an email from Seed telling you that there was an error in your Lambda functions. If you click on the Issues tab you’ll see the error at the top.
And if you click on the error, you’ll see the error message and stack trace.
If you scroll down a bit further you’ll notice the entire request log. Including debug messages from the AWS SDK as it tries to call DynamoDB.
The message
The provided key element does not match the schema, says that there is something wrong with the
Key that we passed in. Our debug messages helped guide us to the source of the problem!
Next let’s look at how we can debug unexpected errors in our Lambda functions.
For help and discussionComments on this chapter | https://serverless-stack.com/chapters/logic-errors-in-lambda-functions.html | CC-MAIN-2021-04 | refinedweb | 513 | 75.4 |
Good documentation is an important part of a successful product. Creating full and comprehensive description of functions and capabilities of a software product or component takes time and patience. In this article, I will discuss some practical aspects of creating documentation for .NET components.
Let's assume that we have finished or almost finished creating a .NET developer library (developers are end users in this case). Library's API is perfect, the number of bugs impressively small, and indeed it is not a library, but simply a storehouse of perfect code. One little thing is left to do. We need to explain to users how to use this wonderful product.
There are different approaches to writing documentation. Some teams prefer to start producing documentation at the time of inception of the product. Others postpone writing manuals to a later time. In some teams, there are people who go from developer to developer and from manager to manager asking questions and accumulating knowledge about the product. These people are responsible for writing documentation for the product. In many small teams, there are no such people and the documentation is often written by a product developer or developers. Some teams use third-party tools like Help & Manual, which, as a full-fledged text processor, can be used to create documentation with a very complex layout of the pages. Such tools are also good for producing documentation in a variety of formats like PDF, CHM etc. Many people use a different approach, widely advocated in recent years - they write documentation directly in the code of the product.
I have used third-party tools and wrote documentation directly in the code, tried to start writing documentation before and after development is done. In the end, I decided for myself that it's better to postpone writing manuals to the second half of a product development cycle. The closer to completion the more stable the API, feature set, etc., and less adjustments to the documentation will be needed. Writing documentation directly in the code eventually proved to be more convenient than using third-party tools, although at first it seemed quite the opposite. This article is just about how to write documentation directly in your code and what you can do with the written one later.
The C# and VB.NET compilers are able to recognize comments, decorated in a special way (XML comments) and, if necessary, create an XML file which can then be used to generate the documentation. In order to create documentation this way, it's needed to describe all the public code entities (classes, interfaces, methods, etc.) using XML comments. The XML comments start with three forward slashes. It looks like this:
public
/// <summary>
/// Gets the R component from ABGR value returned by
/// <see cref="O:BitMiracle.LibTiff.Classic.Tiff.ReadRGBAImage">ReadRGBAImage</see>.
/// </summary>
/// <param name="abgr">The ABGR value.</param>
/// <returns>The R component from ABGR value.</returns>
public static int GetR(int abgr)
{
return (abgr & 0xff);
}
The creation of an XML file from the comments is disabled by default. It should be enabled in the project properties on Build tab.
As a result, an XML file will be created upon each build of your executable or assembly. That file will contain all the XML comments from the code, including comments for all non-public entities. This file is useful in itself because when you put it next to the assembly, the IntelliSense feature in Visual Studio will use information from this file to display descriptions for the methods, properties and parameters of the assembly. Here is an example of how it will look for a function GetR shown above:
GetR
However, in most cases, the generated XML file will contain comments for the internal entities that users should not see. Later in this article, I'll show how to automatically remove information for non-public entities from the XML file.
I'm not going to describe all possible XML comment tags, but will try to briefly describe the most commonly used ones.
The summary tag is used for a description of the class, interface, enumeration, methods and properties of a class or interface, and members of the enumeration. The param tag is used to describe a parameter for a method. This tag should be used for each method parameter. The returns tag is used to describe method return value (if any). The value tag is useful to describe the value that a property accepts or returns. In a sense, the value tag is an analog of the returns tag but is used for properties instead of methods.
summary
param
returns
value
/// <summary>
/// Gets the font ascent.
/// </summary>
/// <value>The font ascent.</value>
/// <remarks>Ascent is the maximum height above the baseline reached
/// by glyphs in this font, excluding the height of glyphs for
/// accented characters.</remarks>
public short Ascent
{
get
{
return Impl.Ascent;
}
}
Very useful and, unfortunately, often overlooked is the remarks tag, which allows you to specify remarks for a code entity. This tag can be used in comments for almost any code entity except enumeration values. In fact, you can use remarks tag for enum values, but the compiled documentation (CHM file) produced from XML comments using default style (vs2005 style) won't contain such remarks. This default behavior obviously reduces the usefulness of remarks for enum values.
remarks
enum
Here are some more practical observations and recommendations.
I recommend you to download and install the GhostDoc plug-in for Visual Studio. This plug-in is compatible with all versions of Visual Studio newer than Visual Studio 2005 and greatly simplifies the authoring of XML comments. GhostDoc generates and inserts XML comment for a method or property near the cursor position when you press Ctrl-Shift-D. The plug-in inserts all the necessary tags and generates text for them based on types, names and other contextual information. Often you will only need to correct and complete the generated text.
The biggest drawback of writing documentation directly in the code is that the comments sometimes take more space than the code itself. This may make the code difficult to read. To circumvent the problem, it's very convenient to separate public interface and its implementation completely.
Compiled documentation will contain a separate page for each group of overloaded methods. You can take a look at such page in Docotic.Pdf library help. For a text you want to be shown above the Overload List section on such pages the overloads tag should be used.
overloads
/// <summary>
/// Adds the new image with the data and properties of the specified
/// <see cref="Image"/> to the end of the collection of document images.
/// </summary>
/// <param name="image">The existing <see cref="Image"/> from which
/// to create the <see cref="PdfImage"/>.</param>
/// <returns>The newly added <see cref="PdfImage"/> for the first
/// frame (page) found in the existing <see cref="Image"/>.</returns>
/// <overloads>Adds the new image to the end of the collection of
/// document images.</overloads>
/// <remarks>This method adds a new image for each frame (page) found
/// in the existing <see cref="Image"/>.</remarks>
public PdfImage AddImage(Image image)
{
return impl.AddImage(image);
}
You may want to provide a link to another method or type in an XML comment. For such a link, you should use a text like this:
<see cref="X:MEMBER">link text</see>
In a code above X is an optional prefix denoting an entity type and MEMBER is a full or partial specification of the entity. Type prefixes are as following: T for a class, M for a method, P for a property, O for a group of overloaded methods. You can use partial specification and omit the prefix for links between the two methods of the same class or between two entities of the same namespace.
X
MEMBER
T
M
P
O
The following code shows partial specification used to link to PdfFontEmbedStyle enum from description of a property in PdfFont class. Both the enum and the class are contained in the same namespace:
PdfFontEmbedStyle enum
PdfFont
public sealed class PdfFont
{
...
/// <summary>
/// Gets or sets the <see cref="PdfFontEmbedStyle"/> value that specifies
/// how this font is embedded into the document.
/// </summary>
/// <value>The <see cref="PdfFontEmbedStyle"/> value that specifies
/// how this font is embedded into the document.</value>
public PdfFontEmbedStyle EmbedStyle
{
get
{
return Impl.EmbedStyle;
}
set
{
Impl.EmbedStyle = value;
}
}
}
If you link to an entity in another namespace, to a group of overloaded methods or to a specific method in a group of overloaded methods, you should always use full specification or your link may be broken in compiled documentation. Examples of links with full specification:
<see cref="P:System.Exception.HResult"/>
<see cref="M:BitMiracle.LibTiff.Classic.Tiff.GetR(System.Int32)"/>
<see cref="O:BitMiracle.LibTiff.Classic.Tiff.PrintDirectory"/>
<see cref="T:BitMiracle.LibTiff.Classic.TiffTagMethods"/>
As you can see, any full specification contains method parameters. This helps to resolve the link but complicates the link text. You can save manual labor by copying the full specifications from a previously produced XML comments file.
There is an annoyance associated with links to a group of overloaded methods. Visual Studio requires such references to be specified as O:XXX.YYY, and the Sandcastle Help File Builder (this tool I will use later to compile help file) requires such references to be specified as Overload:XXX.YYY. To solve this problem, I use a simple script that gets called on Post-build event and replaces all occurrences of O: in produced XML comments file with Overload:.
O:XXX.YYY
Overload:XXX.YYY
O:
Overload:
For links to some external, not related to the description of the API, page of your documentation or a resource on the Internet, use good old <a> tag with href attribute. For example, <a href = "54cbd23d-dc55-44b9-921f-3a06efc2f6ce.htm">link text</a> or <a href = "">another link text</a>. In the first example, the href attribute contains string formatted as "TOPIC_ID.htm". What is the TOPIC_ID and where you can get one will be described further.
<a>
<a href = "54cbd23d-dc55-44b9-921f-3a06efc2f6ce.htm">link text</a>
<a href = "">another link text</a>
href
TOPIC_ID
You can read more about XML comments in the following articles:
Once the XML comments for your component are ready, you can generate documentation file from them. I prefer to use Sandcastle and Sandcastle Help File Builder (SHFB) for this task. Some people prefer DocProject for this. You may want to read a discussion on Stack Overflow about SHFB and DocProject. If you decide to use SHFB then you should:
Let's build the documentation in CHM format. To do this, run Sandcastle Help File Builder and configure Project Properties. You can configure additional components used by SHFB during the build using "ComponentConfigurations" property. If you do not know what components you may need, you can select all the components. In any case, I recommend that you always use IntelliSense Component, as it automatically creates a copy of the input XML file, cleansed of all comments for non-public code entities. You should provide your users with an XML file produced by IntelliSense Component and not the XML file which was created during build of your component.
Also, I recommend changing the following properties:
Next, specify Documentation Sources in the Project Explorer window. I recommend you to specify the DLL and XML files produced during the build of your component as documentation sources, not your project file. If you specify your project file as documentation source you may face a problem: changes in the XML comments are not always reflected in the documentation. Even after rebuild of the documentation. Who is to blame for this problem, I do not know.
Another important step is to describe the namespaces in SHFB. Your code can not have XML comments for namespace so you need to do specify such comments manually in SHFB. The Comments section and NamespaceSummaries property in the section should be used for the task. You can use standard HTML tags for namespace comments.
The documentation project is set up, it's time to build CHM file. We should execute Documentation->Build Project command and if everything is done right then we get a nice MSDN-style help file built.
For more information about Sandcastle Help File Builder take a look at this article.
Description of classes, methods and other code entities is important part of the documentation, but not sufficient one. Good documentation usually includes additional articles, examples, FAQ, etc. Let's see how you can add topics to your help file.
First, you need to open Content Layout window. To do so, right-click in Project Explorer window and select Add->New Item->Content Layout in context menu. Topics should be added to documentation by means of Content Layout window. You can also specify order of topics, default topic, etc.
The markup language for topics is MAML. It's an XML-based format. Topics are stored in *.aml files. Sandcastle Help File Builder contains a set of topic templates which is quite handy. For me, most useful templates are Conceptual and Walkthrough.
Each new topic gets a topic ID. Later, this ID will be used to generate a name for an HTML file produced from topic markup. A produced HTML file will be included in compiled help file. The topic ID is also used to refer to a topic from other topics or from XML comments in the code of your component.
When you create a new topic, SHFB will prompt you to save the topic in a file. A default name for the file is "TOPIC_ID.aml". You may and, probably, should change default name to something like "Topic Title.aml".
Let's look at some GUI elements in SHFB, which are useful when editing topics.
Sets the default topic. This topic will be opened when CHM file is opened.
Sets the API insertion point. Depending on what option is selected, the pages generated from XML comments in your code will be inserted either before or after or as child elements of an element marked as API insertion point.
Opens preview of the current topic.
Inserts template of a link to a topic. You should fill the template with topic ID of the target topic.
Inserts a MAML tag. You can select a tag to insert from dropdown list.
You can use the Entity Reference window (in the picture above it's shown on the right) to insert code entity references into currently open topic. But I think that this window is not very convenient because in order to insert a link at cursor position we need to first open the topic in editor, then open the Entity Reference window, then write a part or full name of the entity, then find an entity in search results and then double-click on it. I prefer to insert references by hand. To do so, I find a text for the references in previous build log.
You should use <code> tag, if you need to insert a code snippet to a topic. Example:
<code>
<code language="cs">
private void helloWorld()
{
Console.WriteLine("Hello World!");
}
</code>
In order to insert an image to a topic, you should do the following:
To insert an image to topic you should use the mediaLink tag like this:
mediaLink
<mediaLink><image xlink:</mediaLink>
Unfortunately, the current version of built-in editor in SHFB is far from perfect. For example, the tags are not closed automatically, too many actions have no associated hotkeys, and some standard MAML tags cannot be inserted by means of the toolbar. It's weird, but I found that most of topic authoring tasks are easier to perform with Visual Studio XML editor. Of course, you can use any other XML editor when writing topics.
That was my description of how to perform basic topic authoring tasks. I recommend you the following links if you want more information:
You can include a Sandcastle Help File Builder project file (*.shfbproj) into a Visual Studio solution, but it won't be added as full-blown project. That is, the project will only be added to the Solution Items group and you won't be able to see its contents.
To include a SHFB project into a Visual Studio solution, do the following:
After that, you'll be able to open help project from within Visual Studio using double click on a help project name.
I think that ability to build help file from the command line is more useful. You can build your help file on Post-Build event, for example. Here is a command you can use to build a Sandcastle Help File Builder project from the command line:
%SystemRoot%\Microsoft.NET\Framework\v3.5\MSBuild.exe"
/p:Configuration=Release Help.shfbproj
In a line above Help.shfbproj is the filename of the SHFB project to be built.
Hopefully, this article will help you start writing the documentation for your projects. Good luck with authoring your help files!
P.S.: You can always download the source code package of LibTiff.Net, if you want to see a sample of the SHFB project and topic files.
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
<member name="M:classes.myclass.mymethod">
<summary>Some explanation here!</summary>
</member>
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | https://www.codeproject.com/Articles/141766/Creating-documentation-for-a-NET-component-with-Sa?msg=4110702 | CC-MAIN-2017-22 | refinedweb | 2,932 | 55.84 |
hi kevin/folks:
just update about this issue.
this morning my X got froze after long weekend -- I was able to work on it in ssh all the time though.
I have 2 screen sessions previously created using option 2) -- start screen inside ssh connections to loopback.
I killed the X and got a new X.
I re-attached my 2 old screen sessions. here is what I observed:
everything "looks" is still there, but
all my own vim key mappings got lost, only the default key maps work. --- looks vim issue.
all login sessions (telnet/ssh) to remote servers got lost, --- look vim issue. (I run vim ConqueTerm plugin and login to server from that)
vim behave strange, no "tab completion" under vim cmd now. ---looks vim issue
cp/paste doesn't work well, this looks expected I think, guess this is because vim is still sticking to previous X clipboard
while it is now running with a new X (display ID changed) ---looks X issue.
so overall I can't blame screen at all.
I'm going to switch to option 1: start screen in console and re-attach it in X. just it's boring to type export DISPLAY=:0.0 in every windows.
is there a way to automatically execute a cmd(s) right before a new windows got created?
and, furthermore, anyone had better vim/screen integration tips/solutions is highly welcomed to share his/her experiences ...
thanks!
regards
ping
On 08/02/2011 06:32 PM, ping wrote:kevin,
thanks for your time on that. but you forget " when you yank to register, so to yank things to X clipboard, type:
"+
not just +
yes I just tested your 2 more alternates out, here is the results:
option 1) the export DISPLAY method works great!
option 2) the ssh method also works in terms of copy&paste
I have to wait and see it survives across next X restart--I think it can.
and, I think this option2) also has its value given that option1 works, imaging I can create a screen from ssh remotely. starting screen from console I need to have physical access to my laptop...
thanks again! I hope other screen/vim-lovers also enjoy these workarounds.
regards
ping
On 08/02/2011 12:13 PM, Kevin Van Workum wrote:
On Mon, Aug 1, 2011 at 5:12 PM, ping <address@hidden> wrote:
hi Kevin / Paul : yes I think this might be vim issue. or , at least vim-screen integration issue. but being able to use vim smoothly in screen is essential for my daily work and it is a big part of my use of screen. the steps to reproduce is quick simple: 1) c-s-5 to go to console 5 2) start screen : screen -S test 3) c-s-7 to go back X 4) screen -dR test to attach the screen 5) start vim in screen session 0 (or any other sessions) vim 6) type "i" go into insert mode, then start to type anything there, for example: some texts that I want to coy to editor geany type <esc> key to leave insert mode 7) shift-v to mark the line in vim, "+y to copy it into register "+ now at this point, ":registers" command shows the texts are in "0 "" and ". register, but not even in the "+ register. I think that's why I can't paste it to any apps in X.
This does not work for me either. But it does not work for me under X or outside of screen either. After shift-v, pressing + gives me a system beep indicating some error. Pressing y does the usual yank.and the "left button to mark and select and middle button to paste" method that usually works in X seems not work for vim, at least in my case... its ok for other editors like nano.Using the mouse works fine for me.I think the "left button text mark" was intercepted by vim for other usage. that said, if I disable mouse in vim(set mouse-=a), I'm ok to achieve the same effect with that method. but again, I don't understand why vim "+ or "* register doesn't cooperatively work inside screen that started outside of X (from console in this case). and, as what I usually did, if I start screen from inside X and start vim there (but vim won't survive accross X reboot, OK, that's another issue), with the help of these vimrc config: if match($TERM, "screen")!=-1 set term=xterm let g:GNU_Screen_used = 1 else let g:GNU_Screen_used = 0 endif or even this: if match($TERM, "screen")!=-1 set term=xterm endif (see this) I can copy things to "+ or "* and then paste the content from these registers to X apps...This still did not work for me. I see nothing in the + register and get the system beep.I'm not sure if plugin fakeclip that another advice I got from this alias work or not (looks most for maxOS), I haven't try it yet...
How about this idea. Under X, open an terminal. Then ssh to localhost. Then start screen. The screen session should persist across X reboots since sshd is started outside of X. You might want to experiment with the -X and -Y option to ssh to see if that has any affect.
Another idea. Do as before (start screen from a non-X console) and do a "export DISPLAY=:0.0" or what every display you are on before starting vim. Maybe vim and/or your mouse is using that to get to the xclipboard.thanks. regards ping > On 08/01/2011 04:28 PM, Paul Ackersviller wrote: This is now just a problem with vim and not specific to screen, correct? I don't know why any of the above is ever necessary, unless it's some sort of workaround for the use of ttymouse. If you're setting ttymouse in vim (or maybe someone else is setting it for you), you need to hold down a shift key for vim to ignore mouse clicks and pass them through to the terminal.
On 07/29/2011 02:16.
--
Kevin Van Workum, PhD
Sabalcore Computing Inc.
Run your code on 500 processors.
--
Kevin Van Workum, PhD
Sabalcore Computing Inc.
Run your code on 500 processors. | https://lists.gnu.org/archive/html/screen-users/2011-09/msg00004.html | CC-MAIN-2021-25 | refinedweb | 1,067 | 80.31 |
My development cloud recently moved from public to a private lan , after that I am failing to register my local vSphere Client with a new vCenter. I keep getting the Auth fail error.Pasting the error below
"VMWARE_CFG_DIR is chosen to be: C:/ProgramData/VMware/vCenterServer/cfg/
Has connection problem with vCenter server IP: 192.168.36.202. Please check vCenter server and authentication.
Auth fail"
Rather than changing the ip address, username and password of the new vCenter in the command "server-registration.bat -vcip <new ip> -u <new username> -pw <new password> -p 22 -v, is there anything else I need to change. I am able to connect through ssh and browser.I am using vCenter 7.0. vSphere Web Client is 6.7.
Hello,
This seems to be a problem with JSch not being able to ssh to the vCenter. "Auth fail" means that connectivity is not a problem - rather the client cannot authenticate to the server. It is very likely that there is a mismatch between the public key of the client and what the server has in its authorized keys records. Can you please check everything is fine with the ssh keys?
Regards,
Plam
Hi ,
Thanks for the reply
I am able to login to vCenter Server using putty with our username and password.
The authorized_keys file is blank inside the .ssh directory. Can this be the issue?
How can we establish a ssh connection between vSphere Client and vCenter server? What are the steps for it?
Hello,
Just to confirm - you checked the authorized_keys file on the vCenter, not on your machine right? It seems that the vCenter is rejecting your public key so that there is probably a stale entry there. This may not be the case, however, since you are able to connect via Putty but is worth checking.
You do not need to establish an ssh connection between the vSphere Client and the vCenter Server. The server-registration script establishes an ssh connection between your machine and the vCenter to transfer over a couple of configuration files. It seems like the problem is that the vCenter rejects the ssh connection.
Regards,
Plam
Yes. I was checking the .ssh/authorized_keys file in the vCenter server. It is completely empty. Should I copy a public key from client to the authorized_keys file in server?
As far I understand SSH, there are two ways of authenticaiton. One using username and password and other using public and private keys. Here I think server-registration.bat is using username and password for autehntication right?
Auth fail error won't be caused by configuration files right as copying of configuration files happens only after successful connection and here connection itself is not established.
This might be irrelevant but is there any requirement that the login details has to be in single quotes or double quotes ? server-registration.bat -vcip ipaddress -u <usrname> -pw <pwd> -p 22 -v
Hello,
You are correct, username/password is used for authentication so the problem should be with how the username/password is passed to the script (excuse me for causing some confusion).
On Windows you can use double quotes (make sure any special symbols are escaped) and on Mac - single ones (should escape automatically). I've tried locally (on both Windows and Mac VMs) and didn't run into any problems using the 6.7 script on a 7.0 vCenter. My only guess at the moment is that there are some special symbols in the username/pass that are causing problems.
Do you maybe have another vCenter for you to try the script against? Or another VM that you can run the script from (against the same vCenter and a different vCenter)?
Regards,
Plam
Hi Thanks for the reply.
Now we are getting this'
Have you seen this error before.
Hi Plam_Dimitrov ,
I tried to manually register the vSphere Client.
After running the startup.bat script and logging into localhost://9443/ui , this is the error I am getting
One or more vCenter Server systems are incompatible with the vSphere Web Client:
I am able to succesfully register to another vCenter that is version 6.7 and also in public network. When I try to register using server-registration.bat script to a vCenter in same private network as my vNSC, it fails. with following'
could this be due to some firewall in the network?
Hello,
The "One or more vCenter Server systems are incompatible with the vSphere Web Client" error you are seeing is most likely due to trying to connect your 6.7 vSphere Client to a 7.0 vCenter. We'd suggest you to get the 7.0 vSphere Client SDK and use that to connect to the 7.0 vCenter? This may also help with your second problem - since you are running the scripts against the 7.0 vCenter, try using the scripts inside the 7.0 vSphere Client SDK. Please, if you encounter any problems send us the vsphere_client_virgo logs and the registration tool command line and output. A firewall rule issue is a possibility but seems unlikely (the ssh client seems to successfully connect over TCP on port 22).
Regards,
Plam
Hi Plam Dimitrov,
Looks like you were right last time.Versions were incompatible. After manual registration of vSphere Client 6.7 with a vCenter server 6.7 in our privatelan, I was able to configure my local Web browser application to interact with vCenter.
But as we are planning to use vCenter server 7.0, we have to use vSphere Client SDK 7.0.
There are some changes in vSphere Client SDK 7.0. There is no Eclipse plugin and Eclipse is not used to start Tomcat server.
According to docs, there is plugin generation scripts folder of vSphere Client 7.0 inside "SDK_folder\html-client-sdk\tools\Plugin generation scripts" should be used to create a plugin.
But that folder is not available along with the scripts. Where can I get them?
When I try to run http-sample project after manual registration, I am getting this error
Plugin configuration for reverse proxy failed
What causes this error?
Hello,
Regarding yoyr first question: The generation scripts are removed from the SDK delivery for 7.0. It is a mistake from our side not to update the docs accordingly. Apologies.
Regarding your second question: I am not sure which plugin sample you refer to by http-sample.
If we are talking about a local plugin, the html-sample, then you should not see this error, as it is related to a remote plugin. Or it is probably an error from another remote plugin on your local environment.
If we are talking about a remote plugin, then one reason for the "Plugin configuration for reverse proxy failed" failure might be if you are running vSphere Client on localhost. Then your Client tries to register proxy rules at your localhost, where there is no proxy.
If that is not the case, then you need to attach the logs so that we can follow what is happening.
Hope this helps.
Regards,
Dimitar
Hi I have attached vsphere_client_virgo.log file along with this reply.
This is the log after running the startup.bat file.
Many of the errors are due to missing files like config.xml, vspherefeatures.cfg ..etc. inside "C:\ProgramData\VMware\vCenterServer\cfg\" directory.
Right now I have only vsphere-client, vsphere-ui and store.jks inside "C:\ProgramData\VMware\vCenterServer\cfg\" directory. What should be done to get the remaining files?
Hi,
Whenever I try to register vSphere Client 7.0 with vCenter server 6.7 , I am getting this error.
"An error occurred while sending an authentication request to the vCenter Single Sign-On server - An error occurred when processing the metadata during vCenter Single Sign-On setup - Couldn't find SSO servers for the local domain."
But if I try to register vSphere Client 7.0 with vCenter server 7.0, there is sso error , but the sample plugin "html-sample" fails to get deployed due to the error "Plugin configuration for reverse proxy failed"
How are the files in the directory "C:\ProgramData\VMware\vCenterServer\cfg\" created?
I am guessing the errors are due to missing files. I am attaching the log file again for reference. This log is after running startup.bat file in my dev environment.
Just to confirm , we are running local plugin not remote plugin
Hi AnoopHPE,
Why do you want to register 7.0 vSphere Client SDK to a 6.7 vCenter ?
Also about the errors, you can try to resolve it by creating the missing files:
C:\ProgramData\VMware\vCenterServer\cfg\vsphereFeatures\vsphereFeatures.cfg
C:/ProgramData/VMware/vCenterServer/cfg/\vsphereFeatures\techPreview.cfg
If there are additiona errors after this, please share them with us.
Martin
I tried registering 7.0 Client with 6.7 vCenter server to check whether they are compatible, as it is said in the document.
Right now I am trying 7.0 Client with 7.0 vCenter server.
Now I am able to register sample plugin "html-sample" successfully. But I am getting this error for my plugin
Error deploying plug-in. org.osgi.service.resolver.ResolutionException: Unable to resolve /C:/vsphere-client-sdk-7.0.0.10100-15863815/html-client-sdk/vsphere-ui/plugin-packages/vnsui/com.hpe.vnsui-1.1.15.esa/vns-ui.war: missing requirement org.apache.aries.subsystem.core.archive.ImportPackageRequirement: namespace=osgi.wiring.package, attributes={}, directives={filter=(&(osgi.wiring.package=com.hpe.vnsui.nskVolume)-ui.war ] org.apache.felix.resolver.ResolutionError.toException(ResolutionError.java:42)
When I unzipped "com.hpe.vnsui-1.1.15.esa" , the war file is present though.
Regards,
Anoop
Hi,
As the error says:
com.hpe.vnsui.nskVolume is missing from the manifest of the war service.
Please take a look and fix the missing packages from the manifest of the war and jar services as well.
On second thought as the error has
I think that the com.vmware.o11n.sdk.rest.client.impl might be missing from the jar manifest file.
Martin.
Hi,
When I place my plugin in "html-client-sdk-6.7.0-8170180\vsphere-ui\plugin-packages" and run startup.bat in the "html-client-sdk-6.7.0-8170180\vsphere-ui\server\bin", it is working fine.
But when I placed the same plugin in "vsphere-client-sdk-7.0.0.10100-15863815\html-client-sdk\vsphere-ui\plugin-packages" and run startup.bat in "vsphere-client-sdk-7.0.0.10100-15863815\html-client-sdk\vsphere-ui\server\bin" it fails to deploy.
Only sdk version has changed.
What could be the reason?
Is there a way to start the server using Eclipse? | https://communities.vmware.com/t5/vSphere-Client-SDK-Discussions/Failing-to-register-the-local-vsphere-Client-with-vCenter/m-p/2289686/highlight/true | CC-MAIN-2021-10 | refinedweb | 1,789 | 68.16 |
Anyone who has done any Windows Forms programming in the .NET Framework is familiar with the
MessageBox class. However, the managed
MessageBox is missing a few capabilities that are available in the Win32 API, including the ability to add a Help button, specify a language to be used in the dialog buttons, and add a custom icon. In this article, I present a managed wrapper for the
MessageBoxIndirect Win32 API function that provides these capabilities.
The Win32 API includes three functions for presenting message boxes to the user. These are
MessageBox,
MessageBoxEx, and
MessageBoxIndirect. Of the three,
MessageBoxIndirect is the most powerful, allowing you to add a Help button, custom icon, and specific language for the button text. It is also the least programmer-friendly, which often leads people to put a friendly wrapper class around it. One example of doing that in C++ can be found in this Code Project article.
Getting access to the
MessageBoxIndirect function from the managed world of the .NET Framework means writing some interop code using Platform Invoke (
PInvoke). Since
PInvoke code can be somewhat tricky to read and write, you generally want to do it once, get it working, and forget about it. That means you should wrap it in a reusable class. Enter the
MessageBoxIndirect class, a C# wrapper class that exposes the full functionality of the
MessageBoxIndirect API.
The
MessageBoxIndirect class exposes four key capabilities of the underlying
MessageBoxIndirect API: Choosing different modalities for the alert, specifying a language identifier to be used for the buttons, adding a working help button, and adding a custom icon. We will discuss each of these in details below, but first I will mention a few design decisions.
MessageBoxIndirect supports the standard
MessageBox behaviors, such as the ability to choose from a standard set of buttons and icons. Thus, where possible to simplify the programming model, the
MessageBoxIndirect class uses enumerations defined in the existing
MessageBox class, such as
MessageBoxButtons,
MessageBoxDefaultButton,
MessageBoxOptions, and
DialogResult.
In my opinion, the
MessageBox class in the .NET Framework is a great example of not-so-great object-oriented design. It is a static class. That is, it just provides a namespace for a few static
Show methods. Twelve static
Show methods, to be exact. Why is this poor design? Imagine what would happen if Microsoft wanted to add, say, the ability to specify a custom icon for the message box. How many more
Show overloads would that force them to add? With all of these options, the combinatorics of supporting
Show methods for each scenario are really bad for maintenance. What you should really do in this situation is allow the user to create an instance, i.e. "
MessageBox mb = new MessageBox() " and set properties on it. To speed things along, add a few constructor overloads for only the most common options, perhaps text, caption, and buttons.
I adopted the object-oriented model I suggested above for the
MessageBoxIndirect class. To make it easier for you to convert your code to use this class, however, I added constructor overloads that match the signatures of the static
Show methods of the built-in
MessageBox. After you have created your
MessageBoxIndirect instance and set all desired options, you only need to call the instance method
Show (which returns a
DialogResult) to present the message box to the user.
The included solution, MessageBoxIndirect.sln, contains a Windows Application where the
DemoForm form demonstrates a number of different ways to use the
MessageBoxIndirect class. We will now cover these in more detail. In the demo project, the
SetResult method displays the output of the
Show method (i.e. what the user selected) in the status bar of the window.
I have included a Visual C++ solution called Win32Resources which builds a resource DLL containing a custom icon. If you would like to try the part of the demo that loads a custom icon from a separate DLL, build this solution and copy the output DLL to the same location as the demo project executable (\MessageBoxIndirect\bin\Debug or \MessageBoxIndirect\bin\Release).
There are three basic behaviors that a message box can have with respect to what else the user is allowed to do while the message box is up. These are application-modal, task-modal, and system-modal. Application-modal message boxes accept an owner window as a parameter and disallow any interaction with the given window until the message box is dismissed. Task-modal message boxes work the same way, except that the resulting message box window is topmost. This is intended to indicate a relatively serious situation. Finally, system-modal message boxes disallow any interaction with all top-level windows from the calling application without requiring you to pass an owner window.
Here is an example of specifying the modality using the
MessageBoxIndirect class:
MessageBoxIndirect mb = new MessageBoxIndirect( this, "App Modal", "Test" ); mb.Modality = MessageBoxIndirect.MessageBoxExModality.AppModal; DialogResult dr = mb.Show();
The
MessageBoxIndirect class allows you to specify a language identifier (
LangID) indicating the language to use in the default message box buttons. In the following example, I am actually passing a casted locale identifier (
LCID) rather than a
LangID, but bits 0-15 of an
LCID are, in fact, the
LangID, so I can get away with this. A deeper discussion of
LangIDs and
LCIDs is beyond the scope of this article, but if you are interested, check out this MSDN topic on Windows national language support. Note that if you do choose to pass different
LangIDs, you'll need to have the appropriate language(s) installed on your system to see the fruits of your efforts.
MessageBoxIndirect mb = new MessageBoxIndirect( "Pass a LangID: " + Thread.CurrentThread.CurrentUICulture.LCID.ToString(), "Test" ); mb.LanguageID = (uint) Thread.CurrentThread.CurrentUICulture.LCID; DialogResult dr = mb.Show();
You can add a Help button to your message box by setting the
ShowHelp property to
true. There are two different ways that you can handle the help button. First, you can provide a delegate of type
MsgBoxCallback that gets called when the help button is clicked, as in the following example:
MessageBoxIndirect mb = new MessageBoxIndirect( "Help Button", "Test", MessageBoxButtons.YesNoCancel ); mb.ShowHelp = true; mb.ContextHelpID = 555; mb.Callback = new MessageBoxIndirect.MsgBoxCallback( this.ShowHelp ); DialogResult result = mb.Show();
The
ShowHelp function returns void and accepts a
HELPINFO instance. Most importantly, the
dwContextId member of the
HELPINFO instance contains the context ID you set into the
MessageBoxIndirect class before calling
Show (555 in the above example).
The second way to handle help is to request that a
WM_HELP message be sent to the parent window. The following code demonstrates this. Note that we give the
MessageBoxIndirect class an owner window ("
this", presumably the parent form) in the constructor to act as a target for the
WM_HELP message:
MessageBoxIndirect mb = new MessageBoxIndirect( this, "Help Button", "Test", MessageBoxButtons.YesNoCancel ); mb.ShowHelp = true; mb.ContextHelpID = 444; DialogResult result = mb.Show();
To handle the
WM_HELP message in your form's overridden
WndProc, note that
Message.LParam points to a
HELPINFO instance. Before you can use the
HELPINFO, you have to unmarshal it. I added a static helper method to the
HELPINFO class called
UnmarshalFrom to assist you in this process. Just pass it the
LParam and it returns the appropriate
HELPINFO for you to use in invoking help.
This was certainly the most difficult and yet in my opinion the most interesting part of my effort to wrap the
MessageBoxIndirect API. If you set the
MB_USERICON flag,
MessageBoxIndirect attempts to load a resource with the ID given in the
lpszIcon member of
MSGBOXPARAMS from the module whose instance handle is supplied in the
hInstance member. The problem is that this must be a traditional Win32 resource. .NET uses a completely different technique for storing and managing resources, and Visual Studio.NET as of version 2003 seems to be incapable of adding Win32 resources to your compiled assemblies (let alone building .rc scripts into .res files in C# or VB.NET projects), save for the application icon. A discussion of the differences between Win32 and .NET resources is beyond the scope of this article, but suffice to say that to get
MessageBoxIndirect to display a custom icon, you must jump through some hoops. I see three different options for getting your icons into play:
1. You can use a resource-editing tool after building your assembly to slam your icons in as Win32 resources. Although .NET doesn't use the same format for resources, it does create standard Win32 binaries, and there's nothing preventing you from adding resources to them. I do not personally have a tool to recommend to pull this off, so I will not discuss this option further.
2. You can build using the csc.exe or vbc.exe command-line compilers, which support a /win32res flag that allows you to specify a compiled resource file (.res) to link in as Win32 resources. Of course, this option means you must abandon Visual Studio as your build environment, which can be a problem particularly in large projects. Also, the /win32res flag is incompatible with the /win32icon flag for specifying an application icon, so if you choose this route, you'll have to make sure your desired application icon is the lowest-numbered icon resource in your Win32 .res file.
In the sample code, there is a build.bat script that demonstrates this technique using a .res file named Win32Resources.res that I supply. On the demo form, click the "Custom Icon (This Exe)" button to try it out. Note that this button will not give you a custom icon unless you compile using the command line and the /win32res flag.
3. You can dynamically load a resource DLL and pass the resulting instance handle to
MessageBoxIndirect. This is my preferred option. In the sample project, I supply a DLL consisting of just icon resources called Win32Resources.dll. In practice, you'll need to create your resource DLL using a tool like Visual C++. The demo form loads this module up using a
PInvoke of
LoadLibraryEx and instructs
MessageBoxIndirect to use it as the source of a custom icon, as shown in the following code:
if( hWin32Resources == IntPtr.Zero ) { hWin32Resources = LoadLibraryEx( Application.StartupPath + "\\Win32Resources.dll", IntPtr.Zero, 0 ); Debug.Assert( hWin32Resources != IntPtr.Zero ); } // Win32 Resource ID of the icon we want to put in the message box. const int Smiley = 102; MessageBoxIndirect mb = new MessageBoxIndirect( "Custom Icon", "Test" ); // Load the icon from the resource DLL that we loaded. mb.Instance = hWin32Resources; mb.UserIcon = new IntPtr(Smiley); DialogResult result = mb.Show();
If this doesn't work for you, check to make sure that the Win32Resources DLL is in the correct location (next to the application executable).
A detailed discussion of the .NET
Interop code to make the
MessageBoxIndirect class work would fill an article in itself. Fortunately, there are many great tutorials on
Interop and
PInvoke available in MSDN and on the web, so here I will just focus on the highlights specific to calling the
MessageBoxIndirect API.
The
MessageBoxIndirect API function takes a single parameter which is a structure containing all of the options desired for the resulting message box dialog. The declaration is:
[DllImport("user32", EntryPoint="MessageBoxIndirect")] private static extern int _MessageBoxIndirect( ref MSGBOXPARAMS msgboxParams );
Note the "ref" decoration indicating that the underlying API accepts a pointer to a structure.
The structure that gets passed to this function has the following managed declaration:
[StructLayout(LayoutKind.Sequential)] public struct MSGBOXPARAMS { public uint cbSize; public IntPtr hwndOwner; public IntPtr hInstance; public String lpszText; public String lpszCaption; public uint dwStyle; public IntPtr lpszIcon; public IntPtr dwContextHelpId; public MsgBoxCallback lpfnMsgBoxCallback; public uint dwLanguageId; };
This structure (along with the other declarations that follow) originate in the winuser.h Platform SDK header file. Note that we use
IntPtr for each HANDLE as is the recommended practice. Also,
lpszIcon (which we will discuss more later) is defined as an
IntPtr even though it is a
LPCTSTR in the API. That is because the typical value passed to
lpszIcon is the result of a call to the
MAKEINTRESOURCE macro, which simply does some type-casting to make the number it is passed look like an address.
This structure includes a member,
lpfnMsgBoxCallback, which is a callback that gets invoked when the user presses the optional Help button on the message box dialog. In .NET, callbacks are naturally implemented as delegates, and thus we wrap this callback in the following compatible delegate declaration:
public delegate void MsgBoxCallback( HELPINFO lpHelpInfo );
The
HELPINFO structure provides some useful information about the specific help request. Its managed declaration is:
[StructLayout(LayoutKind.Sequential)] public struct HELPINFO { public uint cbSize; public int iContextType; public int iCtrlId; public IntPtr hItemHandle; public IntPtr dwContextId; public POINT MousePos; };
As discussed above, one way to handle the help button on the message box is to process the
WM_HELP message. To retrieve the
HELPINFO while processing
WM_HELP, you need to do some unmarshaling, as in the following helper method defined in the
HELPINFO class:
public static HELPINFO UnmarshalFrom( IntPtr lParam ) { return (HELPINFO) Marshal.PtrToStructure( lParam, typeof( HELPINFO ) ); }
Finally, we define a number of message-box-related constants from winuser.h to use in our implementation, along with the following enumeration to represent the various modal behaviors a message box can take:
public enum MessageBoxExModality : uint { AppModal = MB_APPLMODAL, SystemModal = MB_SYSTEMMODAL, TaskModal = MB_TASKMODAL }
Getting the custom system icon to work was a bit tricky. In theory, all one has to do is send a
WM_SETICON message to the
MessageBox window. The problem is actually getting the window handle to send the message. To pull this off, I install a hook using SetWindowsHookEx for
WH_CBT messages on the executing thread.
DialogResult retval = DialogResult.Cancel; try { // Only hook if we have a reason to, namely, to set the custom icon. if( _sysSmallIcon != IntPtr.Zero ) { HookProc CbtHookProcedure = new HookProc(CbtHookProc); hHook = SetWindowsHookEx(WH_CBT, CbtHookProcedure, (IntPtr) 0, AppDomain.GetCurrentThreadId()); } retval = (DialogResult) _MessageBoxIndirect( ref parms ); } finally { if( hHook > 0 ) { UnhookWindowsHookEx(hHook); hHook = 0; } }
WH_CBT messages can be handy, particularly when automating aspects of the system. In this case, I'm interested in the
HCBT_CREATEWND message, which appears after the window has been created but before
WM_CREATE is broadcast. When I see it, I verify that it is actually for the
MessageBox dialog, load the icon, and send the
WM_SETICON message:
private int CbtHookProc(int nCode, IntPtr wParam, IntPtr lParam) { if( nCode == HCBT_CREATEWND ) { // Make sure this is really a dialog. StringBuilder sb = new StringBuilder(); sb.Capacity = 100; GetClassName( wParam, sb, sb.Capacity ); string className = sb.ToString(); if( className == "#32770" ) { // Found it, look to set the icon if necessary. if( _sysSmallIcon != IntPtr.Zero ) { EnsureInstance(); IntPtr hSmallSysIcon = LoadIcon( Instance, _sysSmallIcon ); if( hSmallSysIcon != IntPtr.Zero ) { SendMessage( wParam, WM_SETICON, new IntPtr(ICON_SMALL), hSmallSysIcon ); } } } } return CallNextHookEx(hHook, nCode, wParam, lParam); }
When hooking, it is essential to end with a call to
CallNextHookEx. After I show the
MessageBox and collect the result, I clean up the hook with
UnhookWindowsHookEx.
Most of the rest of the code in the
MessageBoxIndirect class is to support all of the different constructors, and to build the
dwStyle value from the higher-level properties of the class.
General
News
Question
Answer
Joke
Rant
Admin | http://www.codeproject.com/KB/dialog/MessageBoxIndirectCS.aspx | crawl-002 | refinedweb | 2,523 | 55.03 |
Created on 2014-04-13 01:10 by richard.kiss, last changed 2014-06-30 12:41 by python-dev. This issue is now closed.
import asyncio
import os
def t1(q):
yield from asyncio.sleep(0.5)
q.put_nowait((0, 1, 2, 3, 4, 5))
def t2(q):
v = yield from q.get()
print(v)
q = asyncio.Queue()
asyncio.get_event_loop().run_until_complete(asyncio.wait([t1(q), t2(q)]))
When PYTHONASYNCIODEBUG is set to 1, this causes a strange error:
TypeError: send() takes 2 positional arguments but 7 were given
See also
For a reason that I don't understand, this patch to asyncio fixes the problem:
--- a/asyncio/tasks.py Mon Mar 31 11:31:16 2014 -0700
+++ b/asyncio/tasks.py Sat Apr 12 20:37:02 2014 -0700
@@ -49,7 +49,8 @@
def __next__(self):
return next(self.gen)
- def send(self, value):
+ def send(self, value, *args):
return self.gen.send(value)
def throw(self, exc):
Maybe the problem really is somewhere else, but this works.
I'll be darned. It appears that generator's send() method uses METH_O, which means that it really expects a single argument, but if you pass it a tuple, it assumes that you meant each item in the tuple as a separate argument. I think a more correct fix is attached -- don't add a dummy *args to the send() method, but call self.gen.send((value,)).
I'd like to fix this upstream and add some tests first; also see (which touches upon a different problem in CoroWrapper not emulating the real generator object well enough).
Heh. METH_O was *also* a red herring. But upstream (Tulip) issue 163 *was* a good clue. I now believe that the real bug is that CoroWrapper.__iter__() has "return self" rather than "return iter(self.gen)". That fix is in the 2nd attachment.
The error occurs at line "v = yield from q.get()":
Traceback (most recent call last):
File "/home/haypo/prog/python/default/Lib/asyncio/events.py", line 39, in _run
self._callback(*self._args)
File "/home/haypo/prog/python/default/Lib/asyncio/tasks.py", line 357, in _wakeup
self._step(value, None)
File "/home/haypo/prog/python/default/Lib/asyncio/tasks.py", line 309, in _step
self.set_exception(exc)
File "/home/haypo/prog/python/default/Lib/asyncio/tasks.py", line 301, in _step
result = coro.send(value)
File "put_get_bug.py", line 23, in t2
v = yield from q.get()
TypeError: send() takes 2 positional arguments but 7 were given
Task._step() is called with value=(0, 1, 2, 3, 4, 5) (and exc is None).
gen_send.diff doesn't look like a fix but a workaround.
gen_send_2.diff lacks a unit test.
I don't think that the bug comes from asyncio, but it looks like a bug in the implementation of "yield from" in CPython directly! Try with ceval.patch.
ceval.c has a fast path if the object is a generator. With PYTHONASYNCIODEBUG=1, the object is a CoroWrapper, not a generator. In this case, the slow path is used:
retval = _PyObject_CallMethodId(reciever, &PyId_send, "O", v);
This line comes from the initial commit introducing yield-from:
---
changeset: 74356:d64ac9ab4cd0
user: Nick Coghlan <ncoghlan@gmail.com>
date: Fri Jan 13 21:43:40 2012 +1000
files: Doc/library/dis.rst Doc/library/exceptions.rst Doc/reference/expressions.rst Doc/reference/simple_stmts.rst Doc/whatsnew/3.
description:
Implement PEP 380 - 'yield from' (closes #11682)
---
(The exact line changed and the line was moved, but "O" format didn't change.)
Still no unit test, I'm too tired to write one, and I'm not sure that it's a bug in ceval.c.
Wow. So many fixes! :-) Are you going to be at the CPython sprint tomorrow? I'll be there in the morning but my plane leaves in the afternoon.
> Are you going to be at the CPython sprint tomorrow? I'll be there in the morning but my plane leaves in the afternoon.
I organize a "Port OpenStack to Python3" sprint, but I may come also
to the CPython sprint.
New changeset 05b3a23b3836 by Benjamin Peterson in branch '3.4':
fix sending tuples to custom generator objects with yield from (closes #21209)
New changeset d1eba2645b80 by Benjamin Peterson in branch 'default':
merge 3.4 (#21209)
Hm... Can we also commit this to 3.3?
This is nice (a backport 3.3 would be even nicer) but at least for the PyPI
repo version of Tulip I'd like to have work-around so people won't run into
this when they are using a slightly outdated Python version. I'll think
about which of my work-arounds is safe for that while not breaking the
intended functionality of CoroWrapper (i.e. that it prints a warning when
destructed before it has reached the end). That may require setting an
additional flag.
3.3 is in security-fix only mode.
>?
On Mon, Apr 14, 2014, at 10:20, Yury Selivanov wrote:
>
> Yury Selivanov added the comment:
>
> >?
I don't really have an opinion on this nor is it my call; I'm just
regurgitating policy.
I think I have to add a work-around to Tulip anyway, because I don't want to have to tell people "you must upgrade your Python 3.3 otherwise this problem can happen" (if upgrading was easy for them they would be on 3.4 :-). So I don't care much if the 3.3 backport happens.
Guido: please take a look at the patch "corowrapper_01.patch".
Yuri, thanks for the test, but why would the patch need a version check? Shouldn't the work-around work equally well in Python versions that don't need it? Maybe all we need is a comment explaining that it is a work-around and a hint that eventually we should change it back?
Please see the corowrapper_02.patch. I've removed the version check, now it's much simpler.
OK, looks good. I tried your test with my earlier workaround and the wrapper got deallocated too early, proving that my workaround was indeed wrong and your test is useful. I am still concerned theoretically that the CoroWrapper.send() signature is different from a real generator's send() method, but I think that send() to a coroutine is an internal detail anyway, so I can live with that, and I don't see another work-around.
When you commit, can you do upstgream (Tulip) first?
> [...] CoroWrapper.send() signature is different from a real generator's send() method, but I think that send() to a coroutine is an internal detail anyway [...]
Yeah, and since it's used in debug mode only, I think we should be safe.
> When you commit, can you do upstgream (Tulip) first?
Sure, this patch was for tulip code.
New changeset 0c35d3616df5 by Yury Selivanov in branch '3.4':
asyncio.tasks: Fix CoroWrapper to workaround yield-from bug in CPython < 3.4.1
New changeset 13ff8645be57 by Yury Selivanov in branch 'default':
syncio.tasks: Fix CoroWrapper to workaround yield-from bug in CPython < 3.4.1
Guido,.
"I think we should adjust the solution, to avoid having arguments to 'gen.send' packed in two nested tuples."
I should check, but I think that Python create a tuple for you if you don't pass directly a tuple, so it's not very different.
Anyway, it is only used for debug, so I don't think that performances matter here.
I agree with Yuri and I approve of the patch.
New changeset 2729823525fe by Yury Selivanov in branch '3.4':
asyncio.tasks: Make sure CoroWrapper.send proxies one argument correctly
New changeset 552ee474f3e7 by Yury Selivanov in branch 'default':
asyncio.tasks: Make sure CoroWrapper.send proxies one argument correctly
> I should check, but I think that Python create a tuple for you if you don't pass directly a tuple, so it's not very different.
That's what I thought, but still, better to have the code clearly expressing what it does, than relying on obscure implementation/protocol details.
The added comment contains "This workaround should be removed in 3.5.0.". Since default branch now contains Python 3.5, maybe it is time to remove workaround on default branch?
IMO the comment is too aggressive. I want the workaround to stay in the codebase so CPython asyncio ans Tulip asyncio (== upstream) don't diverge.
New changeset defd09a5339a by Victor Stinner in branch '3.4':
asyncio: sync with Tulip
New changeset 8dc8c93e74c9 by Victor Stinner in branch 'default':
asyncio: sync with Tulip | https://bugs.python.org/issue21209 | CC-MAIN-2021-31 | refinedweb | 1,427 | 76.22 |
I am quite habituated of getting this error…, “Code.exe has stopped working”. As far as I know, this is nothing but runtime errors. But this time even in the simplest of code, I got this error while the input file which is quite large (the code is for taking input in the problem C of Facebook Hacker Cup). You can download the full grading file from the problem link.
And here is the small code for the input. (Please note that this is not the solution code. This code is written only for taking inputs and just checking the source of this error.)
#include<bits/stdc++.h> using namespace std; int main() { #ifndef ONLINE_JUDGE freopen("timber_input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int t; cin>>t; for(int test=1;test<=t;test++) { int n; cin>>n; int p[n],h[n]; vector<pair<int,int>> v; for(int i=0;i<n;i++) {cin>>p[i]>>h[i]; v.push_back(make_pair(p[i],h[i]));} } }
Here’s what Sublime Text 3 says
[Finished in 5.3s with exit code 3221225725] [shell_cmd: g++ "C:\Program Files (x86)\Sublime Text 3\Temp.cpp" -o "C:\Program Files (x86)\Sublime Text 3/Temp" && "C:\Program Files (x86)\Sublime Text 3/Temp"] [dir: C:\Program Files (x86)\Sublime Text 3] [path: C:\Windows\System32;C:\MinGW\bin]
Both the files timber_input.txt and output.txt are in the main folder of Sublime Text 3. Also the C++ file is kept in the same folder.
Could anyone please help me with this. | https://discuss.codechef.com/t/code-exe-has-stopped-working-sublime-text-3/73324 | CC-MAIN-2020-40 | refinedweb | 262 | 76.82 |
Hasura is a great way for storing data and is really easy to setup. I normally don't use the words easy to set up but Hasura really is. As a frontend developer with not that much backend and database experience I really did find Hasura easy and nice to work with.
I created a very simple demo of how to use Hasura in your project to fetch data. Feel free to clone the project and modify it to how you want. You can find the live demo here, it really is just a simple app so don't expect too much. It's basically a list of all the food I need to eat when I get out of lockdown and which restaurants I will go to eat that food.
Once you clone the project you will have to change the
GRAPHCMS_API which is located in the apollo/client-config folder for your own Hasura endpoint. Then add your own data and modify the query if you change the table name or columns.
If you are new to Hasura it is really easy to get started.
I have not recreated these steps in this post as the docs on Hasura explain it so well with screen shots so please don't be afraid to click those links and get stared.
There really are only 2 steps you need to take. The first one is creating your Hasura project and deploying to Heroku and this will only take you 2 mins if you already have a Heroku account setup. If not it might take a few minutes more. Heroku is free but if you prefer other options just check out the Hasura docs.
- Here are the docs to get started deploying with Heroku
The next step is to create a table. But don't worry, no backend knowledge is needed and it is as simple as using the graphical interface to create the table and columns which the docs show you along with screenshots.
- Then you just need to create a table and add some data
For this example I have created a table called food with the following schema
Columns
- id - uuid, primary key, unique, default: gen_random_uuid()
- name - text
- where - text
- img - text
- status - text, default: 'pending'::text
- priority - integer
To add to an existing project
- Install
@nuxtjs/apollo
- Add it to your build modules in the nuxt.config.js
- Give apollo module options in the nuxt.config.js
apollo: { clientConfigs: { default: '~/apollo/client-configs/default.js' } },
- Add a config file for apollo
mkdir apollo mkdir apollo/client-configs touch apollo/client-configs/default.js
- Add the following code inside remembering to replace the endpoint with the endpoint you get from Hasura
import { HttpLink } from 'apollo-link-http' import { InMemoryCache } from 'apollo-cache-inmemory' // Replace this with your project's endpoint const GRAPHCMS_API = '' export default () => ({ link: new HttpLink({ uri: GRAPHCMS_API }), cache: new InMemoryCache(), defaultHttpLink: false })
- In your component add your query in within the script tags
import gql from 'graphql-tag' export const food = gql` query { food { id img name priority status where } } `
- And add this below it
export default { data() { return { food: [] } }, apollo: { $loadingKey: 'loading', food: { query: food } } }
That's all you need. You should now have your Hasura endpoint and your application making a query to view the data which you can now display in your template. Have fun
<div v- <h2>{{ item.name }}</h2> </div>
Discussion (5)
where can i put my hasura secret key in nuxt?
before I am using vue js and this is how it works with websocket but
I'm confused how to config in nuxt with hasura
const httpLink = new HttpLink({
uri: "https://",
headers: {
'x-hasura-admin-secret': ''
}
});
const wsLink = new WebSocketLink({
uri: "wss://",
options: {
reconnect: true,
timeout: 30000,
connectionParams() {
return {
headers: {
'x-hasura-admin-secret': ''
}
}
}
}
})
hey, sorry only seeing this now. the secret key should be a secret so should go in Netlify / Heroku or where you have it hosted as env variable.
see if this helps
dev.to/debs_obrien/securing-your-h...
Now, I have to wonder about security of Hasura, and public API's in general.
But, I see that you can set up CORS.
Actually I am writing another post on that. Hasura is really secure but you do need to secure your api by clicking the secure api button and adding a secret key and then you just create a public user that can say select from database only or add depending on what you want them to do and of course you can set up admin roles with authentication etc. Think of Hasura as similar to how Firebase works. | https://practicaldev-herokuapp-com.global.ssl.fastly.net/debs_obrien/getting-data-from-hasura-onto-your-nuxt-js-app-5dpn | CC-MAIN-2021-21 | refinedweb | 774 | 65.96 |
Opened 7 years ago
Closed 7 years ago
Last modified 7 years ago
#20867 closed New feature (fixed)
Allow Form.clean() to target specific fields when raising ValidationError.
Description
The goal would be to unlock the following API:
def clean(self): errors = {} if condition1: errors['field1'] = ValidationError('message1', code='code') if condition2: errors['field2'] = ValidationError('message2', code='code') raise ValidationError(errors)
Most of the groundwork has been done for #20199.
We would need to document passing a
dict to
ValidationError, just like we already document passing a
list in ref/forms/validation/#raising-validationerror.
This would probably deprecate or reduce the need for the pattern discussed in ref/forms/validation/#form-subclasses-and-modifying-field-errors.
Change History (12)
comment:1 Changed 7 years ago by
comment:2 Changed 7 years ago by
comment:3 Changed 7 years ago by
comment:4 Changed 7 years ago by
Quite simultaneously yet in different contexts @mjtamlyn and @akaariai had the idea of having a
Form method to manipulate the
_error dict.
@akaariai on IRC:
(07:56:59 AM) akaariai: I am reading and wondering why this must be so complicated? Why not Form.add_error(field, message)? (07:59:26 AM) jtiai: akaariai: Maybe because no one bothered to figure out API for that? (07:59:53 AM) timograham: akaariai: WIP by loic84 is (08:04:04 AM) akaariai: timograham: hmmh, seems to me that having self.add_error instead of documenting self._errors would be an improvement even if ValidationError(errors_dict) went in. (08:05:19 AM) akaariai: there are some cases where you want to add errors post-clean, and just getting rid of that self._errors docs seems nice. (08:06:08 AM) akaariai: compare that to add_error(field, error_message): Adds an error to specified field. If field is None, then adds a non_field_error.
@mjtamlyn talking about a private utility method that I used in the PR above:
[...] It could even be made public - so this is a shortcut for the old way of doing things, with the clever ValidationError exceptions being a further improvement.
As a result I've cleaned up my utility method and replaced it with
Form.add_errors(self, field, errors).
Now the question is what do we do in term of public API, the current patch documents raising
ValidationError with a dictionary argument. We could also document
add_errors(), or we could only document
add_errors().
One good thing in having a public
add_errors() is that it would be accessible from outside the form. Many time I wished I could add some errors to a form instance from a view without having to fiddle with
_errors.
comment:5 Changed 7 years ago by
This got me wondering a bit, is there any need for
ValidationError to support dictionaries if we have
add_errors? The original aim was to make
clean() methods nicer when affecting multiple fields.
comment:6 Changed 7 years ago by
We need good support for dict because that's how errors travel from the
Model layer to the
Form layer. Also
ValidationError is the vehicle to carry metadata like error code and error params which are lost as soon as they reach
ErrorDict. That said, we don't need to advertise it.
comment:7 Changed 7 years ago by
Yup, of course. I think it's worth documenting both personally.
comment:8 Changed 7 years ago by
Any resolution to this will now also include the
add_errors() functionality, which fixes #5335. I've closed that ticket as its topic has been subsumed into this one.
[edited not->now]
comment:9 Changed 7 years ago by
comment:10 Changed 7 years ago by
I went with the
add_error(field, error) API (note the singular) which seems to be the most popular from the feedback I've received on IRC and on the ML thread.
PR | https://code.djangoproject.com/ticket/20867?cversion=1&cnum_hist=8 | CC-MAIN-2020-29 | refinedweb | 637 | 54.32 |
In this blog, we are going to set up a typical CI/CD pipeline using concourse to make the development process more agile and deployment more visible.
The concourse is an open-source continuous thing-doer.
Built on the simple mechanics of resources, tasks, and jobs, Concourse presents a general approach to automation that makes it great for CI/CD.
Quick Start Concourse CI
There are many ways to setup concourse but in this blog, we are going to use the easiest way to setup concourse that is using docker-compose.
Download the docker-compose file
It contains a concourse server and PostgreSQL database for concourse backend.
wget
Run that docker-compose file
docker-compose up -d
The concourse will be running at localhost:8080. You can log in with the username/password as a test/test.
fly CLI command-line tool
fly CLI is a command-line tool that you need to use to set up and manage pipelines on Concourse. We need to install fly CLI by downloading it from the web UI (localhost:8080). You can see in the above welcome page to download the CLI for windows, mac, and Linux.
After download the CLI tool we need to give execute permission to that and copy to the /usr/bin/
chmod +x fly
sudo cp fly /usr/bin/
Next, set target your local Concourse as the test user:
fly -t tutorial login -c -u test -p test
Now you have successfully setup concourse on your local machine, let’s move to the CI/CD part.
Concourse Pipeline Directory structure
Concourse recomended directory structure.
Set up CI/CD
In this practical, we are going to deploy a spring boot application to the Kubernetes, Lets Start.
Clone the below repository
git clone
Go the to project root directory
cd concourse-ci-cd
Create a pipeline using a fly tool
Note: Before creating the pipeline we need to update the config.yml file to provide the docker and Kubernetes credentials.
Run the below command
fly -t tutorial set-pipeline -p spring-boot-service -c concourse_ci/pipeline.yml -l concourse_ci/config.yml
The pipeline is configured now, and you can see that in the concourse UI.
When you create a new pipeline by default it is paused, so we need to unpause the pipeline, Run the below command to unpause the pipeline
fly -t tutorial unpause-pipeline -p spring-boot-service
Now, you have successfully created a CI/CD pipeline to the kubernetes.
Lets Understand pipeline.yml file
resource_types: - name: kubectl-resource type: docker-image source: repository: jmkarthik/concourse-kubectl-resource tag: latest resources: - name: spring-boot-service type: git source: uri: branch: master - name: spring-boot-service-docker-repository type: docker-image source: email: ((docker-hub-email)) username: ((docker-hub-username)) password: ((docker-hub-password)) repository: ((docker-hub-username))/((docker-hub-repo-name)) - name: kubectl type: kubectl-resource source: api_server_uri: ((server)) namespace: ((namespace)) certificate_authority_data: ((cad)) token: ((token)) jobs: - name: test public: true plan: - get: spring-boot-service trigger: true - task: mvn-test file: "spring-boot-service/concourse_ci/tasks/maven-test.yml" - name: package public: true serial: true plan: - get: spring-boot-service trigger: true passed: [test] - task: mvn-package file: "spring-boot-service/concourse_ci/tasks/maven-package.yml" - put: spring-boot-service-docker-repository params: build: spring-boot-service-out - name: deploy public: true serial: true plan: - get: spring-boot-service trigger: false passed: [package] - put: kubectl params: file: "spring-boot-service/spring-boot-deploy.yaml"
In the above CI/CD pipeline, we are seeing the following components:
- Resource Type
Each resource in a pipeline has a type. The resource’s type determines what versions are detected, the bits that are fetched when the resource’s get step runs, and the side effect that occurs when the resource’s put step runs.
An exhaustive list of all resource types is available in the Resource Types catalog.
- Resource
Resources are the heart and soul of Concourse. They represent all external inputs to and outputs of jobs in the pipeline.
- Job
Jobs determine the actions of your pipeline. They determine how resources progress through it, and how the pipeline is visualized.
The most important attribute of a job is its build plan, configured as a job.plan. This determines the sequence of steps to execute in any builds of the job.
- Task
The smallest configurable unit in a Concourse pipeline is a single task. A task can be thought of as a function from task.inputs to task.outputs that can either succeed or fail.
Resources: | https://blog.knoldus.com/concourse-ci-cd-pipeline/ | CC-MAIN-2021-04 | refinedweb | 754 | 53.1 |
C++ Getting Started).
C++ Install IDE
An IDE (Integrated Development Environment) is used to edit AND compile the code.
Popular IDE's include Code::Blocks, Eclipse, and Visual Studio. These are all free, and they can be used to both edit and debug C++ code.
Note: Web-based IDE's can work as well, but functionality is limited.
We will use Code::Blocks in our tutorial, which we believe is a good place to start.
You can find the latest version of Codeblocks at.
Download the
mingw-setup.exe file, which will install the text editor with
a compiler.
C++ Quickstart
Let's create our first C++ file.
Open Codeblocks and go to File > New > Empty File.
Write the following C++ code and save the file as
myfirstprogram.cpp (File > Save File as):
myfirstprogram.cpp
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
Don't worry if you don't understand the code above - we will discuss it in detail in later chapters. For now, focus on how to run the code.
In Codeblocks, it should look like this:
Then, go to Build > Build and Run to run (execute) the program. The result will look something to this:
Hello World!
Process returned 0 (0x0) execution time : 0.011 s
Press any key to continue.
Congratulations! You have now written and executed your first C++ program.
Learning C++ At W3Schools
When learning C++ at W3Schools.com, you can use our "Run Example" tool, which shows both the code and the result. This will make it easier for you to understand every part as we move forward:
myfirstprogram.cpp
Code:
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
Result:
Hello World! | https://www.w3schools.com/cpp/cpp_getstarted.asp | CC-MAIN-2020-40 | refinedweb | 283 | 77.94 |
Learn how to add a new action to an ASP.NET MVC controller. Learn about the requirements for a method to be an action.
The goal of this tutorial is to explain how you can create a new controller action. You learn about the requirements of an action method. You also learn how to prevent a method from being exposed as an action.
Adding an Action to a Controller
You add a new action to a controller by adding a new method to the controller. For example, the controller in Listing 1 contains an action named Index() and an action named SayHello(). Both methods are exposed as actions.
Listing 1 - Controllers\HomeController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcApplication1.Controllers { [HandleError] public class HomeController : Controller { public ActionResult Index() { return View(); } public string SayHello() { return "Hello!"; } } }
In order to be exposed to the universe as an action, a method must meet certain requirements:
- The method must be public.
- The method cannot be a static method.
- The method cannot be an extension method.
- The method cannot be a constructor, getter, or setter.
- The method cannot have open generic types.
- The method is not a method of the controller base class.
- The method cannot contain ref or out parameters.
Notice that there are no restrictions on the return type of a controller action. A controller action can return a string, a DateTime, an instance of the Random class, or void. The ASP.NET MVC framework will convert any return type that is not an action result into a string and render the string to the browser.
When you add any method that does not violate these requirements to a controller, the method is exposed as a controller action. Be careful here. A controller action can be invoked by anyone connected to the Internet. Do not, for example, create a DeleteMyWebsite() controller action.
Preventing a Public Method from Being Invoked
If you need to create a public method in a controller class and you don’t want to expose the method as a controller action then you can prevent the method from being invoked by using the [NonAction] attribute. For example, the controller in Listing 2 contains a public method named CompanySecrets() that is decorated with the [NonAction] attribute.
Listing 2 - Controllers\WorkController.cs
using System.Web.Mvc; namespace MvcApplication1.Controllers { public class WorkController : Controller { [NonAction] public string CompanySecrets() { return "This information is secret."; } } }
If you attempt to invoke the CompanySecrets() controller action by typing /Work/CompanySecrets into the address bar of your browser then you’ll get the error message in Figure 1.
Figure 01: Invoking a NonAction method(Click to view full-size image)
This article was originally created on March 2, 2009 | http://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/creating-an-action-cs | CC-MAIN-2014-52 | refinedweb | 463 | 59.7 |
IntroductionXML (eXtensible Markup Language) came into existence after several years of HTTP/HTML revolution. If I brief few important features of XML,. Defining a web service is a difficult task. But in brief we can define web service as application logic that is accessible using Internet standards. Or this is a secure and reliable service provided over the internet or intranet. The extension for asp.net web service file is .asmx.WSDL (Web Services Description Language)WSDL can be defined as a language (document) which describes a web service. Hence one more definition of the web service can be given as anything a Web Services Description Language (WSDL) document can describe. The Web Services Description Language tool (WSDL.exe) generates code for XML Web services and XML Web service clients from WSDL contract files, XSD schemas, and .discomap discovery documents. Open Visual studio.Net command prompt and type WSDL /? To get list of options available with this tool.Below command generates .wsdl file for a web service located in specified URL. Wsdl major features in .NET are its ability to create XML Web Services Servers and XML Web Services Clients. There are also several related APIs (application programming interfaces) available for manipulating DISCO (Web Services Discovery Language) and WSDL (Web Services Description Language) documents.The engine that drives most of these features is XML Serialization. This API, found within the System.Xml.Serialization namespace, provides the ability to read and write XML without a DOM (Document Object Model) class or an XML-based stream reader. Instead, classes can be mapped to schema-based XML using a default set of rules, plus a variety of optional attributes to customize this serialization. DISCO (Universal Description, Discovery, and Integration): This is a platform independent framework which acts like dictionary of the web services and helps to locate web services on the internet. This also provides description for the web service that we are searching for. ProxyFor XML Web service clients, the proxy class handles the work of mapping parameters to XML elements and then sending the SOAP message over the network (to and fro). By default, the proxy class uses SOAP over HTTP to communicate with the XML Web service. But this can be changed by using WSDL.exe to use either the HTTP-GET protocol or HTTP-POST protocol.Let's create a Web Service and consume it by the client application. This service returns Maximum of the two numbers sent. Create a Service
Create a proxyOpen Visual Studio.Net command prompt and move to the service folder and type below command.WSDL This will generate a class file with ArithmeticService.cs name. This is a proxy class for the web service. Create an assembly for the proxy class. Consume Service by Client applicationCreate Visual Studio .Net windows application and reference proxy assembly created and call the service to get the result.
Ram... Read more
©2015
C# Corner. All contents are copyright of their authors. | http://www.c-sharpcorner.com/UploadFile/rupadhyaya/BuildingASPWebServices11232005231631PM/BuildingASPWebServices.aspx | CC-MAIN-2015-06 | refinedweb | 493 | 59.8 |
I have a list view which is populated via records from the database. Now i have to make some records visible but unavailable for selection, how can i achieve that?
here’s my code
public class SomeClass extends ListActivity { private static List<String> products; private DataHelper dh; public void onCreate(Bundle savedInstanceState) { dh = new DataHelper(this); products = dh.GetMyProducts(); /* Returns a List<String>*/ super.onCreate(savedInstanceState); setListAdapter(new ArrayAdapter<String>(this, R.layout.myproducts, products)); ListView lv = getListView(); lv.setTextFilterEnabled(true); lv.setOnItemClickListener( new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub Toast.makeText(getApplicationContext(), ((TextView) arg1).getText(), Toast.LENGTH_SHORT).show(); } }); } }
The layout file myproducts.xml is as follows:
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns: </TextView>
How can I disable the OnItemClick() in a List of items in Android?
How can I disable the OnItemClick() once a List item has been clicked? I am trying to display a list of items in a grid view. Once the user clicks on one item, it must not be possible for him to click
disable list items in ListView
I wanna disable all list items in a ListView excluding the 1st position item. That means every time the 1st item can be clicked not the all. How can I do this. Is there any way. Give me some sample co
Android: How to disable list items on list creation
I’m pretty new to Android dev and still working out a lot of things. I’ve got a main menu showing using the following code, but can’t work out how to disable selected items in the menu. Can anybody he
How to disable indentation of LaTeX list items? [closed]
By default the enumerate environment is indented with respect to the current environment. How can I disable this indentation so that an enumerate environment of three items would produce the same ou
how to check the list view items when we are using groups in list view
how to check the list view items when we are using list view group s… I have list view in that i am using two groups …. If i click on the list view first group item then click on the list view sec
In List view how many list items can load in android
Normally in ListView are used in android,but how many items can totally load in list view ? Is it possible to load more than 10,000 items ?
How to disable the particular list item in list-view in android?
How to disable the particular list item in list-view in android? I mean if once i selected any one of item from a list-view,that item suppose to be disabled which means that item should not be select-
disabling and greying out list items
I have a list view. In that list view, I have to grey out and disable some items, and enable the rest list items with seperate color. How to do this?
How to disable onitem click in list view paricular row in android
How to disable list view on item click in particular row in android.if value is search i have to disable the onitem click event of particular row in list view in android can anybody tell how to do? Th
Disabling items in the list view
I have a requirement wherein I want to disable items in the list view. Say e.g., I have 5 items in the listview out of which I want to only enable 1 item. Note: disabling means greying out the item. F
Answers
Make your own subclass of ArrayAdapter that has AreAllItemsEnabled() return false, and define isEnabled(int position) to return true/false for a given item in your data set. | http://w3cgeek.com/how-to-disable-items-in-a-list-view.html | CC-MAIN-2019-04 | refinedweb | 636 | 71.65 |
Templating languages, and YAPTL?
I like the idea of push_pull; it gives people used to pull templating systems a place to start.
FWIW, I consider ElementTree the badass DOM replacement API rather than anything built on top of it. I'm not real crazy about the idea of hiding the ElementTree API from people; it's very well-documented, and very simple. That's why for meld3 I chose to expose and extend the ElementTree _ElementInterface API for nodes rather than creating another entirely different one (or sticking to the PyMeld API). While this won't let you use "old" PyMeld templates, that wasn't a goal of mine (and it appears neither for meld4 as it has some slight API differences).
Certainly the intent of meld3 wasn't to just "create YAPTL", although any templating language written in Python is just that. It's also not a ZPT clone or anything. The only thing ZPT-like about meld3 is its use of the names "content", "repeat", "replace", and "structure". This was a nod to my Zopish background and for the tasks that really do need to be done when doing web templating. It has nothing else whatsoever to do with ZPT. It has the same goals as PyMeld and your meld4.
meld3, does support the full API functionality of PyMeld. The main differences:
- getattr on nodes isn't tasked with searching for
elements with meld ids (that's .findmeld() in
meld3).
- You can get at __mod__ functionality via fillmelds() instead
- Instead of using __setitem__ to set an attribute value, you use either the ElementTree API (node.attrib['k'] = 'v') or the meld3 'attributes' method (node.attributes(**kw)).
There just isn't a lot to the PyMeld API, so supporting all of its features was pretty simple (ElementTree already had them all; I just took the tact of exposing them).
meld3 also lets you do some web page templating a bit more easily that are a bit harder to do in PyMeld: repeating elements using an iterator, diffing structure of meld templates.
If the audience for meld4 is templating people, I'll also note that you'll want to try to use your templates in WYSIWYG editors before you lead other people to beleieve they'll work well in those editors... a lot of WYSIWYG editors don't seem to deal well with XML/XHTML templates and break them badly in bizarre ways (NVU comes to mind). Lots of browsers also have major problems dealing with namespace output. This is why meld3 has an HTML parser and serializer, and an XHTML serializer that strips out namespace output. meld3 also attempts to explicitly allow for "pipelineing" where you can output a serialized version of a tree with the ids intact for later processing (maybe by XSL or another meld system).
There is the equivalent of your fill() in the z3meld bindings for Zope3 (see plope.com).
It would be great to try to collaborate on this stuff if we could find some common ground.
Of course, I'd love to collaborate. Maybe I missed it, but does meld3 have a way to get the parent node of a given meld? Or an equivalent to ._content?
Yes. Every meld3 node has a 'parent' attribute, and this attribute is maintained as you move nodes around via the elementtree/meld3 API. You can delete a node from its parent by calling 'node.deparent()'.
The closest equivalent to viewing the equivalent of PyMeld's ._content is to call 'node.shortrepr()'.
The equivalent to the concept of assigning to ._content is done via "node.content('some stuff')". If the content is another node as opposed to text, you need to do a multiline thing which deletes the children of the node andthe nodes. This could be made easier if meld3 allowed its "content" method to accept another node too instead of only allowing text (which is simple and is probably a good idea). The 'content' method accepts an optional second argument named 'structure' which if it's true will turn off HTML escaping of the text passed in, which allows you to do things like:
node.replace('some suff', structure=True)
Replacing a node is done via "node.replace('some stuff')". This also accepts the structure flag and could also accept a node instead of text (it doesn't now).
"You can also use the elementtree API against all nodes, and do node.text = 'foo' or node._children = [] to clear all child nodes, node.find('bar') to find the first bar node beneath this node, and so on.
Anyway, it'd be great if you could take a closer look at meld3 and see what you don't like about it; it can obviously be changed to make things easier as necessary.
Doh... the above blockquote demonstrating structure should have tags around the "some stuff" (implying that what you pass in is html).
A good comparison is to the View and Controller layers in Apple-style MVC.
In Apple MVC, the View layer consists solely of graphical widget objects, assembled live and stored in serialized form (.nib) using Interface Builder, and the Controller layer contains the glue code that pulls data from the Model layer and inserts it into the View objects.
With DOM-style templating engines, the tagged HTML file is analogous to the .nib file, the templating engine the AppKit framework that turns this data back into live objects, and the Python code that manipulates these objects the Controller layer.
Incidentally, I do think there's something to be said for stuff like automatic interpolation of dictionary values or instance variables to reduce the amount of tedious glue code developers need to write in common situations (c.f. Cocoa Bindings). Though I'd suggest you allow for that by ensuring your basic API is sufficiently open and flexible (i.e. supports introspection) that such functionality can be built on top of it, rather than trying to include such convenience features in the core engine. Otherwise you'll end up in the same bind as the traditional macro-style engines of endless feature creep and API complexity as it tries to be all things to all men.
I am thinking about starting a blog on my hobbie. I have been collecting flags for many years and have a lot of great information. At first, I was going to start a website, but that looked to hard. Your blog helped. Thanks.
Hey
peter Hunt's ur personal blog is quite interesting.
Data entry
I do not like ElementTree. You can't even search for nodes based on element attributes. The Perl module of similar functionality, HTML::TreeBuilder, has had such functionality forever. | http://www.aminus.org/blogs/index.php/2006/01/27/templating_languages_and_yaptl%3Fblog=15 | crawl-002 | refinedweb | 1,116 | 71.24 |
Sun's Phipps Slams App Engine's Java Support 186
narramissic writes "Sun Microsystems' chief open source officer, Simon Phipps, said in an April 11 blog post that Google committed a major transgression by only including support for a subset of Java classes in its App Engine development platform. 'Whether you agree with Sun policing it or not, Java compatibility has served us all very well for over a decade,' Phipps wrote. characterized his remarks as non-official, saying: 'This isn't something I could comment on on Sun's behalf. My personal comments come purely from my long association with Java topics.'"
Pot. Kettle. Black. (Score:5, Insightful)
You mean like Java ME [wikipedia.org]?
Re: (Score:2)
The real problem is that Google created their own version of Java ME. Instead of sticking with the existing standard, they came up with their own. And that's bad for everyone.
Re:Pot. Kettle. Black. (Score:5, Insightful)
Since AppEngine, Google's cloud platform is (while, like mobile devices, a different environment from the standard desktop or server environment for which the Java Standard Library is designed) not a mobile platform, and doesn't have the same constraints that shape the development of Java ME, it's not surprising that they did something different.
OTOH, the justification is the same for having Java ME when Java SE already exists: the environment in which AppEngine Java is being used is very different from that for which SE was conceived, putting unique constraints on it.
I think that Phipps is upset because Sun is in the process of gearing up their own cloud services, and the last thing they want is Google's Java support drawing enterprise interest to AppEngine while they try to get Sun's cloud service off the ground.:Pot. Kettle. Black. (Score:5, Insightful)
I really don't think that Java developers have much trouble understanding or using a clearly defined subset of existing functionality.
What Microsoft did was create an incompatible implementation of core Java classes, supporting similar features but requiring different behavior with the same classes. This has much more serious negative impact than implementing a well-defined subset, since the former makes it hard to move code either way between implementations, and the latter (what Google is doing) makes it very easy to move code off the non-standard implementation (AppEngine) and onto a standard implementation, but somewhat challenging to move code using the unsupported features from the standard implementation onto the non-standard one.
It's actually a really bad thing to do if you want to create lock-in to your non-standard implementation, since it does nothing to keep people from moving off your platform, but makes it harder than supporting the standard would for them to move on to your platform.
Re: (Score:3, Interesting)
Re:Pot. Kettle. Black. (Score:5, Informative)
Yes they did; Sun took them to court. Specifically, they left out JNI and RMI in favour of their own COM object APIs.
Proof? Microsoft's own document [microsoft.com] reveals this.
Re: : (Score:3, Insightful)
Free or not, at some point you MUST have a standard, or you will not have interoperability. What Google is doing here is no different than what Microsoft has done for years.
Now I'm not saying Java ME is good. In fact, it's awful. But an awful standard is still better than none.: (Score:2)
It would be extremely trivial to convert something written for Microsoft's broken standards too.
The point is that as a developer, that just means more wasted time on something that's out of my control.
Re: (Score:3, Insightful)
The point is actually this: If I (or someone else) write a program in GoogleJava (or whatever you want to call it) and said program runs, I can take that same source and compile it under Java standard edition, with no refactoring, and it will run exactly the same (AFAIK). Try doing that with MS Java (no refactoring allowed!).
"Flout", not "flaunt" (Score:4, Funny)
Grr.
Re: (Score:2)'.
No, I got it right, and you have no sense of humor.. He's flaunting his (Sun's) rules, making poor google feel bad about itself. It's an alternate explanation of the meaning of that sentence, with the assumption that the guy typed exactly what he meant.
"Wonton", not "wanton" (Score:3, Funny)
I think Sun is jealous (Score:5, Interesting)
Re: (Score:3, Interesting)
Re: (Score:2).
Re:Mountain: (Score:3, Insightful)
That would be their locked-down sandbox. You can accomplish the same thing in vanilla Java with a security manager. (Which for all we know, they did. I haven't tried yet.) If the security manager doesn't allow it, you're not using it. Period, end of story.
You may note that everything Google has locked down is either controlled by the security manager or is simply an API to access a service that they don't provide.
Generally speaking, it's a good
Re: (Score:2)
You can accomplish the same thing in vanilla Java with a security manager. (Which for all we know, they did. I haven't tried yet.) If the security manager doesn't allow it, you're not using it. Period, end of story.
I'd really like to know if this is the case. Everything I've read in the list seems to me to be something a security manager could potentially block anyways. I'd like to know if they're throwing a SecurityException in these situations or not.
Re: (Score:2)
Speaking of your sig - the collection that you link to is seriously outdated (2004? c'mon, that's even before
.NET 2.0). A lot of points on it simply don't apply anymore.
Re: (Score:2)
Ummm, even Sun says you should not be launching threads inside of JEE containers. Or writing to the file system for that matter. In fact, most of Google's restrictions are identical to Sun's own restrictions for JEE, the only difference is, Sun didn't make it mandatory, and now they're complaining that Google are (because they have to actually host these things in a sane and manageable way).
The only thing that really irks me is no socket connections. Making HTTP the only avenue for network I/O, and even
Re:Mountain out of Molehill (Score:4, Insightful)
Following
/. tradition, I have not looked at the details, but that won't stop me from commenting here... :)
As someone who has been writing Java since '99, I have to say if even Threads is not supported, it is a big issue.
There is a reason why the Core class are called "Core", every Java library expects the Core classes are there. If we now have a popular Java platform that only have a subset of the Core classes, it will cause a lot of headaches down the road, eventually fragmenting the "Java" platform.
Re: (Score:2)
Um... no. They're not supporting Threads for a start - which is pretty major.
A major improvement. It's now accepted on concurrency wonks (including, no especially, the ones at Sun and Google) that Threads is a disaster. Sun itself would much prefer that everybody switch to the new Concurrency classes [sun.com], which are not only much more reliable, but a lot easier to use.
... and seems to use threads.
Re: (Score:2)
It uses Thread objects. Not quite the same thing. If Thread is no longer a public class, then the various bad idioms that the Thread API. encourages are no longer possible.
Re:
Re: n
Re: (Score:2)
You're confusing threads (in the generic sense) with Threads (the Java data type). You can't have multithreading without threads (duh!) but you can easily dispense with Threads as part of the official API.
I'm no expert on this technology, but I do know a lot about the motivations behind the Concurrency classes. That's because I spent 2006 helping to update the Java Tutorial, and spent a lot of time getting indoctrinated by the key people involved in this stuff, including Doug Lea.
Re: (Score:2)
Hmm, I did forget about Thread objects being part of the language. But that doesn't mean they have to be part of the public API. You just fiddle with the package declarations so that programmers can't declare or instantiate Thread objects. The Thread objects still exist, but they're only accessible via the Concurrency classes.
Except this is all getting a little weird. I suspect that the real status of Thread (and the other classes missing from the "White List") is "deprecated" rather than "deleted". So you
Re: (Score:2)
The problem you're referring to is a well-known limitation of the java platform with a planned solution. The problem is that it's been stalled and hasn't made it past the JSR stage despite being first reviewed in 2001.
See either: Project Barcelona [sun.com] or the Java Isolates [jcp.org] JSR.
That combined with the Java Resource Consumption Management [jcp.org] AP
What about changing Java's license? (Score:3, Interesting)
I realize it's now too late but if it were a few years ago, SUN should have considered changing Java's license to make sure that whoever supports Java, supports it in its entirety.
Re: (Score:2)
Re: (Score:3, Interesting)
Google isn't calling their product Java. Google's product is called AppEngine. Google is free to say that AppEngine has "Java(TM) Language Support" without getting permission from Sun or anyone else.
Trademark isn't an absolute monopoly on the mark.
Re: (Score:2)
They did that for many years.
As I understand it sun was pulled between two conflicting forces. On the one hand with MS pushing
.net they wanted java to be a first class citizen on linux. Otoh they wanted to keep control over java.
Being a first class citizen on linux basically requires being FOSS. If not your package will most likely be either excluded altogether or shunted off to some "non-free" repositry which is not enabled by default and likely has lower standards of maintinance.
After much dithering a co.
Re: (Score:3, Insightful)
Exactly. I can't help thinking that Java might have been a lot more pervasive and standardised by now (not to mention that the CLR probably wouldn't exist) if Sun had been more open with Java licensing years ago.
Re: (Score:3, Interesting)
Heh. I had to write an IoC container that would run on CLDC 1.1. Fun fun fun. No Serializable meant I had to re-compile all my code. Love that fragile base-class problem.
Re: (Score:2)
Was going to post about how J2ME does exactly what they complain about: "Creating subsets of the core classes in the Java platform was forbidden", well, Sun itself did it and let me tell you, it makes Java's already convoluted API a nightmare to work with, and is ridiculous when programming on a device such as a Blackberry.
RIM had to provide alternatives to some useful Java classes that are just not present in J2ME, turning Blackberry development into an incompatible and horrendous mess, negating all the be
Flout not Flaunt (Score:5, Funny)
Java compatibility has served us all very well for (Score:3, Funny)
Sauce for the goose... (Score:2)
Re: (Score:3, Interesting)
We'd be worried about Microsoft attempting to create an MS-only ghetto that they lock people into
Like
.NET?
For most parts,
/. seems to be pretty much ignoring what msft is doing these days, as far as server technologies are concerned.
Uh, we did scream (Score:3, Informative)
Re: (Score:2, Insightful),
AP Java Subset? (Score:2, Insightful)
why didn't they complain about GWT? (Score:3, Interesting)
Hmm...I wonder why they never complained about the limited subset of classes that GWT supports [google.com] in client-side code.
Re: (Score:2, Insightful)
Hmm...I wonder why they never complained about the limited subset of classes that GWT supports [google.com] in client-side code.
Because they never said that GWT supports "Java", they said it implements some JRE classes. And like everyone says, Sun is a sore loser for failing to release a usable cloud-computing project.,
yes well, who cares really (Score:2)
there fixed that for you.
Everything you need is there (Score:3, Insightful)
OK, no Swing, no Corba etc. But I cannot see what part is missing for cloud computing (or any other algorithm. The collections classes (even the thread safe ones), all cryptographic stuff etc. The only thing that really seems to be missing is graphics (images). But for most cloud computing needs, this should be sufficient.
Anything else you may be able to import using the classes from the open source JDK anyway. As long as you don't create files etc. of course, thanks to the sandbox. And we're not talking about a release of another JDK or anything like that, in that case it would be a problem not to include the default functionality.
This seems to be a bit of a cheap shot. He should well know that you cannot display any personal opinions that are directly in his line of work, and then claim that they are not the opinions of his employer. Not in his position.
HOWTO: Using a SUBSET to create LOCK-IN!!! (Score:4, Insightful)
Re: (Score:2, Interesting)
Your theory falls flat when you hit point #2
The following packages do not exist.
google.io.*
google.threads.*
google.db.*
google.util.*
If, in the future, google does add those libraries, I would fully expect them to be opensourced.
Re: (Score:3, Insightful)
Your theory falls flat when you hit point #2
The following packages do not exist. google.io.*
google.threads.*
google.db.*
google.util.*
If, in the future, google does add those libraries, I would fully expect them to be opensourced.
I can see how you misunderstood the posting. Please, let me help you.
I will do this in two parts:
[PART-1]
I am sure that you only missed the that I used "e.g." ( what is an e.g.? [about.com]) in the above, otherwise you would not have made the mistake of thinking that it could have been referring to anything else other than an example being posited for the discussion.
Those names were examples... hypothetical, if you will.
Now that that is all cleared up, give the post a re-read... but only after reading PART-
Sun folks often have no clue about Java (Score:2, Insightful)
Google's response... (Score:2)
Re:do their own then... (Score:4, Funny)
bahahahaha. Sun? Money?
You've not been here long, eh?
:)
Re: (Score:3, Insightful)
...
Re:do their own then... (Score:5, Insightful)
If you want lock-in, you create a superset of the competitor's platform, or a variant of the platform that behaves differently, then push people to use your proprietary features. Implementing a subset of the competitor's platform just raises the cost of porting to your implementation, and creates no barrier to moving from your implementation to others' implementations.
The java-subset thing seems like a bad idea; and I'd be curious to know why they did it; but I don't see how a platform subset is a good basis for a lock-in strategy.
Re:do their own then... (Score:5, Informative) [google.com]
So I would say the reasons behind their decision would boil down to "cutting out the stuff that isn't compatible with the model the App Engine uses to run things".
Re: (Score:2)
Sounds like they should have specified a security model that would forbid certain classes and method rather than simply removing classes. Or was that too hard for Google's engineers? As a developer, would you rather have you application fail to run, or throw a completely bizzare ClassNotFoundException: java.lang.System, or run but throw an informative SecurityException when it tried to call System.exit()?
Re:
Re:do their own then... (Score:5, Insightful)
Well sure, If you're re-using a standard library it may have handling for the security exception chain and either fail gracefully or work with limited functionality.
If a JDK class is missing and the library class you want to use references it the code won't even run with an UnsatisfiedLinkError. That is a HUGE difference.
Another case where the library class references a missing JDK class but the use of the library class you're using never touches the forbidden code. In that case you again get a UnsatisfiedLinkError. If the use of the JDK class was just restricted by a security policy you only get the security exception if you actually call the API, a much better alternative.
Re: (Score:2)
So it seems like you're saying that what Google did is better than what the guy from Sun thinks they should have done. Because it's *always* better to get a compile-time error than a run-time error.
Re: (Score:3, Insightful)
Imagine that you use some 3rd party library that includes code for caching to disk. Since you know you can't write to disk on the AppEngine, you disable caching in the configuration. But the UnsatisfiedLinkError is still there.: (Score:2)
Re: (Score:2) [google.com]
And given the SDK they point you to is Sun's and this is Google, how unlikely is it that the things being complained about are actually being managed by a security manager and not actually missing. I.E. Communication error.
Re: (Score:3, Insightful)
I'm not sure what you mean. The complaints seem to indicate that you'll get things such as "NoClassDefFoundError" and the like, rather than the more appropriate "SecurityException". As to which one actually happens, I don't know. The point is that a developer, developing an application for Java, should not have to concern himself whatsoever with NoClassDefFoundErrors when interacting with standard jvm classes. He SHOULD however, be concerned with potentially encountering SecurityExceptions.
My point w
Re: (Score:2)
Agreed, And not being a Java developer I have no way of knowing the truth of whether Google did it the 'right' way or not other than asking. However, the only complainer I've actually seen is someone from Sun, a company who has a vested interest in making whatever Google did look bad and not a stellar rep with me for saying things 100% on the up and up all the time.
Additionally, I don't see anywhere in the 'official' statements indicating that Google actually removed anything in the breaking sense. Google's
Re:do their own then... (Score:5, Informative)
The Right Way:
Google's way::4, Insightful)
I like that better than The Sun Way:
Re: (Score:2)
Yeah I'm surprised they didn't do this. Everything they describe is doable via a security policy configuration file and a single custom ClassLoader implementation.
Re: : (Score:2)
Then subclass for f***'* sake
Re:do their own then... (Score:5, Insightful)
Re: (Score:2)
This article writer is a tool. Interestingly enough, most of these restrictions (no filesystem access, no sockets, no spawning threads) are EXACTLY the same restrictions as recommended by Sun for EJB: [sun.com]
Re:do their own then... (Score:5, Interesting)
It's not the restrictions, it's the implementation. Normally, existing Java code could just be compiled on the embedded system, and compiler errors would specifically identify security reasons for specific classes/methods/etc being disabled. Google removed the classes entirely, so the developer will just get IDontKnowWTFThatClassIs exceptions instead, which are less informative.
It also contravenes existing standards, sort of like making "dangerous" files invisible to unprivileged users in *NIX (via some sort of arcane black magic, perhaps a modified (munged) shell or something...) instead of just setting appropriate file permissions.
Re: (Score:2):do their own then... (Score:5, Insightful)
While I agree that google is not Mr. Friendly, I'd be surprised if this particular move is about lock-in.
It never is. Whenever somebody modifies standard technology to suit themselves, they get accused of trying to create lockin. That's what happened when Phil Katz [wikipedia.org] decided he could redo the ARC format faster and smaller. That's what happened when Anders Hejlsberg [wikipedia.org] decided he couldn't live with Java's limitations [zdnet.com]. Netscape and HTML. Microsoft and HTML, CP/M, x86....
Lockin does usually occur when people do things in a different way, and the different way ends up being the de facto standard. But that's not why they do them. They do them because developers just plain like to do things their own way.
In the case of Google's "white list" this doesn't even come close to being lockin, because any application that will run on Google's classes will run on "standard Java". Sun's problem is that the reverse isn't true. And I'm not sure that really matters. Unless I've missed something, the missing classes are all legacy cruft that should have been deleted from Java long ago.
So why haven't they been? Lack of will. One Java core engineer told me that Sun got in trouble when they even deprecated an API, never mind removing a whole class. People just don't want to fix up all their legacy code, and Sun was too anxious to monetize Java to stand up to them.
Google has more flexibility, since they don't need for their version of the Java platform to make money anytime soon.
Re: (Score:3, Interesting)
Sun's problem is that they are working up to the general launch of their cloud computing services, and Google AppEngine supporting more than just Python makes it that much harder for any new launch to get traction.
Re: (Score:2)
Please. Not every shoot-from-the-lip blog entry is part of a FUD campaign.
Re: (Score:2)
I, too, eagerly await the deprecation of java.lang.Thread, and the loss of the ability to open sockets and write directly to the filesystem. Who needs that cruft?!
In all seriousness, the missing functionality isn't about trimming cruft, it's about sandboxing so that apps can readily be hosted in google's "cloud", and play nice with other apps.
Legacy code? Like FORTRAN? (Score:2)
I think I can speak a bit about legacy code. Where I work there are some old apps written in FORTRAN-77. Yes, I know the current name of that language isn't written all-caps anymore, but that's the whole point: the code is still all-caps, it was written in 1977 and never rewritten since then.
There's a bunch of old engineers who aren't old enough to retire who insist on keeping tha
Re: (Score:2)
Most of what's wrong with FORTAN got designed in 50 years ago. Plus they're mostly part of the fundamentals of the language. Maintaining compilers that handle ancient FORTRAN design mistakes (FORTRAN was the very first high-level language, and taught all subsequent language designers a lot about how not to go about it) is one thing. Removing a class from Java is quite another. It's completely different from changing a language feature, which Sun is very very conservative about doing.
(Once had a coworker wit
Re: (Score:2)
What, like Microsoft did when it reinvented Java for IE? Do you really want a 3rd version of Java that's not quite compatible with regular Java (counting gcj as the 2nd)?
I'm fine with the GOOG not offering Java support, but what's the justification for only offering half-assed support? It kills the whole point of portability.
Re: (Score:3, Insightful)
Subtle yet important difference to me, Microsoft released something that did include the 'full set' plus some but didn't work the same as the specs said it should.
Google simply didn't release a full set.
And where Microsoft pulled their stunt to kill Java, I imagine Google did it for technical reasons (i.e. trying to lock down the sandbox) since they have said they want to add more classes to the list of allowed ones.
Re:do their own then... (Score:5, Insightful)
The justification is the same as Sun has when it creates a limited profile of Java for a special environment, like Java ME: the demands of a special environment.
Re: .
Re: (Score:3)
So your blaming Sun for Ciscos ineptitude. I have code written under the 1.0.2 Java SDK that still runs under Java 1.6. There again, unlike Cisco's engineers I understood what portability was, because I was targeting SunOS as well as Windows.
Re: (Score:2)
I thougth the a key feature of java was "write once - run anywhere".
It is. Although "write properly once - run anywhere" would probably be more accurate.
Dont blame the developer if a new JVM breaks a java app.
Most issues I have seen with a new JVM breaking a java app is because the app developer was doing something they weren't supposed to. (using com.sun classes, relying on undocumented, "undefined" behavior, etc) If you code to the spec, and only expect methods to do what they say they'll do in the documentation, chances of a new JVM breaking your application are very slim.
As a disclaimer, note that I use terms like "
Re: effectivel
Re: (Score:2)
Sun actually is launching their own cloud computing environment this summer, and has been announcing tie-ins to a lot of their existing products for it ("Save to Cloud", "Load from Cloud" in OpenOffice.org, Cloud related functionality in Netbeans 6.7, etc.) If their attempts to market their cloud offerings fall flat (which AppEngine supporting more than just Python makes somewhat more likely, as they have more competition, though I think Amazon | http://developers.slashdot.org/story/09/04/13/2017246/suns-phipps-slams-app-engines-java-support/insightful-comments?limit=0 | CC-MAIN-2014-52 | refinedweb | 4,370 | 64 |
11 February 2011 22:18 [Source: ICIS news]
HOUSTON (ICIS)--?xml:namespace>
IPA exports totalled 237,275 tonnes in 2010, down from 295,395 tonnes in 2009, the ITC said. The decline was partly because of increased domestic demand compared with recessionary weakness in US paints and coatings markets during 2009.
December exports also fell by 22%, to 16,769 tonnes from 21,631 tonnes in November 2010.
The largest foreign customers for US IPA in December were
On the import side,
Imports were virtually flat in 2010 from 2009.
US prices for IPA are at 79-82 cents/lb ($1,742-1,808/tonne, €1,289-1,338/tonne), as assessed by ICIS.
US IPA producers include Shell Chemicals, Dow Chemical, LyondellBasell and ExxonMobil.
($1= €0.74)
For more on isopropanol | http://www.icis.com/Articles/2011/02/11/9434853/us-2010-ipa-exports-down-by-20-from-2009-itc.html | CC-MAIN-2014-52 | refinedweb | 132 | 65.42 |
I have been working on a design doc for restricted execution of Python as part of my dissertation for getting Python into Firefox to replace JavaScript on the web. Since this is dealing with security and messing that up can be costly, I am sending it to the list for any possible feedback. I have already run the ideas past Neal, Guido, Jeremy, and Alex and everyone seemed to think the design was sound (thanks to them and Will for attending my meeting on it and giving me feedback that helped to shape this doc), so hopefully there are no major issues with the design itself. There are a couple of places (denoted with XXX) where there is an open issue still. Feedback on those would be great. Anyway, here it is. I am going to be offline most of tomorrow so I probably won't get back to comments until Friday. And just in case people are wondering, I plan on doing the implementation in the open on a branch within Python's repository so if this design works out it will end up in the core (as for when that would land, I don't know, but hopefully for 2.6). --------------------------------------------------------------------------------------------- Restricted Execution for Python ####################################### About This Document ============================= This document is meant to lay out the general design for re-introducing a restriced execution model for Python. This document should provide one with enough information to understand the goals for restricted execution, what considerations were made for the design, and the actual design itself. Design decisions should be clear and explain not only why they were chosen but possible drawbacks from taking that approach. Goal ============================= A good restricted execution model provides enough protection to prevent malicious harm to come to the system, and no more. Barriers should be minimized so as to allow most code that does not do anything that would be regarded as harmful to run unmodified. An important point to take into consideration when reading this document is to realize it is part of my (Brett Cannon's) Ph.D. dissertation. This means it is heavily geared toward the restricted execution when the interpreter is working with Python code embedded in a web page. Python application, the former will win out. Throughout this document, the term "resource" is to represent anything that deserves possible protection. This includes things that have a physical representation (e.g., memory) to things that are more abstract and specific to the interpreter (e.g., sys.path). When referring to the state of an interpreter, it is either "trusted" or "untrusted". A trusted interpreter has no restrictions imposed upon any resource. An untrusted interpreter has at least one, possibly more, resource with a restriction placed upon it. .. contents:: Use Cases ///////////////////////////// All use cases are based on how many untrusted or trusted interpreters are running in a single process. When the Interpreter Is Embedded ================================ Single Untrusted Interpreter ---------------------------- This use case is when an application embeds the interpreter and never has more than one interpreter running. The main security issue to watch out for is not having default abilities be provided to the interpreter by accident. There must also be protection from leaking resources that the interpreter needs for general use underneath the covers into the untrusted interpreter. Multiple Untrusted Interpreters ------------------------------- When multiple interpreters, all untrusted at varying levels, need to be running within a single application. This is the key use case that this proposed design is targetted for. On top of the security issues from a single untrusted interpreter, there is one additional worry. Resources cannot end up being leaked into other interpreters where they are given escalated rights. Stand-Alone Python ================== When someone has written a Python program that wants to execute Python code in an untrusted interpreter(s). This is the use case that 'rexec' attempted to fulfill. The added security issues for this use case (on top of the ones for the other use cases) is preventing something from the trusted interpreter leaking into an untrusted interpreter and having elevated permissions. With the multiple untrusted interpreters one did not have to worry about preventing actions from occurring that are disallowed for all untrusted interpreters. With this use case you do have to worry about the binary distinction between trusted and untrusted interpreters running in the same process. Resources to Protect ///////////////////////////// XXX Threading? XXX CPU? Filesystem =================== The most obvious facet of a filesystem to protect is reading from it. One does not want what is stored in ``/etc/passwd`` to get out. And one also does not want writing to the disk unless explicitly allowed for basically the same reason; if someone can write ``/etc/passwd`` then they can set the password for the root account. But one must also protect information about the filesystem. This includes both the filesystem layout and permissions on files. This means pathnames need to be properly hidden from an untrusted interpreter. Physical Resources =================== Memory should be protected. It is a limited resource on the system that can have an impact on other running programs if it is exhausted. Being able to restrict the use of memory would help alleviate issues from denial-of-service (DoS) attacks. Networking =================== Networking is somewhat like the filesystem in terms of wanting similar protections. You do not want to let untrusted code make tons of socket connections or accept them to do possibly nefarious things (e.g., acting as a zombie). You also want to prevent finding out information about the network you are connected to. This includes doing DNS resolution since that allows one to find out what addresses your intranet has or what subnets you use. Interpreter =================== One must make sure that the interpreter is not harmed in any way. There are several ways to possibly do this. One is generating hostile bytecode. Another is some buffer overflow. In general any ability to crash the interpreter is unacceptable. There is also the issue of taking it over. If one is able to gain control of the overall process through the interpreter than heightened abilities could be gained. Types of Security /////////////////////////////////////// As with most things, there are multiple approaches one can take to tackle a problem. Security is no exception. In general there seem to be two approaches to protecting resources. Resource Hiding ============================= By never giving code a chance to access a resource, you prevent it from be (ab)used. This is the idea behind resource hiding. This can help minimize security checks by only checking if someone should be given a resource. By having possession of a resource be what determines if one should be allowed to use it you minimize the checks to only when a resource is handed out. This can be viewed as a passive system for security. Once a resource has been given to code there are no more checks to make sure the security model is being violated. The most common implementation of resource hiding is capabilities. In this type of system a resource's reference acts as a ticket that represents the right to use the resource. Once code has a reference it is considered to have full use of that resource it represents and no further security checks are performed. To allow customizable restrictions one can pass references to wrappers of resources. This allows one to provide custom security to resources instead of requiring an all-or-nothing approach. The problem with capabilities is that it requires a way to control access to references. In languages such as Java that use a capability-based security system, namespaces provide the protection. By having private attributes and compartmentalized namespaces, references cannot be reached without explicit permission. For instance, Java has a ClassLoader class that one can call to have return a reference that is desired. The class does a security check to make sure the code should be allowed to access the resource, and then returns a reference as appropriate. And with private attributes in objects and packages not providing global attributes you can effectively hide references to prevent security breaches. To use an analogy, imagine you are providing security for your home. With capabilities, security came from not having any way to know where your house is without being told where it was; a reference to its location. You might be able to ask a guard (e.g., Java's ClassLoader) for a map, but if they refuse there is no way for you to guess its location without being told. But once you knew where it was, you had complete use of the house. And that complete access is an issue with a capability system. If someone played a little loose with a reference for a resource then you run the risk of it getting out. Once a reference leaves your hands it becomes difficult to revoke the right to use that resource. A capability system can be designed to do a check every time a reference is handed to a new object, but that can be difficult to do properly when grafting a new way to handle resources on to an existing system such as Python since the check is no longer at a point for requesting a reference but also at plain assignment time. Resource Crippling ============================= Another approach to security is to provide constant, proactive security checking of rights to use resource's reference leaking out to insecure code is alleviated since the resource cannot be used without authorizing it regardless of whether even having the reference was granted. This does add extra overhead, though, by having to do so many security checks. FreeBSD's jail system provides a system similar to this. Various system calls allow for basic usage, but knowing of the system call is not enough to grant usage. Every call our home analogy, everyone in the world can know where your home is. But to access any door in your home, you have to pass a security check. The overhead is higher and slows down your movement in your home, but not caring if perfect strangers know where your home is prevents the worry of your address leaking out to the world. The 'rexec' Module /////////////////////////////////////// The 'rexec' module [#rexec]_ was based on the design used by Safe-Tcl [#safe-tcl]_. The design was essentially a capability system. restricted environment. Imports were checked against a whitelist of modules. You could also restrict the type of modules to import based on whether they were Python source, bytecode, or C extensions. Built-ins were allowed except for a blacklist of built-ins to not provide. Several other protections were provided; see documentation for the complete list. With an RExec object created, one could pass in strings of code to be executed and have the result returned. One could execute code based on whether stdin, stdout, and stderr were provided or not. The ultimate undoing of the 'rexec' module was how access to objects that in normal Python require no direct action restricted interpreter, one only had to do ``del __builtins__`` to gain access to the full set of built-ins. Another way is through using the gc module: ``gc.get_referrers(''.__class__.__bases__[0])[6]['file']``. While both of these could be fixed (the former a bug in 'rexec' and the latter not allowing gc to be imported), they are examples of things that do not require proactive actions on the part of the programmer in normal Python to gain access to tends to leak out. An unfortunate side-effect of having all of that wonderful reflection in Python. There is also the issue that 'rexec' was written in Python which provides its own problems. Much has been learned since 'rexec' was written about how Python tends to be used and where security issues tend to appear. Essentially Python's dynamic nature does not lend itself very well to passive security measures since the reflection abilities in the language lend themselves to getting around non-proactive security checks. The Proposed Approach /////////////////////////////////////// In light of where 'rexec' succeeded and failed along with what is known about the two main types of security and how Python tends to operate, the following is a proposal on how to secure Python for restricted execution. First, security will be provided at the C level. By taking advantage of the language barrier of accessing C code from Python without explicit allowance (i.e., ignoring ctypes [#ctypes]_), direct manipulation of the various security checks can be substantially reduced and controlled. Second, all proactive actions that code can do to gain access to resources will be protected through resource hiding. By having to go through Python to get to something (e.g., modules), a security check can be put in place to deny access as appropriate (this also ties into the separation between interpreters, discussed below). Third, any resource that is usually accessible by default will use resource crippling. Instead of worrying about hiding a resource that is available by default (e.g., 'file' type), security checks within the resource will prevent misuse. Crippling can also be used for resources where an object could be desired, but not at its full capacity (e.g., sockets). Performance should not be too much of an issue for resource crippling. It's main use if for I/O types; files and sockets. Since operations on these types are I/O bound and not CPU bound, the overhead for doing the security check should be a wash overall. Fourth, the restrictions separating multiple interpreters within a single process will be utilized. This helps prevent the leaking of objects into different interpreters with escalated privileges. Python source code modules are reloaded for each interpreter, preventing an object that does not have resource crippling from being leaked into another interpreter unless explicitly allowed. C extension modules are shared by not reloading them between interpreters, but this is considered in the security design. Fifth, Python source code is always trusted. Damage to a system is considered to be done from either hostile bytecode or at the C level. Thus protecting the interpreter and extension modules is the great worry, not Python source code. Python bytecode files, on the other hand, are considered inherently unsafe and will never be imported directly. Attempts to perform an action that is not allowed by the security policy will raise an XXX exception (or subclass thereof) as appropriate. Implementation Details =============================== XXX prefix/module name; Restrict, Secure, Sandbox? Different tense? XXX C APIs use abstract names (e.g., string, integer) since have not decided if Python objects or C types (e.g., PyStringObject vs. char *) will be used Support for untrusted interpreters will be a compilation flag. This allows the more common case of people not caring about protections to not have a performance hindrance when not desired. And even when Python is compiled for untrusted interpreter restrictions, when the running interpreter *is* trusted, there will be no accidental triggers of protections. This means that developers should be liberal with the security protections without worrying about there being issues for interpreters that do not need/want the protection. At the Python level, the __restricted__ built-in will be set based on whether the interpreter is untrusted or not. This will be set for *all* interpreters, regardless of whether untrusted interpreter support was compiled in or not. For setting what is to be protected, the XXX<pointer to interpreter> for the untrusted interpreter must be passed in. This makes the protection very explicit and helps make sure you set protections for the exact interpreter you mean to. The functions for checking for permissions are actually macros that take in at least an error return value for the function calling the macro. This allows the macro to return for the caller if the check failed and cause the XXX exception to be propagated. This helps eliminate any coding errors from incorrectly checking a return value on a rights-checking function call. For the rare case where this functionality is disliked, just make the check in a utility function and check that function's return value (but this is strongly discouraged!). API -------------- * interpreter PyXXX_NewInterpreter() Return a new interpreter that is considered untrusted. There is no corresponding PyXXX_EndInterpreter() as Py_EndInterpreter() will be taught how to handle untrusted interpreters. * PyXXX_Trusted(error_return) Macro that has the caller return with 'error_return' if the interpreter is not a trusted one. Memory ============================= Protection -------------- An memory cap will be allowed. Modification to pymalloc will be needed to properly keep track of the allocation and freeing of memory. Same goes for the macros around the system malloc/free system calls. This provides a platform-independent system for protection instead of relying on the operating system providing a service for capping memory usage of a process. PyXXX_SetMemoryCap(interpreter, integer) Set the memory cap for an untrusted interpreter. If the interpreter is not running an untrusted interpreter, return NULL. * PyXXX_MemoryAlloc(integer, error_return) Macro to increase the amount of memory that is reported that the running untrusted interpreter is running. If the increase puts the total count passed the set limit, raise an XXX exception and cause the calling function to return with the value of error_return. For trusted interpreters or untrusted interpreters where a cap has not been set, the macro does nothing. * int PyXXX_MemoryFree(integer) Decrease the current running interpreter's allocated memory. If this puts the memory returned to below 0, raise an XXX exception and return NULL. For trusted interpreters or untrusted interpreters where there is no memory cap, the macro does nothing. CPU ============================= XXX Needed? Difficult to get right for all platforms. Would have to be very platform-specific. Reading/Writing Files ============================= Protection -------------- The 'file' type will be resource crippled. The user may specify files or directories that are acceptable to be opened for reading/writing, or both. All operations that either read, write, or provide info on a file will require a security check to make sure that it is allowed for the file that the 'file' object represents. This includes the 'file' type's constructor not raising an IOError stating a file does not exist but XXX instead so that information about the filesystem is not improperly provided. The security check will be done for all 'file' objects regardless of where the 'file' object originated. This prevents issues if the 'file' type or an instance of it was accidentally made available to an untrusted interpreter. Why -------------- Allowing anyone to be able to arbitrarily read, write, or learn about the layout of your filesystem is extremely dangerous. It can lead to loss of data or data being exposed to people whom should not have access. Possible Security Flaws ----------------------- Assuming that the method-level checks are correct and control of what files/directories is not exposed, 'file' object protection is secure, even when a 'file' object is leaked from a trusted interpreter to an untrusted one. API -------------- * int PyXXX_AllowFile(interpreter, path, mode) Add a file that is allowed to be opened in 'mode' by the 'file' object. If the interpreter is not untrusted then return NULL. * int PyXXX_AllowDirectory(interpreter, path, mode) Add a directory that is allowed to have files opened in 'mode' by the 'file' object. This includes both pre-existing files and any new files created by the 'file' object. XXX allow for creating/reading subdirectories? * PyXXX_CheckPath(path, mode, error_return) Macro that causes the caller to return with 'error_return' and XXX as the exception if the specified path with 'mode' is not allowed. For trusted interpreters, the macro does trusted based on the assumption that all resource harm is eventually done at the C level, thus Python code directly cannot cause harm. Thus only C extension modules need to be checked against the whitelist. The requested extension module name is checked in order to make sure that it is on the whitelist if it is a C extension module. If the name is not correct an XXX exception is raised. Otherwise the import is allowed. Even if a Python source code module imports a C extension module in a trusted interpreter it is not a problem since the Python source code module is reloaded in the untrusted interpreter. When that Python source module is freshly imported the normal import check will be triggered to prevent the C extension module from becoming available to the untrusted interpreter. For the 'os' module, a special restricted work off of rexec whitelist? Why -------------- Because C code is considered unsafe, its use should be regulated. By using a whitelist it allows one to explicitly decide that a C extension module should be considered safe. Possible Security Flaws ----------------------- If a trusted C extension module imports an untrusted C extension module and make it an attribute of the trust module there will be a breach in security. Luckily this a rarity in extension modules. There is also the issue of a C extension module calling the C API of an untrusted C extension module. Lastly, if a trusted C extension module is loaded in a trusted interpreter and then loaded into an untrusted interpreter then there is no possible checks during module initialization for possible security issues for resources opened during initialization of the module if such checks exist in the init*() function. All of these issues can be handled by never blindly whitelisting a C extension module. Added support for dealing with C extension modules comes in the form of `Extension Module Crippling`_. API -------------- * int PyXXX_AllowModule(interpreter, module_name) Allow the untrusted interpreter to import 'module_name'. If the interpreter is not untrusted, return NULL. XXX sub-modules in packages allowed implicitly? Or have to list all modules explicitly? * int PyXXX_BlockModule(interpreter, module_name) Remove the specified module from the whitelist. Used to remove modules that are allowed by default. If called on a trusted interpreter, returns NULL. * PyXXX_CheckModule(module_Name, error_return) Macro that causes the caller to return with 'error_return' and sets the exception XXX if the specified module cannot be imported. For trusted interpreters the macro PyXXX_Trusted() to protect unsafe code from being executed. Hostile Bytecode ============================= Protection -------------- The code object's constructor is not callable from Python. Importation of .pyc and .pyo files is also prohibited. Why -------------- Without implementing a bytecode verification tool, there is no way of making sure that bytecode does not jump outside its bounds, thus possibly executing malicious code. It also presents the possibility of crashing the interpreter. Possible Security Flaws ----------------------- None known. API -------------- None. Changing the Behaviour of the Interpreter ========================================= Protection -------------- Only a subset of the 'sys' module will be made available to untrusted interpreters. Things to allow from the sys module: * byteorder * subversion * * __stdin__ # See `Stdin, Stdout, and Stderr`_ XXX Perhaps not needed? * __stdout__ * __stderr__ * version * api PyXXX_AllowIPAddress(interpreter, IP, port) Allow the untrusted interpreter to send/receive to the specified IP address on the specified port. If the interpreter is not untrusted, return NULL. * PyXXX_CheckIPAddress(IP, port, error_return) Macro to verify that the specified IP address on the specified port is allowed to be communicated with. If not, cause the caller to return with 'error_return' and XXX exception set. If the interpreter is trusted then do nothing. * PyXXX_AllowHost(interpreter, host, port) Allow the untrusted interpreter to send/receive to the specified host on the specified port. If the interpreter is not untrusted, return NULL. XXX resolve to IP at call time to prevent DNS man-in-the-middle attacks? * PyXXX_CheckHost(host, port, error_return) Check that the specified host on the specified port is allowed to be communicated with. If not, set an XXX exception and cause the caller to return 'error_return'. If the interpreter is trusted then do nothing. Network Information ============================= Protection -------------- Limit what information can be gleaned about the network the system is running on. This does not include restricting information on IP addresses and hosts that are have been explicitly allowed for the untrusted interpreter to communicate with. PyXXX_AllowNetworkInfo(interpreter) Allow the untrusted interpreter to get network information regardless of whether the IP or host address is explicitly allowed. If the interpreter is not untrusted, return NULL. * PyXXX_CheckNetworkInfo(error_return) Macro that will return 'error_return' for the caller and set XXX exception if the untrusted interpreter does not allow checking for arbitrary network information. For a trusted interpreter this does nothing. Filesystem Information ============================= Protection -------------- Do not allow information about the filesystem layout from various parts of Python to be exposed. This means blocking exposure at the Python level to: * __file__ attribute on modules * __path__ attribute on packages * co_filename attribute on code objects Why -------------- Exposing information about the filesystem is not allowed. You can figure out what operating system one is on which can lead to vulnerabilities specific to that operating system being exploited. Possible Security Flaws ----------------------- Not finding every single place where a file path is exposed. API -------------- * int PyXXX_AllowFilesystemInfo(interpreter) Allow the untrusted interpreter to expose filesystem information. If the passed-in interpreter is not untrusted, return NULL. * PyXXX_CheckFilesystemInfo(error_return) Macro that checks if exposing filesystem information is allowed. If it is not, cause the caller to return with the value of 'error_return' and raise XXX. Threading ============================= XXX Needed? Stdin, Stdout, and Stderr ============================= Protection -------------- By default, sys.__stdin__, sys.__stdout__, and sys.__stderr__ will be set to instances of cStringIO. Allowing use of the normal stdin, stdout, and stderr will be allowed. XXX Or perhaps __stdin__ and friends should just be blocked and all you get is sys.stdin and friends set to cStringIO. Why -------------- Interference with stdin, stdout, or stderr should not be allowed unless desired. Possible Security Flaws ----------------------- Unless cStringIO instances can be used maliciously, none to speak of. XXX Use StringIO instances instead for even better security? API -------------- * int PyXXX_UseTrueStdin(interpreter) int PyXXX_UseTrueStdout(interpreter) int PyXXX_UseTrueStderr(interpreter) Set the specific stream for the interpreter to the true version of the stream and not to the default instance of cStringIO. If the interpreter is not untrusted, return NULL. Adding New Protections ============================= -------------- XXX Could also have PyXXXExtended prefix instead for the following functions + Bool * int PyXXX_ExtendedSetTrue(interpreter, group, type) Set a group-type to be true. Expected use is for when a binary possibility of something is needed and that the default is to not allow use of the resource (e.g., network information). Returns NULL if the interpreter is not untrusted. * PyXXX_ExtendedCheckTrue(group, type, error_return) Macro that if the group-type is not set to true, cause the caller to return with 'error_return' with XXX exception raised. For trusted interpreters the check does nothing. + Numeric Range * int PyXXX_ExtendedValueCap(interpreter, group, type, cap) Set a group-type to a capped value, with the initial value set to 0. Expected use is when a resource has a capped amount of use (e.g., memory). Returns NULL if the interpreter is not untrusted. * PyXXX_ExtendedValueAlloc(increase, error_return) Macro to raise the amount of a resource is used by 'increase'. If the increase pushes the resource allocation past the set cap, then return 'error_return' and set XXX as the exception. * PyXXX_ExtendedValueFree(decrease, error_return) Macro to lower the amount a resource is used by 'decrease'. If the decrease pushes the allotment to below 0 then have the caller return 'error_return' and set XXX as the exception. + Membership * int PyXXX_ExtendedAddMembership(interpreter, group, type, string) Add a string to be considered a member of a group-type (e.g., allowed file paths). If the interpreter is not an untrusted interpreter, return NULL. * PyXXX_ExtendedCheckMembership(group, type, string, error_return) Macro that checks 'string' is a member of the values set for the group-type. If it is not, then have the caller return 'error_return' and set an exception for XXX. For trusted interpreters the call does nothing. + Specific Value * int PyXXX_ExtendedSetValue(interpreter, group, type, string) Set a group-type to a specific string. If the interpreter is not untrusted, return NULL. * PyXXX_ExtendedCheckValue(group, type, string, error_return) Macro to check that the group-type is set to 'string'. If it is not, then have the caller return 'error_return' and set an exception for XXX. If the interpreter is trusted then nothing is done. References /////////////////////////////////////// .. [#rexec] The 'rexec' module () .. [#safe-tcl] The Safe-Tcl Security Model () .. [#ctypes] 'ctypes' module () | http://mail.python.org/pipermail/python-dev/2006-June/066344.html | crawl-002 | refinedweb | 4,670 | 54.63 |
09 November 2012 14:50 [Source: ICIS news]
LONDON (ICIS)--Evonik is “still doing well” in difficult global economic conditions and will retain its full-year 2012 sales and profit outlook - despite a 6% decline in third-quarter sales, the CEO of the Germany-based specialty chemicals major said on Friday.
Evonik expects its full-year 2012 full-year sales to be slightly higher than in 2011, with operating results in line with 2011, or slightly higher. The outlook excludes sales from the carbon black business Evonik divested last year.
“However, the global economic framework is challenging and demand has weakened since the summer, especially in ?xml:namespace>
The slight slowdown in global economic growth is expected to continue in the current fourth quarter, Engel said.
Risks relating to the European sovereign debt crisis are continuing unabated and could adversely affect the economic situation in
Also, growth prospects in some emerging markets have deteriorated. Overall, Evonik expects global economic growth to be lower than in 2011, he said.
Engel also pointed to the Evonik’s cost savings programme.
"We will continue to systematically work towards our goal of sustained annual cost savings of around €500m ($641m) by the end of 2016,” he said.
“Our ambitious growth targets and the combination of strict cost management and a further improvement in efficiency are two sides of the same coin," he said.
Evonik’s third-quarter sales fell 6% year on year to €3.4bn, and nine-month sales were down 8% year on year to €10.4bn – mainly because of sales lost from the divested carbon black business, the company said earlier on Friday.
($1 = €0.78)
Additional reporting by Nurluqman Surat | http://www.icis.com/Articles/2012/11/09/9612856/evonik-maintains-outlook-despite-q3-decline-in-sales-ceo.html | CC-MAIN-2014-52 | refinedweb | 280 | 52.29 |
Car detection
Recently I've been working on a program that allows you to detect when ever there's a parking space available. But my algorithm ran into a problem. I'm using simplecv and what I did was crop the parking as close as possible to the car and
.meanColor() the crop and comparing that to a
.meanColor() taken from and empty parking space. It was working fine with white and dark cars, but when I tried it with others colors that weren't so dark or light, the values were lower than the values of the empty space. I started looking for an alternative solution and stumbled upon the tutorial on car detection that simplecv provides, BUT it worked if you hardcoded the color. I don't want to hard code the color, I need to identify it or try something similar that can help me detect there's a car there.
This is what I tried :
from SimpleCV import * imgOri = Image("allCars3.jpg") imgOri = imgOri.scale(400, 400) corX = 0 #ancho del parking parking = 0 imgList = [] for i in range(3): imgList.append(imgOri.crop(corX, 70, 133, 120)) avg = imgList[i].meanColor() if avg[0] < 123 and avg[1] < 126 and avg[2] < 127: parking += 1 corX += 133 imgList[2].show()
worked with these type of cars:... (picture too big to upload here)
Didn't work with these three:...
The values I took to detect a car where taken from this picture:...
This is the tutorial I found for car detection:...
Notice that the person how wrote this tutorial already knew the color. I need the program to figure out that color in order to use that same idea.
Any suggestions, questions, tips or ideas are welcomed.
Thanks | http://help.simplecv.org/question/2633/car-detection/ | CC-MAIN-2019-26 | refinedweb | 292 | 74.69 |
should delete.this all process in single jsp page..i hopely waiting for answer...Student Sir i want display data for dropdownlistbox from database... in table..(using ajax) and each row have edit and delete buttton,i click edit
Hi... - Struts
Hi... Hi,
If i am using hibernet with struts then require... of this installation Hi friend,
Hibernate is Object-Oriented mapping tool... more information,tutorials and examples on Struts with Hibernate visit
Hi - Struts
very urgent....
Hi friend,
I am sending you a link...Hi Hi friends,
must for struts in mysql or not necessary...:// all - Java Beginners
hi all hi,
i need interview questions of the java asap can u please sendme to my mail
Hi,
Hope you didnt have this eBook. You... friend,
I am sending you a link. This link will help you.
Please read Some errors in Struts - Struts
i am Getting Some errors in Struts I am Learning Struts Basics,I am Trying examples do in this Site Examples.i am getting lot of errors.Please Help me
Student - Java Beginners
[]=new Student[2];
for (int i=0; i65&&tm<75){
data[i].setGrade("C...].setGrade("A");
}
}
for(int i=0;i<2;i++){
Student show = data[i...Student Create a class named Student which has data fields
genarating student weekly progress report
genarating student weekly progress report Hi every one iam using struts frame work backend as oracle 10g . i want code for how to genarate student weekly and monthly marks .
thanks in advance
hi
online multiple choice examination hi i am developing online multiple choice examination for that i want to store questions,four options,correct answer in a xml file using jsp or java?can any one help me?
Please I need some help I've got my java code and am having difficulty to spot what errors there are is someone able to help
import java.util.Scanner;
public class Post {
public static void main(String[] args) {
Scanner sc
hi
hi i want to develop a online bit by bit examination process as part of my project in this i am stuck at how to store multiple choice questions options and correct option for the question.this is the first project i am doing class
points being displayed in the world
points being displayed in the world how do i display points in my world
Hi Friend,
Please clarify your problem.
Thanks
Struts - Jboss - I-Report - Struts
Struts - Jboss - I-Report Hi i am a beginner in Java programming and in my application i wanted to generate a report (based on database) using Struts, Jboss , I
Student Marks
Student Marks Hi everyone
I have to do this java assignment... programming grades of 8 IT students.
Randomly create student numbers for each... in an array.
Addresses of Students and store them in array.
Previous Grade for student Hello
I like to make a registration form in struts inwhich students course
also mention in a combo box. If student choose particular course then page is redirected to that course's subjects. Also all subject should
struts
struts <p>hi here is my code in struts i want to validate my form fields but it couldn't work can you fix what mistakes i have done</p>...;
Student Name:<html:text
Fathers
Struts
Struts Hi i am new to struts. I don't know how to create struts please in eclipse help me
school student attendence report
school student attendence report Hi i want school student attendence genaration source code please urgent
Student Management System
Student Management System Hi , Friend can i get the solution for connecting login page of JFrames to JDBC
Not sure what I am missing ? Any ideas?
Not sure what I am missing ? Any ideas? import java.util.*;
public...)
{
if(str.length()==0)
return false;
for(int i=0;i<str.length();i++)
if (c==str.charAt(i));
return true
struts- login problem - Struts
struts- login problem Hi all, I am a java developer, I am facing problems with the login application. The application's login page contains fields like username, password and a login button. With this functionality only
the Struts if being used in commercial purpose.
the Struts if being used in commercial purpose. Do we need to pay the Struts if being used in commercial purpose
Student Admission Form in Java - Java Beginners
Student Admission Form in Java I want to store following Information into MS Access 2007 with JDBC.
1)Student PRN Number
2)Student Name
3)Date...; Hi i produce sample application with access 2007 and i haven't done Code - Struts
Struts Code Hi
I executed "select * from example" query and stored all the values using bean . I displayed all the records stored in the jsp using struts . I am placing two links Update and Delete beside each record .
Now I
Struts - Struts
Struts hi,
I am new in struts concept.so, please explain example login application in struts web based application with source code...://
I hope that, this link will help you...
{
public ActionForward execute(ActionMapping am,ActionForm af...(ActionMapping am,HttpServletRequest req)
{
ActionErrors ae=new ActionErrors
Struts file uploading - Struts
Struts file uploading Hi all,
My application I am uploading... = newDocumentForm.getMyDocument();
byte[] fileData = file.getFileData();
I am... when required.
I could not use the Struts API FormFile since 2.0 - Struts
Struts 2.0 Hi ALL,
I am getting following error when I am trying to use tag.
tag 'select', field 'list': The requested list key 'day' could.../SelectTag.jsp"
please let me know If I am doing
creating an applet for student management system
creating an applet for student management system Write an applet/awt... a student management system having the following characteristics:
The interface... it to act), and reasonably realistic. It must accept the student id,name,age,address
Hi
Hi I want import txt fayl java.please say me...
Hi,
Please clarify your problem!
Thanks, how i get answer of my question which is asked by me for few minutes ago.....rply
i am inserting an image into database but it is showing relative path not absolute path
i am inserting an image into database but it is showing relative path not absolute path hi my first page.........
<html>
<head>...)
{
System.out.println(e);
}
%>
</body>
</html>
when i compiled it i
hi
the total cost of the two items;otherwise,display the total for all three
hi..
hi.. I want upload the image using jsp. When i browse the file then pass that file to another jsp it was going on perfect. But when i read...);
for(int i=0;i<arr.length-1;i++) {
newstr=newstr
Advertisements
If you enjoyed this post then why not add us on Google+? Add us to your Circles | http://roseindia.net/tutorialhelp/comment/11974 | CC-MAIN-2016-18 | refinedweb | 1,128 | 64.91 |
12 Downloads
Updated 03 Aug 2012View Version History
The function xlwrite has similar syntax and inputs as MatLAB's xlswrite.
It also can write 3-d arrays (xlswrite can't), of cell and double type. To simplify the idea : we forward Matlab data to be exported to a Java function which in turn writes the data to excel.
Note that data to be exported is converted to cell then to java String array.
This workaround is a real working solution, it may need further refinements :
- manage Java heap space, as Java heap memory saturates for large arrays exported many times.
- format dates and strings, as all numbers appear as text in Excel.
Matlab's decimal separator is '.' : in order to be able to work with exported data, users of this solution will have to change Mac preferences regarding the decimal separator (should be ".").
To do so you need to go to System Preferences > International > Formats and click on Customize button in number zone, then type '.' in the field required.
This solution works under Windows.
Test_xlwrite.m contains an example.
Marin Deresco (2020). xlwrite : Export Data to Excel from Matlab on Mac/Win (), MATLAB Central File Exchange. Retrieved .
Inspired: xlread, xlwrite: Generate XLS(X) files without Excel on Mac/Linux/Win, csvimport(filename), csvexport(filename,cellVals)
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!
Create scripts with code, output, and formatted text in a single executable document.
For those who still struggle with WriteXL error, just go to Test_xlwrite.m and copy the following lines and paste them write before using "xlwrite" in your main code.
best,
javaaddpath('jxl.jar');
javaaddpath('MXL.jar');
import mymxl.*;
import jxl.*;
I still got a problem like this:
"Undefined function or variable 'WriteXL'.
Error in xlwrite (line 108)
WriteXL(java.lang.String(file),Cell2JavaString(data),m(1),m(2),java.lang.String(sheet),exist(file,'file')/2); "
xlwrite line of 108-116 is as below:
if (max(size(m))==2)
WriteXL(java.lang.String(file),Cell2JavaString(data),m(1),m(2),java.lang.String(sheet),exist(file,'file')/2);
Result=1;
else
error('data Matrix too large, when specifying a single sheet, data must have at most 2 dimensions');
end
Could anybody teach me how to fix it?
Sorry, but it's been 5 years now and there is still nothing better than a "working solution"? I really don't want to have to work myself into running a JAVA script just to print my Matlab output as an XLS file. Why hasn't that been worked into release RS2015a?
If you are not already using Java with MATLAB, don't waste your time, there are no instructions on how to get this to run.
when i run it and then try to open the xlsx file both under Office 2011 or Office 365 for Mac it tells me that the file is corrupted or invalid. Any suggestions? thanks
Hi,
Thanks for having this utility for us! It may solve my need: I am writing an Matlab function which uses xlswrite under window OS. The intended user of this function however will be in Mac and Linux OS. I tried your test_xlwrite.m in my window machine and it works. However when I opened the resultant excel file, mat1_excel.xls, I got warning messages for all each of the cells, saying that the numbers are stored as text. I have to manually convert text to number cell by cell. Do you have a better solution to this problem?
Zhigang
How do I add the POI jar files to the Matlab Java path?
I keep getting this error:
Error using xlwrite (line 93)
The POI library is not loaded in Matlab.
Check that POI jar files are in Matlab Java path!
I'm running MATLAB R2015a on a MacBook air
Thanks!
For the people asking about the "WriteXL" error.
In my copy, the indentation was off. I just went to line 107 in the "xlwrite.m" file and corrected it. Hope that works for you as well.
The link posted below by Marin Deresco:
will lead you to another version of the same program. This is confusing - there are overlapping programs with overlapping updates. However, the link leads to the latest, and the latest works.
Another confusing thing is managing the Java libraries, which is unexplained. Practically, I have put the poi-library in an area where I keep matlab programs, moved the javaaddpath statements to my startup, which executes from there, and removed them from the test case. The Java paths are relative to wherever javaaddpath is executed (not explained).
It turns out that javaaddpath is inefficient, intended for development only. Instructions on putting a library on your static Java path are in Matlab documentation at Bringing Java Classes into MATLAB Workspace, Static Path. I have not been able to make these work. I have tried various forms of the path, relative and absolute. The instructions seems to be Windows-oriented. If anyone figures out how to make the instructions for static path work, an explanation would be appreciated. Meanwhile the dynamic path does work.
I tried this function with Matlab 2015a but it seems to have problems running, any updates? I get Error in xlwrite (line 146)
xlsWorkbook=HSSFWorkbook( );
Like Joachim Seel, but I got a similar error while using xlwrite :
"
Undefined function 'WriteXL' for input arguments of type 'java.lang.String'.
Error in xlwrite (line 108)
WriteXL(java.lang.String(file),Cell2JavaString(data),m(1),m(2),java.lang.String(sheet),exist(file,'file')/2);
"
In the folder Archive, there is
Cell2JavaString.m WriteXL.java xlwrite.m
MXL.jar cell2char.m
Test_xlwrite.m jxl.jar,
but no WriteXL.m :(
How can I fix this ? I'm a beginner using additional tools like this.
Hi, could I write on specific cells with xlwrite?
If the answer is yes please tell me how!
Hi, I have downloaded the xlwrite file but run into this error when trying to run the script below: Any suggestions how to correct this error? Thanks!
Undefined function 'WriteXL' for input arguments of type 'java.lang.String'.
Error in xlwrite (line 68)
WriteXL(java.lang.String(file),Cell2JavaString(data),m(1),m(2));
This is the script.
%define variables
anualbaselineT=5045.2;
anualbaselineX=6902.8;
anualbaselineZ=8773.5;
PVloadratio=1.56;
% read in dynamic load
[dynamic_load_matrix,~,~]=xlsread('../E1_Load_Profile.xlsx','sheet1','C1:Z365');
%pre-allocate for speed
dynamic_load_vector=zeros(8760,1);
% loop through each row of dynamic_load_matrix and append to
% dynamic_load_vector
for i=1:365
dynamic_load_vector((24*i-23):(24*i))=dynamic_load_matrix(i,:);
end
dynamic_load_vector_norm=dynamic_load_vector/sum(dynamic_load_vector);
dynamic_load_baseline_norm(:,1)=dynamic_load_vector_norm*anualbaselineT;
dynamic_load_baseline_norm(:,2)=dynamic_load_vector_norm*anualbaselineX;
dynamic_load_baseline_norm(:,3)=dynamic_load_vector_norm*anualbaselineZ;
dynamic_load_baseline_norm_PV=dynamic_load_baseline_norm*PVloadratio;
header_baseline={'baselineT','baselineX','baselineZ'};
%%
xlwrite('../E1_load_vector.xlsx',header_baseline);
xlwrite('../E1_load_vector.xlsx',header_baseline,'load','A1:C1');
xlwrite('../E1_load_vector.xlsx',dynamic_load_baseline_norm,'load','A2:C366');
xlwrite('../E1_load_vector.xlsx',header_baseline,'load_PV','A1:C1');
xlwrite('../E1_load_vector.xlsx',dynamic_load_baseline_norm,'load_PV','A2:C366');
Complicated to get started with the java files etc and no very good instructions on this. See the example however.
Doesn't support specifying to a range.
However - support multi-dimensional variables which is a great bonus.
@ the cyclist:
check the following submission:
@ Paul Shoemaker :
Will try to test a quick solution for xlsread soon (1-2 months).
Regards
Very neat! Any chance we might see an xlread variant that is similarly cross-platform?
@ the cyclist :
Hope xlwrite will help you. Thank you for the remark about the specific cells export. I didn't focus on this point yet. The idea behind xlwrite was to export Matlab 3d arrays of doubles or cells to excel.
If time permits, my next submission will contain currently missing xlswrite features.
This is an exciting submission, as it is an ongoing frustration that xlswrite doesn't function fully on a Mac.
xlwrite doesn't seem to have the ability to write to specific cells on a worksheet, as xlswrite does. Is that something you are planning to add, or is there some fundamental impediment to doing that? It would be a powerful addition. | https://www.mathworks.com/matlabcentral/fileexchange/37560-xlwrite-export-data-to-excel-from-matlab-on-mac-win?s_tid=srchtitle | CC-MAIN-2020-45 | refinedweb | 1,344 | 50.12 |
I'm having been getting a weird DNS response recently. If I ping any unresolved DNS (without tld, I.e. abc instead of abc.com), it will return the IP 72.167.34.97. If I would do it in the browser, it then redirect to telogis.com's login page.
I first notice this a month back in our office when I wanted to access the AP, but keyed in a wrong IP into the browser. It shows the telogis page. It was in the middle of mixing pfSense with Windows 2003 AD environment, thus I was assuming it's an configuration mistaken. After everything stabilized, I still bump into telogis page for this unresolved domain name, that's when I started to take notice. It would even redirect to telogis if I've misspelled the SharePoint server name in the browser.
I never heard of telogis before this. I've not installed anything from telogis as well. After much digging, I didn't find anything related to telogis or 72.167.34.97 recorded in registry or hosts file. This doesn't happen to my colleague. And it even happen to the same laptop when I'm online elsewhere.
Anywhere else I should be looking to remove this as it's starting to pose problem when I'm diagnosing a network issue, while Windows cache the unwanted DNS entries. Or anyone has a similar experience.
I'm running Windows 7 Ultimate x86 SP1, I'm 99.9% sure my laptop is free from spyware and viruses. Another side note, along the same time, I was migrating my local laptop profile to join the office's Windows 2003 AD domain. I've configured the NIC interface's DNS server to the AD in the office, router at home and ISPs elsewhere. Also, It won't resolved if I try to ping offline, which is expected.
EDIT:
billc.cn for the nslookup tips. Now I've found out the culprit. Our office domain is example.com , which the domain will resolve to telogis' IP, but we're using it internally, which shouldn't be a problem, except for this particular one. Any DNS lookup to non-tld domain, ends up with domain.example.com, which in turn resolve back to telogis again. This is what nslookup return when I lookup for test
example.com
domain.example.com
test
C:\>nslookup test
Server: unknown
Address: 192.168.1.1
Non-authoritative answer:
Name: telogis.com
Address: 72.167.34.97
Aliases: test.example.com
So this means that it should happen to all PC which has joint this domain. I've better double check again. Is there anyway to overcome this?
xxx.com.
xxx.
xxx.com
Do you have more than one active network connection or a working IPv6 link? You may have a differerent DNS setting elsewhere that is taking precedence over your main DNS setting. Run nslookup without any argument and see what is the default one your systme is using.
nslookup
If the DNS is correct, it is possible some software registered a namespace in your system. Use netsh winsock show cata to view the installed ones.
netsh winsock show cata
It has to be a DNS suffix set in one of the adapters. Can you hit Start then type
view net
in the search box, and select view network connections. Go through the properties of each interface and check the properties of the ipv4 and ipv6 items. Look in Advanced, and the DNS tab, and look for the second box to see if it has any additional suffixes defined.
view network connections
I am assuming you have already checked the ID of your computer, but if not, go to Start, then right-click Computer and select properties. See what domain is defined in the Computer Name section. If this is fine, then click Change Settings, then Change against "To rename...", then the More button, and see what the Primary DNS suffix is set to.
By posting your answer, you agree to the privacy policy and terms of service.
asked
4 years ago
viewed
369 times
active
10 days ago | http://superuser.com/questions/344620/unexpected-dns-entries-returned | CC-MAIN-2016-26 | refinedweb | 692 | 76.11 |
I
import Tkinter
app = Tkinter.Tk()
app.iconbitmap("@/usr/X11R6/include/X11/bitmaps/flagup")
app.mainloop()
As often happens, the Tkinter documentation doesn't tell the whole
story---you have to dig into the Tk documentation. I started with "man
n wm", and read the following:
If bitmap is specified, then it names a bitmap in the standard
forms accepted by Tk (see the Tk_GetBitmap manual entry for
details).
OK, on to Tk_GetBitmap...
@fileName FileName must be the name of a file containing a
bitmap description in the standard X11 or X10 format.
and I happened to know that some bitmaps in this format exist in the
directory I mentioned above. Note that the "standard X11 format" is
monochrome, so you will not be able to use color images with
"iconbitmap" on Linux. Tk doesn't support _NET_WM_ICON for setting
full-color icons.
Jeff
Thanks for this, Jeff - I'll do some digging in the Tk docs. My problem is
that I'm trying to use iconwindow() to use a colour image, as opposed to
iconbitmap(), although if push comes to shove I suppose I could use that.
Thanks again for the quick response - on Easter weekend too!
Best of luck! Unfortunately, the code is not supported.
Jeff
Thanks very much for the link! I'll take a look. | https://groups.google.com/g/comp.lang.python/c/laXFfIKWmdI | CC-MAIN-2022-21 | refinedweb | 219 | 66.23 |
Caching issues¶
While developing an app, if you see an error or warning that stems from a cached function, it’s probably related to the hashing procedure described in the Improve app performance. In this article, we’ll provide solutions to common issues encountered when using caching. If you have an issue that’s not covered in this article, please let us know in the community forum.
How to debug a cached function that isn’t executing¶
If you believe your cached function isn’t executing even though its inputs are a “Cache miss”, you can debug using
st.write statements inside and outside of your function like this:
@st.cache def my_cached_func(a, b): st.write("Cache miss: my_cached_func(", a, ", ", b, ") ran") ... st.write("Calling my_cached_func(", a, ", ", b, ")") my_cached_func(2, 21)
How to fix an
UnhashableTypeError¶
Streamlit raises this error whenever it encounters a type it doesn’t know how to hash. This could be either when hashing the inputs to generate the cache key or when hashing the output to verify whether it changed. To address it, you’ll need to help Streamlit understand how to hash that type by using the
hash_funcs argument:
@st.cache(hash_funcs={FooType: hash_foo_type}) def my_cached_func(a, b): ...
Here,
FooType is the type Streamlit was unable to hash, and
hash_foo_type is a function that can be used to properly hash
FooType objects.
For example, if you’d like to make Streamlit ignore a specific type of object when hashing, you can pass a constant function to
hash_funcs, like this:
@st.cache(hash_funcs={FooType: lambda _: None}) def my_cached_func(a, b): ...
For more information, see Improve app performance.
How to fix the Cached Object Mutated warning¶
By default Streamlit expects its cached values to be treated as immutable – that cached objects remain constant. You received this warning if your code modified a cached object (see Example 5 in Caching). When this happens, you have a few options:
If you don’t understand why you’re seeing this error, it’s very likely that you didn’t mean to mutate the cached value in the first place. So you should either:
Preferred: rewrite your code to remove that mutation
Clone the output of the cached function before mutating it. For example:
import copy cloned_output = copy.deepcopy(my_cached_function(...))
If you wanted to allow the cached object to mutate, you can disable this check by setting
allow_output_mutation=Truelike this:
@st.cache(allow_output_mutation=True) def my_cached_func(...): ...
For examples, see Advanced caching.
Note
If your function returns multiple objects and you only want to allow a subset of them to mutate between runs, you can do that with the hash_funcs option.
If Streamlit is incorrectly hashing the cached object, you can override this by using
hash_funcs. For example, if your function returns an object of type
FooTypethen you could write:
@st.cache(hash_funcs={FooType: hash_func_for_foo_type}) def my_cached_func(...): ...
For more information, see Improve app performance.
By the way, the scenario above is fairly unlikely — unless
FooTypedoes something particularly tricky internally. This is the case with some
SpaCYobjects, which can automatically mutate behind the scenes for better performance, while keeping their semantics constant. That means Streamlit will correctly detect a mutation in the object’s internal structure, even though semantically that mutation makes no difference.
If all else fails¶
If the proposed fixes above don’t work for you, or if you have an idea on how to further improve
@st.cache – let us know by asking questions in the community forum, filing a bug, or submitting a feature request. We love hearing back from the community! | https://docs.streamlit.io/en/stable/troubleshooting/caching_issues.html | CC-MAIN-2021-04 | refinedweb | 596 | 54.83 |
Write a MIME Email Body to a file. More...
#include "config.h"
#include <stdbool.h>
#include <string.h>
#include "mutt/lib.h"
#include "email/lib.h"
#include "body.h"
#include "lib.h"
#include "ncrypt/lib.h"
#include "mutt_globals.h"
#include "muttlib.h"
Go to the source code of this file.
Write a MIME Email Body body.c.
Set up the base64 conversion.
Definition at line 55 of file body.c.
Save the bytes to the file.
Definition at line 69 of file body.c.
Base64-encode one character.
Definition at line 104 of file body.c.
Base64-encode some data.
Definition at line 118 of file body.c.
Write the data as raw 8-bit data.
Definition at line 146 of file body.c.
Encode text as quoted printable.
Definition at line 167 of file body.c.
Should the Body be written as a text MIME part.
Definition at line 300 of file body.c.
Write a MIME part.
Definition at line 314 of file body.c. | https://neomutt.org/code/send_2body_8c.html | CC-MAIN-2021-49 | refinedweb | 167 | 83.22 |
Mix is a build tool that provides tasks for creating, compiling, and testing Elixir projects, managing its dependencies, and more.
The foundation of Mix is a project. A project can be defined by using
Mix.Project in a module, usually placed in a file named
mix.exs:
defmodule MyApp.MixProject world") end end
The task can now be invoked with
mix hello.
See the
Mix.Task behaviour for detailed documentation on Mix tasks.
Mix also manages your dependencies and integrates nicely with the Hex package manager.
In order to use dependencies, you need to add a
:deps key to your project configuration. We often extract the list of dependencies into its own function:
defmodule MyApp.MixProject
You can also specify that certain dependencies are available only for certain environments:
{:some_test_dependency, "~> 1.0", only: :test}
The environment can be read via
Mix.env/0.
Besides environments, Mix supports targets. Targets are useful when a project needs to compile to different architectures and some of the dependencies are only available to some of them. By default, the target is
:host but it can be set via the
MIX_TARGET environment variable. The target can be read via
Mix.target/0.Project world", then fetches dependencies specific to the current environment, and compiles the project.
Aliases can also be used to augment existing tasks. Let's suppose you want to augment
mix clean to clean another directory Mix does not know about:
[clean: ["clean", &clean_extra/1]]
Where
&clean_extra/1 would be a function in your
mix.exs with extra cleanup logic.
Arguments given to the alias will be appended to the arguments of the last task in the list. Except when overriding an existing task. In this case, the arguments will be given to the original task, in order to preserve semantics. For example, in the
:clean alias above, the arguments given to the alias will be passed to "clean" and not to
clean_extra/1.
Aliases defined in the current project do not affect its dependencies and aliases defined in dependencies are not accessible from the current project.
Aliases can be used very powerfully to also run Elixir scripts and shell commands, for example:
# priv/hello1.exs IO.puts("Hello One") # priv/hello2.exs IO.puts("Hello Two") # priv/world.sh #!/bin/sh echo "world!" # mix.exs defp aliases do [ some_alias: ["hex.info", "run priv/hello1.exs", "cmd priv/world.sh"] ] end
In the example above we have created the alias
some_alias that will run the task
mix hex.info, then
mix run to run an Elixir script, then
mix cmd to execute a command line shell script. This shows how powerful aliases mixed with Mix tasks can be.
Mix tasks are designed to run only once. This prevents the same task to be executed multiple times. For example, if there are several tasks depending on
mix compile, the code will be compiled once. Tasks can be executed again if they are explicitly reenabled using
Mix.Task.reenable/1:
another_alias: [ "format --check-formatted priv/hello1.exs", "cmd priv/world.sh", fn _ -> Mix.Task.reenable("format") end, "format --check-formatted priv/hello2.exs" ]
Some tasks are automatically reenabled though, as they are expected to be invoked multiple times. They are:
mix cmd,
mix do,
mix loadconfig,
mix profile.cprof,
mix profile.eprof,
mix profile.fprof,
mix run, and
mix xref.
It is worth mentioning that some tasks, such as in the case of the
mix format command in the example above, can accept multiple files so it could be rewritten as:
another_alias: ["format --check-formatted priv/hello1.exs priv/hello2.exs"]
Several environment variables can be used to modify Mix's behaviour.
Mix responds to the following variables:
MIX_ARCHIVES- specifies the directory into which the archives should be installed (default:
~/.mix/archives)
MIX_BUILD_ROOT- sets the root directory where build artifacts should be written to. For example, "_build". If
MIX_BUILD_PATHis set, this option is ignored.
MIX_BUILD_PATH- sets the project
Mix.Project.build_path/0config. This option must always point to a subdirectory inside a temporary directory. For instance, never "/tmp" or "_build" but "_build/PROD" or "/tmp/PROD", as required by Mix
MIX_DEPS_PATH- sets the project
Mix.Project.deps_path/0config (default:
deps)
MIX_DEBUG- outputs debug information about each task before running it
MIX_ENV- specifies which environment should be used. See Environments
MIX_TARGET- specifies which target should be used. See Targets
MIX_EXS- changes the full path to the
mix.exsfile
MIX_HOME- path to Mix's home directory, stores configuration files and scripts used by Mix (default:
~/.mix)
MIX_PATH- appends extra code paths
MIX_QUIET- does not print information messages to the terminal
MIX_REBAR- path to rebar command that overrides the one Mix installs (default:
~/.mix/rebar)
MIX_REBAR3- path to rebar3 command that overrides the one Mix installs (default:
~/.mix/rebar3)
MIX_XDG- asks Mix to follow the XDG Directory Specification for its home directory and configuration files. This behaviour needs to be opt-in due to backwards compatibility.
MIX_HOMEhas higher preference than
MIX_XDG. If none of the variables are set, the default directory
~/.mixwill be used
Environment variables that are not meant to hold a value (and act basically as flags) should be set to either
1 or
true, for example:
$ MIX_DEBUG=1 mix compile
Returns the default compilers used by Mix.
Sets Mix debug mode.
The path for local archives or escripts.
Raises a Mix error that is nicely formatted.
Sets the current shell.
Changes the current Mix target to
target.
compilers() :: [atom()]
Returns the default compilers used by Mix.
It can be used in your
mix.exs to prepend or append new compilers to Mix:
def project do [compilers: Mix.compilers() ++ [:foo, :bar]] end
debug(boolean()) :: :ok
Sets Mix debug mode.
debug?() :: boolean()
Returns
true if Mix is in debug mode,
false otherwise.
env() :: atom()
Returns the current config files, often per-environment (see the
Config module for more information).
env(atom()) :: :ok
Changes the current Mix environment to
env.
Be careful when invoking this function as any project configuration won't be reloaded.
This function should not be used at runtime in application code (see
env/0 for more information).
path_for(:archives | :escripts) :: String.t()
The path for local archives or escripts.
raise(binary()) :: no_return()
Raises a Mix error that is nicely formatted.
shell() :: module().
Mix.shell().info("Preparing to do something dangerous...") if Mix.shell().yes?("Are you sure?") do # do something dangerous end
shell(module()) :: :ok
Sets the current shell.
As an argument you may pass
Mix.Shell.IO,
Mix.Shell.Process,
Mix.Shell.Quiet, or any module that implements the
Mix.Shell behaviour.
After calling this function,
shell becomes the shell that is returned by
shell/0.
iex> Mix.shell(Mix.Shell.IO) :ok
You can use
shell/0 and
shell/1 to temporarily switch shells, for example, if you want to run a Mix Task that normally produces a lot of output:
shell = Mix.shell() Mix.shell(Mix.Shell.Quiet) try do Mix.Task.run("noisy.task") after Mix.shell(shell) end
target() :: atom()
Returns the Mix target.
target(atom()) :: :ok
Changes the current Mix target to
target.
Be careful when invoking this function as any project configuration won't be reloaded.
© 2012 Plataformatec
Licensed under the Apache License, Version 2.0. | https://docs.w3cub.com/elixir~1.11/mix | CC-MAIN-2021-10 | refinedweb | 1,200 | 60.41 |
Java usual, expect the same mix of Java and (mostly) related news and articles, but the addition of more experiences and viewpoints.
Java News
Java 16 will be released in March.
- JDK 16: Second Release Candidate
- GraalVM 21.0 Introduces a JVM Written in Java – introduces Java on Truffle (espresso), how to use it and major features you get with it. Currently experimental – not ready for production yet.
- JakartaOne Livestream 2020: Conference Summary – Summary of all the JakartaOne sessions from December 2020 including the Jakarta EE 9 release – the main change is the migration from the javax to jakarta namespace (btw we have a tutorial on creating a Jakarta EE 9 application). Main themes for the live stream were cloud development and the namespace migration.
- GraalVM Inside Oracle Database – "Oracle has added support for GraalVM-based stored procedures that run inside the database".
- JEP draft: Primitive Objects (Preview) – quoting InfoQ: "covers the basic semantics of identify-free primitive objects (previously known as inline classes, previously known as value types)."
- JEP draft: Unify the Basic Primitives with Objects (Preview) – "As a result of this change, all Java values are objects." – retrofitting primitive types into the above JEP, Primitive Objects.
- Nested Record and Array Patterns (Preview) – Building on JEP 394 (pattern matching for instanceof), this will give us record and array patterns to extend pattern matching capabilities.
- Pattern Matching for switch (Preview) – you can see pattern matching is going to be a theme in Future Java.
We just launched the new @snyksec #Java ecosystem survey 2021. This year we partner with @AzulSystems and the final report will be different from previous years.
Read all about it and take the survey. It is super short, only 10 questions 🙂 pic.twitter.com/sKd6xEuv6k
— 🧑🏼💻 Brian Vermeer (@BrianVerm) February 15, 2021
Java Tutorials & Tips
- Faster Charset Decoding – a deep dive on performance improvements related to charset decoders expected in JDK 17.
- Hash ordering and Hyrum’s Law – We’ve all honestly done this and been bitten by it in tests. Ordering isn’t guaranteed and the tests don’t fail so you assume there are no issues.
- Building a layered modular Java application? Watch out for these! – covers some pitfalls Andres ran into while porting a JavaFX application to a layered modular application.
- The best of 2020 : The 10 most popular Java Magazine articles – did I include this because it contains my (Trisha’s) Code Review Antipatterns article? Yes, yes I did.
- 5 Ways to Improve Your Code (video) – from Dave Farley, including a section on refactoring which should have every IntelliJ IDEA user thinking about how to use the automatic refactoring tools to improve their code.
- The Unsafe Class: Unsafe at Any Speed – Unsafe is one of those things the language developers desperately want us not to use, and yet it’s also one of those things that is very handy for extremely niche, but important, cases. Eventually the use cases should be covered by not-unsafe APIs.
Languages, Frameworks, Libraries and Technologies
- Mutation testing: Too good to be true? – Mutation testing is another tool we can call upon when required, but the application of it needs to be handled with care.
- Pipeline Configuration as Code with Kotlin – Good walk-through of using Kotlin in this context, and why it was a good choice of language.
- Pinterest Describes an Architecture for Efficient Retrieval of Hierarchical Documents
- Getting Started with AWS S3 and Spring Boot – This great tutorial takes you through step by step explaining the concepts and configuration required for building a file sharing application, including code samples you can download.
- A Love Letter to Clojure (video & transcript) – Gene Kim (author of the excellent Phoenix Project) takes you on a journey of discovery and optimism with complete honesty throughout.
- Getting Started With RSocket Part 1 & Part 2 – These tutorials take you through the basics of RSocket, how to use it with Spring Boot, and then the RSocket communication models of Fire-and-Forget, Request-Stream, and Channel.
- Spring Boot with Kotlin and RSocket – with step-by-step instructions in IntelliJ IDEA. Really wish this had been around when we created the Reactive Spring Boot tutorial!
- Unit Testing Kotlin Flow – A guide to using Turbine to write unit tests for Kotlin Flows & coroutines.
- From Java to Kotlin and back: Java calling Kotlin – An experience blog of combining Java and Kotlin code in IntelliJ-based IDEs with interesting tips for the interoperability between Java and Kotlin code.
- Virtual Panel: The MicroProfile Influence on Microservices Frameworks – contains background information on MicroProfile. There’s an interesting question about the industry realizing microservices are not a silver bullet and that a monolithic application can be an appropriate solution.
- Micronaut with Kotlin Coroutines – tutorial on how to create a simple Micronaut application and use coroutines.
- Why Namespacing Matters in Public Open Source Repositories – interesting read on why namespacing matters and the consequences of namespacing not being enforced.
- DDD is Overrated – even the article admits this is a clickbait title! But actually what’s discussed in this piece is sensible.
- Opening multiple IntelliJ IDEA modules in the same project – one approach to emulating the multi project workspace approach that Eclipse takes, in IntelliJ IDEA.
- Multik: Multidimensional Arrays in Kotlin – "A lot of data-heavy tasks, as well as optimization problems, boil down to performing computations over multidimensional arrays". It’s a great chance to try it out and share your feedback.
- Primitive Set Operations in Eclipse Collections — Part 2 – following on from part 1. Between them they cover the set operations that will be available on primitive sets for the Eclipse Collections 11.0 release.
📢 Tried Kotlin for server-side, but abandoned using it? Or wanted to start with it but couldn’t?@kotlin invites you to participate in a brief interview and tell them what stops you from using Kotlin. Any reasoning is welcome!
📨 Please apply via the form
— JetBrains IntelliJ IDEA (@intellijidea) February 18, 2021
Culture & Community
What is an OKR? Here are the basics. – Ever wondered what the difference between an Objective and a Key Result is, and more importantly how they come together to form OKRs? This blog explains both with examples and anti-patterns. Highly recommended read especially for folks interested in leadership.
Applying OKRs – Sticking with OKRs, there are some fascinating insights into what OKRs are, and more importantly, are not, in this article as well as some very practical time-boxed advice for applying them.
Uber has lost in the Supreme Court. Here’s what happens next – "Uber drivers in the UK are workers, not contractors". The question for "disruptive" tech products might be, how much are you really disrupting an industry, and how much are you weasling around laws designed to protect people? Reminds me of this other piece on how third party delivery companies are hurting restaurants.
Nasa’s Perseverance rover lands on Mars – A phenomenal achievement and feat of engineering. It will be some time before we can get the samples back to Earth, but the world is watching this mission with great interest. Of course, before the real work starts, they’ll be updating the software that Perseverance is running.
Potentially habitable exoplanet candidate spotted around Alpha Centauri A in Earth’s backyard – Apparently there’s not one, but two planets that may be capable of supporting life in the Alpha Centauri system. More data is needed, but the discovery is something that is likely to keep scientists intrigued for centuries to come.
Angie Jones · The ReadME Project – really enjoyed reading this article. Angie talks about overcoming imposter syndrome early in her career and flourishing – with an impressive 26 patents under her belt. She highlights why diverse teams build better more innovative products. I recommend you go read it.
Black to the Future – Angie Jones – basically a video version of the article above.
Why it’s time to stop telling women to be “more confident” – "women are not stupid. If we were rewarded for being direct in emails, we would be direct in emails. Softened language, a conciliatory attitude, superfluous apologies – these are not the result of low self-esteem but of a calculation: will I be penalised more for appearing abrasive or unconfident?". Could not agree more.
‘Unconscious bias is utter crap’: KPMG staff share shock at UK chair’s Zoom comments – eyeroll. And people say we don’t need to do any more for inclusion.
Finding the “I” Within Inclusion (video & transcript) – 20 minutes on inclusion and why it matters.
The “Learning Styles” Myth Is Still Prevalent Among Educators — And It Shows No Sign of Going Away – I (Trisha) did not know this was a myth, and now I have to change the way I think about teaching.
Grateful People Are More Likely To Obey Commands To Commit Ethically Dubious Acts – this was interesting. And terrifying.
25 Content Creation and Sharing Hacks – Helen’s impressive and ever-growing list of tips to get you going. If you find these useful, let her know, so she can put them into a book!
How to avoid ‘Zoom fatigue’ during the Covid pandemic – top tips. Or… Just Say No.
Hierarchy of Needs through the COVID crisis – this is from the start of the pandemic, but a year in, it’s valuable to reflect upon.
Be Humble – agree with the general sentiment to keep your ego in check and remember folks that are less fortunate.
JetBrains Connect, Ep. 3 – "Python in Africa" (video) – featuring our own Dalia. Yes, OK, this is Java Annotated Monthly, but these challenges exist in the broader technical space.
The one with Trisha Gee (video) – had a lovely chat with Nate Schutta about… everything. Almost felt like being at the bar in a conference.
I see toxic positivity disguised as support a lot on Twitter, so sharing this as a reminder pic.twitter.com/vAJ4NKA4g4
— Sarah Beecroft (@sarah_bean) February 26, 2021
And Finally
A round up of blog posts and videos from IntelliJ IDEA and JetBrains:
- 20 Things Developers Love About IntelliJ IDEA – celebrating IntelliJ IDEA’s 20th Birthday. On that topic, IntelliJ IDEA Conf last week was filled with loads of really useful information and very inspiring. Subscribe to our YouTube Channel to be notified when the talks are uploaded.
- Working with Hibernate/JPA in IntelliJ IDEA (video)
- Creating New Jakarta Persistence/JPA Applications
- Find Your Visual Zen – the different view modes in IntelliJ IDEA. Reader Mode got a lot of love during our conference.
- EAP for a New Product That Brings the “Smarts” of JetBrains IDEs Into Your CI Pipeline – I am asked all the time about how to use IntelliJ IDEA’s analysis and inspections in CI.
- IntelliJ IDEA 2021.1 EAP is still going on (download), the Beta will be available soon!
- Join us for this month’s Live Streams:
- A Simple Approach to Advanced JVM profiling – 17 March
- Server-side With Kotlin Webinar Series, Vol 2 – three upcoming webinars covering reactive programming, asynchronous applications with the Ktor framework, building microservices with Helidon, and other aspects of using Kotlin for server-side development.
Remember that International Women’s Day is March 8th. Every month we work hard to make sure women’s voices are represented in Java Annotated Monthly, but please do make the extra effort to let us (java-advocates@jetbrains.com) know of any women whose work we should be including.
If you have any interesting or useful Java / JVM news to share via Java Annotated Monthly, leave a comment or drop me a message via Twitter. | https://blog.jetbrains.com/idea/2021/03/java-annotated-monthly-march-2021/ | CC-MAIN-2021-43 | refinedweb | 1,914 | 53.92 |
. In the next section, you will get a brief overview of the content of this blog post.
Outline
Before we get into the details on how to create a violin plot in Python we will have a look at what is needed to follow this Python data visualization tutorial. When we have what we need, we will answer a couple of questions (e.g., learn what a violin plot is). In the following sections, we will get into the practical parts. That is, we will learn how to use 1) Matplotlib and 2) Seaborn to create a violin plot in Python.
Requirements
First of all, you need to have Python 3 installed to follow this post. Second, to use both Matplotlib and Seaborn you need to install these two excellent Python packages. Now, you can install Python packages using both Pip and conda. The latter if you have Anaconda (or Miniconda) Python distribution. Note, Seaborn requires that Matplotlib is installed so if you, for example, want to try both packages to create violin plots in Python you can type
pip install seaborn. This will install Seaborn and Matplotlib along with other dependencies (e.g., NumPy and SciPy). Oh, we are also going to read the example data using Pandas. Pandas can, of course, also be installed using pip.
What is a Violin Plot?
As previously mentioned, a violin plot is a data visualization technique that combines a box plot and a histogram. This type of plot therefore will show us the distribution, median, interquartile range (iqr) of data. Specifically, the iqr and median are the statistical information shown in the box plot whereas distribution is being displayed by the histogram.
What does Violin plot show?
A violin plot is showing numerical data. Specifically, it will reveal the distribution shape and summary statitistics of the numerical data. It can be used to explore data across different groups or variables in our datasets.
Example Data
In this post, we are going to work with a fake dataset. This dataset can be downloaded here and is data from a Flanker task created with OpenSesame. Of course, the experiment was never actually run to collect the current data. Here’s how we read a CSV file with Pandas:
Code language: Python (python)Code language: Python (python)
import pandas as pd data = '' df = pd.read_csv(data, index_col=0) df.head()
Now, we can calculate descriptive statistics in Python using Pandas
describe():
Code language: Python (python)Code language: Python (python)
df.loc[:, 'TrialType':'ACC'].groupby(by='TrialType').describe()
Now, in the code above we used loc to slice the Pandas dataframe. This as we did not want to calculate summary statistics on the SubID. Furthermore, we used Pandas groupby to group the data by condition (i.e., “TrialType”). Now that we have some data we will continue exploring the data by creating a violin plot using 1) Matplotlib and 2) Seaborn.
How to Make a Violin Plot in Python with Matplotlib
Here’s how to create a violin plot with the Python package Matplotlib:
Code language: Python (python)Code language: Python (python)
import matplotlib.pyplot as plt plt.violinplot(df['RT'])
n the code above, we used the
violinplot() method and used the dataframe as the only parameter. Furthermore, we selected only the response time (i.e. the “RT” column) using the brackets. Now, as we know there are two conditions in the dataset and, therefore, we should create one violin plot for each condition. In the next example, we are going to subset the data and create violin plots, using matplotlib, for each condition.
Grouped Violin Plot in Python with Matplotlib
One way to create a violin plot for the different conditions (grouped) is to subset the data:
Code language: Python (python)Code language: Python (python)
# Subsetting using Pandas query(): congruent = df.query('TrialType == "congruent"')['RT'] incongruent = df.query('TrialType == "incongruent"')['RT'] fig, ax = plt.subplots() inc = ax.violinplot(incongruent) con = ax.violinplot(congruent) fig.tight_layout()
Now we can see that there is some overlap in the distributions but they seem a bit different. Furthermore, we can see that iqr is a bit different. Especially, the tops. However, we don’t really know which color represents which. However, from the descriptive statistics earlier, we can assume that the blue one is incongruent. Note we also know this because that is the first one we created.
We can make this plot easier to read by using some more methods. In the next code chunk, we are going to create a list of the data and then add ticks labels to the plot as well as set (two) ticks to the plot.
Code language: Python (python)Code language: Python (python)
# Combine data plot_data = list([incongruent, congruent]) fig, ax = plt.subplots() xticklabels = ['Incongruent', 'Congruent'] ax.set_xticks([1, 2]) ax.set_xticklabels(xticklabels) ax.violinplot(plot_data)
Notice how we now get the violin plots side by side instead. In the next example, we are going to add the median to the plot using the
showmedians parameter.
Displaying Median in the Violin Plot Created with Matplotlib
Here’s how we can show the median in the violin plots we create with the Python library matplotlib:
Code language: Python (python)Code language: Python (python)
fig, ax = plt.subplots() xticklabels = ['Incongruent', 'Congruent'] ax.set_xticks([1, 2]) ax.set_xticklabels(xticklabels) ax.violinplot(plot_data, showmedians=True)
In the next section, we will start working with Seaborn to create a violin plot in Python. This package is built as a wrapper to Matplotlib and is a bit easier to work with. First, we will start by creating a simple violin plot (the same as the first example using Matplotlib). Second, we will create grouped violin plots, as well.
How to Create a Violin Plot in Python with Seaborn
Here’s how we can create a violin plot in Python using Seaborn:
Code language: JavaScript (javascript)Code language: JavaScript (javascript)
import seaborn as sns sns.violinplot(y='RT', data=df)
In the code chunk above, we imported seaborn as sns. This enables us to use a range of methods and, in this case, we created a violin plot with Seaborn. Notice how we set the first parameter to be the dependent variable and the second to be our Pandas dataframe.
Again, we know that there two conditions and, therefore, in the next example we will use the
x parameter to create violin plots for each group (i.e. conditions).
Grouped Violin Plot in Python using Seaborn
To create a grouped violin plot in Python with Seaborn we can use the
x parameter:
Code language: Python (python)Code language: Python (python)
sns.violinplot(y='RT', x="TrialType", data=df)
Now, this violin plot is easier to read compared to the one we created using Matplotlib. We get a violin plot, for each group/condition, side by side with axis labels. All this by using a single Python metod! If we have further categories we can also use the
split parameter to get KDEs for each category split. Let’s see how we do that in the next section.
Grouped Violin Plot in Seaborn with Split Violins
Here’s how we can use the
split parameter, and set it to
True to get a KDE for each level of a category:
Code language: Python (python)Code language: Python (python)
sns.violinplot(y='RT', x="TrialType", split=True, hue='ACC', data=df)
In the next and final example, we are going to create a horizontal violin plot in Python with Seaborn and the
orient parameter.
Horizontal Violin Plot in Python with Seaborn
Here’s how we use the
orient parameter to get a horizontal violin plot with Seaborn:
Code language: Python (python)Code language: Python (python)
sns.violinplot(y='TrialType', x="RT", orient='h', data=df)
Notice how we also flipped the
y and
x parameters. That is, we now have the dependent variable (“RT”) as the
x parameter. If we want to save a plot, whether created with Matplotlib or Seaborn, we might want to e.g. change the Seaborn plot size and add or change the title and labels. Here’s a code example customizing a Seaborn violin plot:
Code language: Python (python)Code language: Python (python)
import seaborn as sns import matplotlib.pyplot as plt fig = plt.gcf() # Change seaborn plot size fig.set_size_inches(10, 8) # Increase font size sns.set(font_scale=1.5) # Create the violin plot sns.violinplot(y='RT', x='TrialType', data=df) # Change Axis labels: plt.xlabel('Condition') plt.ylabel('Response Time (MSec)') plt.title('Violin Plot Created in Python')
In the above code chunk, we have a fully working example creating a violin plot in Python using Seaborn and Matplotlib. Now, we start by importing the needed packages. After that, we create a new figure with plt.gcf(). In the next code lines, we change the size of 1) the plot, and 2) the font. Now, we are creating the violin plot and, then, we change the x- and y-axis labels. Finally, the title is added to the plot.
For more data visualization tutorials:
- How to Plot a Histogram with Pandas in 3 Simple Steps
- 9 Python Data Visualization Examples (Video)
- How to Make a Scatter Plot in Python using Seaborn
- Seaborn Line Plots: A Detailed Guide with Examples (Multiple Lines)
Conclusion
In this post, you have learned how to make a violin plot in Python using the packages Matplotlib and Seaborn. First, you learned a bit about what a violin plot is and, then, how to create both single and grouped violin plots in Python with 1) Matplotlib and 2) Seaborn.
| https://www.marsja.se/how-to-make-a-violin-plot-in-python-using-matplotlib-and-seaborn/ | CC-MAIN-2021-25 | refinedweb | 1,601 | 64.51 |
10 Steps to optimize a stored procedure
Introduction
was started growing at a rapid rate day by day, problem started occurring. E-mails started to arrive from the client complaining that the site is performing too slowly (Some of them ware angry mails). The client claimed that, they started losing users.
You started investigating the application. Soon you discovered that, the production database was performing extremely slowly when application was trying to access/update data. Looking into the database you. So, I know why such situation took doing this by sharing my data access optimization experiences and findings with you in this series of articles. I just hope, this might enable you to optimize your data access routines in the existing systems, or, to develop the data access routines in the optimized way in your future projects.
So, let us start our optimization mission in a step-by-step process:
Step1: Apply proper indexing in the table columns in the database
Well, some could argue whether implementing proper indexing should be the first step in performance optimization process in the database. But, I would prefer applying indexing properly in the database in the first place, because of following two reasons:
1. This will allow you to improve the best possible performance in the quickest amount of time in a production system.
2. Applying/creating indexes in the database will not require you to do any application modification and thus will not require any build and deployment.
Of course, this quick performance improvement can be achieved if you find that, indexing is not properly done in the current database. However, if indexing is already done, I would still recommend you to go through this step.
Follow these steps to ensure proper indexing in your database
Make sure that every table in your database has a primary key.
This will ensure that every table has a Clustered index created (And hence, the corresponding pages of the table are physically sorted in the disk according to the primary key field). So, any data retrieval operation from the table using primary key, or, any sorting operation on the primary key field or any range of primary key value specified in the where clause will retrieve data from the table very fast.
Create non-clustered indexes on columns which are:
Following is an example of an index creation command on a table:
CREATE INDEX
NCLIX_OrderDetails_ProductID ON
dbo.OrderDetails(ProductID)
Alternatively, you can use the SQL Server Management Studio to create index on the desired table
Step2 : Create appropriate covering indexes
So, you have created, comparing to the situation where no index created on the foreign key column (ProductID) in which case, a full table scan
1. The Sales table has a non-clustered index on ProductID column. So, it “seeks” the non-clustered index tree for finding the entry that contains ProductID=112
2. The index page that contains the entry ProductID = 112 also contains the all Clustered index keys (All Primary key values, that is SalesIDs, that have ProductID = 112 assuming that primary key is already created in the Sales table)
3. For each primary key (400 here), the SQL server engine “seeks” into the clustered index tree to find the actual row locations in the corresponding page.
4. For each primary key, when found, the SQL server engine selects the SalesDate and SalesPersonID column values from the corresponding rows. the step 3 and step 4 in the above steps, and, thus, would be able to select the desired results even faster just by “seeking” into the non clustered index tree for ProductID column, and, reading all three mentioned column values directly from that index page.
Fortunately, there is a way to implement this feature. This is what is called “Covered index”. You create “Covered indexes” in table columns to specify what are the additional column values the index page should store along with the clustered index key values (primary keys). Following is the example of creating a covered index on the ProductID column.
Use Database Tuning Advisor’s help while creating covered index
We all know, when result. But, how can we do this?
The answer is, we have to simulate the production server’s load in the test server, and then need to create appropriate indexes and test those. Only then, if the newly created indexes improves performance in the test environment, these will most likely to improve performance in the production environment.
Doing this should be hard, but, fortunately, we have some friendly tools to do this. Follow these instructions:
1. Use SQL profiler to capture traces in the production server. Use the Tuning template (I know, it is advised not to use SQL profiler in the production database, but, sometimes you have to use it while diagnosing performance problem in the production). If you are not familiar with this tool, or, if you need to learn more about profiling and tracing using SQL profiler, read.
2. Use the trace file generated in the previous step to create a similar load in the test database server using the Database tuning advisor. Ask the Tuning advisor to give some advice (Index creation advice most of the cases). You are most likely to get good realistic (index creation) advice from the tuning advisor (Because, the Tuning advisor loaded the test database with the trace generated from the production database and then tried to generate best possible indexing suggestion) . Using the Tuning advisor tool, you can also create the indexes that it suggests. If you are not familiar with the Tuning advisor tool, or, if you need to learn more about using the Tuning advisor, read.
Step3 : Defragment indexes if fragmentation occurs
OK, you created all appropriate indexes in your tables. Or, may be, indexes are already there in your database tables. But, you might not still get the desired good performance according to your expectation.
There is a strong chance that, index fragmentation have occurred.
What is index fragmentation?. So, data retrieval operations perform slow.
Two types of fragmentation can occur:
Internal Fragmentation: Occurs due to the data deletion/update operation in the index pages which ends up in distribution of data as sparse matrix in the index/data pages (create lots of empty rows in the pages). Also results in increase of index/data pages that increase query execution time.
External Fragmentation: Occurs due to the data insert/update operation in the index/data pages which ends up in page splitting and allocation of new index/data pages that are not contiguous in the file system. That reduces performance in determining occurred or not?
Execute the following SQL in your database (The following SQL will work in SQL Server 2005 or later databases. Replace the database name ‘Adventure ‘AdventureWorks’ database as follows:
Analyzing the result, you can determine where index fragmentation have occurred, using the following rules:
How to defragment indexes? ‘ALL’ keyword in the above queries. Alternatively, you can also use the SQL Server Management Studio to do index defragmentation.
When to reorganize and when to rebuild indexes?
You should “Reorganize” indexes when the External Fragmentation value for the corresponding index is in between 10-15 and Internal Fragmentation value is in between 60-75. Otherwise, you should rebuild indexes.
One important thing with index rebuilding is, while rebuilding indexes for a particular table, the entire table will be locked (Which does not occur index rebuild command given above). This will rebuild the indexes for the table along with making the table available for transactions.
Step4: Move TSQL codes from application into the database server
I know you may not like this suggestion at all. You might have used an ORM that does generate all the SQLs for you on the fly. Or, you or your team might have a “principle” of keeping SQLs in your application codes (In the Data access layer methods). But, still, if you need to optimize the data access performance, or, if you need to troubleshoot a performance problem in your application, I would suggest you to move your SQL codes into your database server (Using Stored procedure, Views, Functions and Triggers) from your application. Why? Well, I do have some strong reasons for this recommendation:
Despite the fact that indexing (In Step1 to Step3) will let you troubleshoot the performance problems in your application in a quick time (if properly done), following this step 4 might not give you a real performance boost instantly. But, this will mainly enable you to perform other subsequent optimization steps and apply different problem in a production system where lots of transactions take place each second, and where too many concurrent database connections are there, in order to optimize your application’s performance you might have to re-think with your ORM based data access logics. It is possible to optimize an ORM based data access routines, but, it is always true that if you implement your data access routines using the TSQL objects in your database, you have the maximum opportunity to optimize your database.
If you have come this far while trying to optimize your application’s data access performance, come on, convince your management and purchase some time to implement a TSQL object based data operational logic. I can promise you, spending one or two man-month doing this might save you a man-year in the long run!
OK, let’s assume that you have implemented your data operational routines using the TSQL objects in your database. So, having done this step, you are done with the “ground work” and ready to start playing. So, let’s move towards the most important step in our optimization adventure. We are going to re-factor our data access codes and apply the best practices.
No matter how good indexing you apply in your database, if you use poorly written data retrieval/access logic, you are bound to get slow performance.
We all want to write good codes, don’t we? While we write data access routines for a particular requirement, we really have lots of options to follow for implementing particular data access routines (And application’s business logics). But, most of the cases, we have to work in a team with members of different calibers, experience and ideologies. So, while at development, there are strong chances that our team members may write codes in different ways and some of them miss following the best practices. While writing codes, we all want to “get the job done” first (Most of the cases). But, while our codes run in production, we start to see the problems.
Time to re-factor those codes now. Time to implement the best practices in your codes.
I do have some SQL best practices for you that you can follow. But, I am sure that you already know most of them. Problem is, in reality, you just don’t implement these good stuffs in your code (Of course, you always have some good reasons for not doing so). But what happens, at the end of the day, your code runs slowly and your client becomes unhappy.
So, knowing the best practices is not enough at all. The most important part is, you have to make sure that you follow the best practices while writing TSQLs. This is the most important thing.
SELECT column_list FROM table WHERE 0 < (SELECT count(*) FROM table2 WHERE ..)
Instead, use
SELECT column_list FROM table WHERE EXISTS (SELECT * FROM table2 WHERE ...).
-Use inline sub queries to replace User Defined Functions. -Use correlated sub queries to replace Cursor based codes. -If procedural coding is really necessary, at least, use a table variable Instead of a cursor to navigate and process the result set.
For more info on "set" and "procedural" SQL , see Understanding “Set based” and “Procedural” approaches in SQL.
SELECT COUNT(*) FROM dbo.orders
This query will perform full table scan to get the row count.
SELECT rows FROM sysindexes
WHERE id = OBJECT_ID('dbo.Orders') AND indid < 2
Unless really required, try to avoid the use of dynamic SQL because:
Full text search always outperforms the LIKE search.
And, that’s not the end. There are lots of best practices out there! Try finding some of them clicking on the following URL:
Remember, you need to implement the good things that you know, otherwise, you knowledge will not add any value to the system that you are going to build. Also, you need to have a process for reviewing and monitoring the codes (That are written by your team) whether the data access codes are being written following the standards and best practices.
In an ideal world, you always prevent diseases rather than cure. But, in reality you just can’t prevent always. I know your team is composed of brilliant professionals. I know you have good review process, but still bad codes are written, still poor design takes place. Why? Because, no matter what advanced technology you are going to use, your client requirement will always be way much advanced and this is a universal truth in the Software development. As a result, designing, developing and delivering a system based on the requirement will always be a challenging job for you.
So, it’s equally important that you know how to cure. You really need to know how to troubleshoot a performance problem after it happens. You need to learn the ways to analyze the TSQLs, identify the bottlenecks and re-factor those to troubleshoot the performance problem. To be true, there are numerous ways to troubleshoot database and TSQL performance problems, but, at the most basic levels, you have to understand and review the execution plan of the TSQLs that you need to analyze.
Whenever you issue an SQL in the SQL Server engine, the selects one that is likely to be the best execution plan most of the cases.
Did you know? You can use the SQL Server Management Studio to preview and analyze the estimated execution plan for the query that you are going to issue. After writing the SQL in the SQL Server Management Studio, click on the estimated execution plan icon (See below) to see the execution plan before actually executing the query.
(Note: Alternatively, you can switch the Actual execution plan option “on” before executing the query. If you do this, the Management Studio will include the actual execution plan that is being executed along with the result set in the result window)
Each icon in the execution plan graph represents one:
I found an article that can help you further understanding and analyzing the any optimization, most of the cases, the first thing you would like to do is to view the execution plan. You will most likely to quickly identify the area in the SQL that is creating the bottlenecks in the overall SQL.
Keep watching for the following costly operators in the execution plan of your query. If you find one of these, you are likely to have problems in your TSQL and you need to re-factor the TSQL to try to improve performance.
Table Scan: Occurs when the corresponding table does not have a clustered index. Most likely, creating clustered index or defragmenting indexes will enable you to get rid of it.
Clustered Index Scan: Sometimes considered equivalent to Table Scan. Takes place when non-clustered index on an eligible column is not available. Most of the cases, creating non-clustered index will enable you to get rid of it.
Hash Join: Most expensive joining methodology. This takes place when the joining columns between two tables are not indexed. Creating indexes on those columns will enable you to get rid of it.
Nested Loops: Most cases, this happens when a non-clustered index does not include (Cover) a column that is used in the SELECT column list. In this case, for each member in the non-clustered index column the database server has to seek into the clustered index to retrieve the other column value specified in the SELECT list. Creating values ‘Caps’ for the year 2009:
exec uspGetSalesInfoForDateRange ‘1/1/2009’, 31/12/2009,’Cap’
Accordingly, Mr. Tom was assigned to optimize the Stored Procedure.
Following is a stored procedure that is somewhat close to the original one (I can’t include the original stored procedure for proprietary issue you know). are being queried in the Stored Procedure. He had a quick look into the query and identified the fields that the tables should have indexes on (For example, fields that have been used in the join queries, WHERE conditions and ORDER BY clause). Immediately he found that, several indexes are missing on some of these columns. For example, indexes on following two columns were missing:
OrderDetails.ProductID
OrderDetails.SalesOrderID
He created non-clustered indexes on those two columns and executed the stored procedure as follows:
exec uspGetSalesInfoForDateRange ‘1).
Mr. Tom’s next step was to see the execution plan in the SQL Server Management Studio. He did this by writing the ‘exec’ statement for the stored procedure in the query window and viewing the “Estimated execution plan”. (The execution plan is not included here as it is quite a big one that is not going to fit in screen).
Analyzing the execution plan he identified some important scopes for improvement
Being, 2 of the existing indexes (In the corresponding tables used in the TSQL in the Stored Procedure) had fragmentation that were responsible for the Table scan operation. Immediately, he defragmented those 2:
ALTER FUNCTION [dbo].[ufnGetLineTotal]
(
@SalesOrderDetailID int
)
RETURNS money scopes Mr. Tom decided to take a look at the column types in the SELECT list in the TSQL. Soon he discovered that one Text column (Products.DetailedDescription) were included in the SELECT list. Reviewing the application code Mr. Tom found that this column values were not being processed by the application immediately. Few columns in the result set were being displayed in a listing page in the application, and, when user clicks user sees the detail page for an item in the item list. He also converted those two “Text” columns to “VARCHAR(MAX) columns and that enabled him to use the len() function on one of these two columns in the TSQLs in other places (That also allowed him to save some query execution time because, he was calculating the length using len(Text_Column as Varchar(8000)) in the earlier version of the code.
What’s next? All the optimization steps so far reduced the execution time to 6 seconds. Comparing to the execution time of 50 seconds before optimization, this is a big achievement so far. But, Mr. Tom thinks the query could have further improvement scopes. Reviewing the TSQLs Mr. Tom didn’t find any significant option left for further optimization. So, he indented and re-arranged the TSQL (So that each individual query statement (Say, Product.ProductID = OrderDetail.ProductID) is written in a particular line) and starts executing the Stored Procedure again and again by commenting out each line that he suspects!
It seemed that, having done with all the optimizations so far, the LIKE searches were taking the most amount of time in the TSQL. After carefully looking at the LIKE search conditions, Mr. Tom became pretty sure that the LIKE search based SQL could easily be implemented using the!
Great achievement, isn’t it?
You might have written application codes where you select a result set from the database, and, do a calculation for each rows in the result set to produce the ultimate information to show in the output. For example, you might have a query that retrieves Order information from the database and in the application you might have written codes to calculate the total Order prices by doing arithmetic operations on Product and Sales data). But, why don’t you do all these large number of rows and the computed column. The situation might get worse if the computed column is specified in the WHERE clause in a SELECT statement. In this case, to match the specified value in the WHERE clause, the database engine has to calculate computed column’s value for each row in the table. This is a very inefficient process because it always requires a table or full clustered index scan.
So, we need to improve performance on computed columns. How? The solution is, you need to create index on the computed columns. When an index is built on a computed column, SQL Server calculates the result in advance, and builds an index over them. Additionally, when the corresponding column values are updated (That the computed column depends on), the index values on computed column are also updated. So, while executing the query, the database engine does not have to execute the computation formula for every row in the result set. Rather, the pre-calculated values for the computed column are just get selected and returned from the index. As a result, creating index on computed column gives you excellent performance boost.
Note : If you want to create index on a computed column, you must make sure that, the computed column formula does not contain any “nondeterministic” function (For example, getdate() is a nondeterministic function because, each time you call it, it returns a different value).
Did you know that you can create indexes on views (With some restrictions)? Well, if you have come this far, let us learn the indexed Views!
As we all know, Views are nothing but compiled SELECT statements residing as the objects in the database. If you implement your common and expensive TSQLs using Views, it’s obvious that, you can re-use these across your data access routines. Doing this will enable you to join the Views with the other tables/views to produce an output result set, and, the database engine will merge the view definition with the SQL you provide, and, will generated an execution plan to execute. Thus, sometimes Views allow you to re-use common complex SELECT queries across your data access routines, and also let the database engine re-use execution plans for some portion of your TSQLs.
Take my words. Views don’t give you any significant performance benefits. “remembers” the result set for the SELECT query it is compost function, and when data and the base table do not change often.
CREATE VIEW dbo.vOrderDetails
WITH SCHEMABINDING
AS
Wait! Don’t get too much exited about indexed Views. You can’t always create indexes on Views. Following are the restrictions:
So, straight-forward way. To create index on a UDF, you have to create a computed column specifying an UDF as the formula and then you have to create index on the computed column field.
For example,
CREATE FUNCTION [dbo.ufnGetLineTotal]
-- Add the parameters for the function here
@UnitPrice [money],
@UnitPriceDiscount [money],
@OrderQty [smallint]
WITH SCHEMABINDING
return (((@UnitPrice*((1.0)-@UnitPriceDiscount))*@OrderQty))
END
We already have seen that we can create index on computed columns to retrieve faster results on computed columns. But, what benefit could be achieved by using UDF in the computed columns and creating XML column is created, SQL Server shreds the XML content and creates several rows of data that include information like element and attribute names, the path to the root, node types and values, and so on. So, creating the primary index enable the SQL server to support XQuery requests more easily.
Following is the syntax for creating primary XML index:
CREATE PRIMARY XML INDEX
index_name
ON <object> ( xml_column )
Creating the primary XML indexes improves XQuery performance because the XML data is shredded already. But, SQL Server still needs to scan through the shredded data to find the desired result. To further improve query performance, the secondary XML index should be created on top of primary XML indexes.
Three types of secondary XML indexes are there. These are:
Following is the syntax for creating the secondary XML indexes
CREATE XML INDEX
ON <object> ( xml_column )
USING XML INDEX primary_xml_index_name
FOR { VALUE | PATH | PROPERTY }
Please note that, the above guidelines are the basics. But, creating indexes blindly on each and every tables on the mentioned columns may not always result in performance optimization, because, sometimes, you may find that, creating indexes on some particular columns in some particular tables resulting in making the data insert/update operations in that table slower (Particularly, if the table has a low selectivity on a column)., Also if the table is a small one containing small number of rows (Say, <500), creating times), optimization techniques so far, if you find that some of your data retrieval operations still not performing efficiently, you need to consider applying some sort of de-normalizations. So, the question is, how should you apply de-normalization and why this would improve performance?
Let’s say we have two tables OrderDetails(ID,ProductID,OrderQty) and Products(ID,ProductName) that stores Order Detail information and Product Information respectively. Now to select the Product names with their ordered quantity for a particular order, we need to issue the following query that requires joining the OrderDetails and Products table.
SELECT Products.ProductName,OrderQty
FROM OrderDetails INNER JOIN Products
ON OrderDetails.ProductID = Products.ProductID
WHERE SalesOrderID = 47057
Now, if these two tables contain huge number of rows, and, if you find that, the query is still performing slowly even after applying OrderDetails and Products Table). So, while we insert/update the ProductName field in Products table, we also have to do the same in the OrderDetails Table. Additionally, doing this de-normalization will increase the overall data storage.
So, while de-normalizing, we have to do some trade-offs between the data redundancy and select operation’s performance. Also, we have to re-factor some of our data insert/update operations after applying the de-normalization. Please be sure to apply de-normalization only if you have applied all other optimization steps and yet operations on a specified time each day. If you do this, the periodic data retrieval operation than previous. The reason is obvious, while the SELECT query executes, the database engine does not have to process the expensive calculation logic any more for each row.
The SQL Profiler tool is perhaps the most well-known performance troubleshooting tool in the SQL server arena. Most of the cases, when a performance problem is reported, this is the first tool that you are going to launch to investigate the problem.
As you perhaps already know, the SQL Profiler is a graphical tool for tracing and monitoring the SQL Server instance, mostly used for profiling and measuring performance of the TSQLs that are executed on the database server. You can capture about each event on the server instance and save event data to a file or table to analyze later. For example, if the production database perform slowly, you can use the SQL Profiler to see which stored procedures are taking too much time to execute.
There is a 90% chance that you already know how to use it. But, I assume lots of newbie’s out there reading this article might feel good if there is a section on basic usage of SQL Profiler (If you know this tool already, just feel free to skip this section). So, here we put a brief section:
Start working with the SQL Profiler in the following way
SELECT TextData,Duration,…, FROM Table_Name ORDER BY
Duration DESC
Voila! You just identified the most expensive TSQLs in your application in a quick time.
Most of the cases, the SQL profiler tool is used to trace the most expensive TSQLs/Stored Procedures in the target database to find the culprit one that is responsible for performance problem (Described above). But, the tool is not limited to provide only TSQL duration information. You can use many powerful features of this tool to diagnose and troubleshoot different kinds of problems that could occur due to many possible reasons.
When you are running the SQL Profiler, there are two possibilities. Either you have a reported performance related issue that you need to diagnose, or, you need to diagnose any possible performance issue in advance so that you can make sure you system would perform blazing fast in the production after deployment.
Following are some tips that you can follow while using the SQL Profiler tool:
Most of the times theàTemplatesàNew Template and specifying the Template name and events and columns. Also, you can select an existing template and modify it according to your need.
Did you know that you can listen to these two interesting events using the SQL profiler?
Imagine a situation where you have done all possible indexing in your test database, and after testing, you have implemented the indexes in the production server. Now suppose, on a sudden, you start getting error mails stating that deadlocks are occurring in the database (With exception message from database containing database level error codes). You need to investigate and find the situation and corresponding set of TSQLs that are responsible for creating the deadlock in the production database. How would you carry this out?
SQL profiler gives you possible ways to investigate it. the deadlock took problem a Replay trace. You can use a TSQL_Replay Trace template to capture events in the production server and save that trace in a .trace file. Then, you can replay the trace on test server to re-generate and diagnose problems.
To learn more about TSQL Replay trace, see
The Database tuning advisor is a great tool that can give you good tuning suggestions to enhance your database performance. But, to get a good and realistic suggestion from the tuning advisor, you need to provide the tool with “appropriate load” that is similar to the production environment. That is, you need to execute the same the set of TSQL’s and open the same number of concurrent connections in the test server and then run the tuning advisor there. The SQL Profiler lets you capture the appropriate set of events and columns (for creating load in the tuning advisor tool) by the Tuning template. Run the profiler using the Tuning template, capture the traces and save it. Then, use the tuning trace file for creating server. performance problem) in the production server to view the actual execution plan for lots of reasons. You can of course take a look at the estimated execution plan for a similar query, but, this execution plan might not reflect you the true execution plan that is used in reality in a fully loaded production database.The find out the difference in them very easily.
When you encounter performance related problems in your database, the SQL Profiler would enable you to diagnose and find out the reasons behind the performance issues most of the cases. But, sometimes the Profiler alone cannot help you identifying the exact cause of the problems.
For example, issues that are creating a bottleneck situation in the production server. How would you diagnose this problem then?
The Performance Monitoring Tool (Known as Perfmon) comes to your aid in these kinds of situations. Performance Monitor is a tool (That is built in within the Windows OS) gathers statistical data related to hardware and software metrics from time to time.
When you issue a TSQL to execute in the database server, there are many stakeholders participating in the actions to execute the query and return performance of each individual components the Windows. While the SQL Server gets installed, Performance counters for SQL server also get installed. Hence, these counters are available when you define a performance counter log.
Follow these steps to create a performance counter log:
Specify log file name and press OK.
The SQL Profiler can give you information about the long running queries, but, it cannot provide you with the context information to explain the reason for long query execution time.
On the other hand, the Performance monitor tool gives you statistics regarding production server to execute, but, takes shorter time in test server, that indicates the test server may not have the same amount of load, environment and query execution context as the production server has. a same time period can only be correlated).
Correlating these two tool’s output can help
Create the performance counter log, but, don’t start it.
I bet, you’ll surely find correlating these two tools output extremely interesting and handy.
When an SQL Server database is created, the database server internally creates a number of files in the file system. Every database related object that gets created later in the database are actually being stored inside these files.
An SQL Server database has following three kinds of files
When an SQL Server database is created, by default, the primary data file and the transaction log file is created. You can of course modify the default properties of these two files.
Database files are logically grouped for better performance and improvement of administration on large databases. When a new SQL Server database is created, the primary file group is created and the primary data file is included in the primary file group. Also, the primary group is marked as the default group. As a result, every newly created user objects are automatically placed inside the primary file group (More specifically, inside the files in the primary file group).
If you want your user objects (Tables/Views/Stored Procedures/Functions and others) to be created in the database performance. Here are some of the best practices you can follow:
Table partitioning means nothing but splitting a large table into multiple smaller tables so that, queries has to scan less amount data while retrieving. That is “Divide and conquer”.
When you have a large (In fact, very large, possibly having more than millions of rows) table in your database and when you see that, querying on this table is executing slowly, you should consider portioning this table (Of course, after making sure that all other optimization steps are done) to improve performance.
Following two following options are available to partition a table.
Suppose, we have a table containing 10 millions of rows. For easy understandability, let’s assume that, the table has an auto-increment primary key field (Say, ID). So, we can divide the table’s data into 10 separate portioning tables where each partition will contain 1 million rows and the partition will be based upon the value of the ID field. That is, First partition will contain those rows which have a primary key value in the range 1-1000000, in smaller boxes. Hence, this is called horizontal partitioning.
Suppose, we have a table having upon in different thinner partitions is called vertical partition
Another good criteria for applying vertical partitioning could be to partition the Indexed columns and non-indexed columns into separate tables. Also, vertical partitioning could be done by splitting the LOB or VARCHARMAX columns into separate tables.
Like the horizontal partitioning, vertical partitioning also allows to improve query performance (Because, queries now have to scan less data pages internally, as the other column values from the rows ‘1999’ and adding a secondary data file ‘C:\OrderDB\1999.ndf' to this file group. We did this, because, we would like to put our table partitions into separate files in separate file groups.
Using the SQL command above, create another 3 file groups ‘2000’,’2001’ and ‘2002’. As you perhaps could imagine already, each of these file group would store a year’s order data inside their corresponding data files.
A partition function is an object that defines the boundary points for partitioning data. Following command creates a partition function
CREATE PARTITION FUNCTION FNOrderDateRange (DateTime) AS
RANGE LEFT FOR VALUES ('19991231', '20001231', '20011231')
The above partition function specifies that, the Order date column having value between
DateTime <= 1999/12/31 would fall into 1st partition.DateTime > 1999/12/31 and <= 2000/12/31 would fall info 2nd partition.DateTime > 2000/12/31 and <= 2001/12/31 would fall info 3rd partition.DateTime > 2001/12/31 would fall info 4th partition.
The RANGE LEFT is used to specify that, the boundary value should fall into left partition. For example, here the boundary value 1999/12/31 is falling into the 1st partition (With all other dates less than this value) and the next value is falling into the next partition. If we specify RANGE RIGHT, then, the boundary value would fall into the right partition. So, in this example, the boundary value 2000/12/31 would fall into the 2nd partition and any date less than this value would fall into the 1stpartition.
The partition scheme maps the partitions of a partitioned table/index to the file groups that will be used to store the partitions.
Following command creates a partition schema
CREATE PARTITION SCHEME OrderDatePScheme AS PARTITION FNOrderDateRange
TO ([1999], [2000], [2001], [2002])
Here, we are specifying that,
The 1st partition should go into the ‘1999’ file groupThe 2nd partition should go into the ‘2000’ file groupThe 3rd partition should go into the ‘2001’ file groupThe 4th partition should go into the ‘. The statement. Assuming that, the PK_Orders is the primary key of the table, use the following command to drop the primary key which will eventually drop the clustered index from the table. detail level explanation on partitioning).
SQL SERVER – 2005 – Database Table Partitioning Tutorial – How to Horizontal Partition Database Table (A very simple and easily understandable tutorial on partitioning).
We all know that, In order to better manage the DBMS objects (Stored procedures, Views, Triggers, Functions etc), it’s important to follow a consistent structure while creating these. But, for many reasons (Due to time constraints mainly), most of the times we fail to maintain a consistent structure while developing these DBMS objects. So, when the codes are debugged later for any performance related issue or for any reported bug, it becomes a nightmare for any person to understand the code and find the possible causes.
To help you In this regard, I have developed some TSQL templates that you can use to develop the DBMS objects using a consistent structure within a short amount of time.
I’ve also imagined that, there will be a person reviewing the DBMS objects and routines created by the team. The review process helps identifying the issues (Say, best practices) that generally are missed by the developers due to work pressure or other issues, and, the templates have a “REVIEW” section where the reviewer can put review information along with comments.
I’ve attached some sample templates of different common DBMS objects in SQL Server. Here these are:
At first, you need to create the templates in your SQL Server Management Studio. To do this, you need to download the attached templates and follow the steps given below. I’ve used the Template_StoredProcedure.txt for creating the Stored Procedure template. You can follow the same procedure to create other templates.
Well, after creating all the templates in the SQL Server Management Studio, it’s time to use them. I am showing how to use the Stored Procedure template here, but, the procedure is the same for all other templates
You can follow the above steps to create other DBMS objects (Functions, Views, Triggers etc).
I can promise, you can create the DBMS objects using the templates now in an easy manner, within a quick amount of time.
C#, BI, Sql server 2005 Developer. | http://www.c-sharpcorner.com/Blogs/2066/how-to-optimize-a-stored-procedure.aspx | CC-MAIN-2014-10 | refinedweb | 6,572 | 51.28 |
Working with Images in PDF using C#
Images can be quite a complex topic in PDF format. A wide variety of manipulations with images awaits the user when he is faced with the work of PDF documents. We are used to the fact that pictures can only be added or removed from files, but the Aspose.PDF library will also allow you to set image size, replace images, extract images, search, and get Images from PDF Document and etc.
How to add image to PDF? You will receive an answer to the most popular question about pictures in PDF with Aspose.PDF.
Aspose.PDF for .NET is a smart and efficient tool for working with digital documents that lets you quickly import and place any graphical object in an existing PDF. Using our C# library is also a helpful option if you need to insert a chart into a report, add a floor plan overlay to a project, or just include a photo on your CV. If you are looking for an advanced way to insert and edit images in a PDF document, we highly recommend learn next articles for resolving your tasks.
You are able to do the following:
- Add Image to Existing PDF File - add images and references of a single image in PDF document, after that control quality.
- Delete Images from PDF File - check code snippet for deleting images from PDF file.
- Extract Images from PDF File - use Images collection for extract images from PDF file.
- Get the Resolution and Dimensions of Embedded Images - use the operator classes in the Aspose.PDF namespace which provide the capability to get resolution and dimension information.
- Working with Image Placement - it is possible to get an image’s resolution and position in a PDF document.
- Search and Get Images from PDF Document - you can get an image from an individual page and search among images on all pages with C#.
- Replace Image in Existing PDF File - check our code snippet, it shows you how to replace an image in a PDF file.
- Set Image Size - C# library allows you to set the size of an image.
- Set Default Font Name - Setting Default Font Name for conversion process.
- Generate Thumbnail Images from PDF Documents - next article shows how to generate thumbnail images from PDF documents using first the Acrobat SDK and then Aspose.PDF.
- Support for DICOM Images - Aspose.PDF for .NET supports special medical graphic standard of images. Aspose.PDF for .NET allows you to convert DICOM and SVG images. Please check Convert DICOM to PDF section. | https://docs.aspose.com/pdf/net/working-with-images/ | CC-MAIN-2022-27 | refinedweb | 427 | 62.17 |
@FlippedCodingMilecia
Software/Hardware Engineer | International tech speaker | Random inventor and slightly mad scientist.
What is a container.
What containers have to do with DevOps.
Working with containers
Making a container in Docker means that you’re starting with a Docker image. As an example, say you want to deploy a React app in a Docker container. You know that you need a specific version of `node` and you know where all of your files are. So you just have to write the image so that Docker can utilize these things.
When you see Docker images, it looks like they’re written similar to bash commands but it’s not the same. Think of images as step by step instructions that Docker needs to make your files correctly. Here’s an example of a Docker container that builds a React app.
# pull the official base image FROM node:13.12.0-alpine # set the working directory WORKDIR /app # add `/app/node_modules/.bin` to $PATH ENV PATH /app/node_modules/.bin:$PATH # install app dependencies COPY package.json ./ COPY package-lock.json ./ RUN npm install --silent RUN npm install [email protected] -g --silent # add app COPY . ./ # start app CMD ["npm", "start"]
These are all instructions that you’re probably used to running locally or executing in some other environment. Now you’re doing the same thing, just in an environment “bubble”. It’ll use the version of `node` specified in the image and it’ll use the directories specified in the image. You won’t have to check and change all of these things whenever you need to run the code.
Including containers in your CI/CD pipeline
Here’s an example of a container being built and run using Conducto as the CI/CD tool. This is running the Docker image we created above.
import conducto as co def cicd() -> co.Serial: image = co.Image("node:current-alpine", copy_dir=".") make_container_node = co.Exec("docker build --tag randomdemo:1.0 .") run_container_node = co.Exec("docker run --publish 8000:8080 --detach --name rd randomdemo:1.0") pipeline = co.Serial(image=image, same_container=co.SameContainer.NEW) pipeline["Build Docker image"] = make_container_node pipeline["Run Docker image"] = run_container_node return pipeline if __name__ == "__main__": co.main(default=cicd)
Other considerations
Remember that if you’re still working with a monolith, it’s going to take some time to get CI/CD ready. One small bug can take down the entire application and unit tests aren’t the easiest things to write. So don’t get too down if the upfront investment seems like a lot because it can be.
The payoff is that later on, everything will run so seamlessly that you forget DevOps is in place until something breaks. That’s way better than dealing with angry support calls, stressing about deployments, and decreasing customer trust..
read original article here | https://coinerblog.com/ever-wondered-why-we-use-containers-in-devops-l5113wif/ | CC-MAIN-2020-45 | refinedweb | 471 | 58.69 |
;
True, but typically pointers aren't used in such a simple manner. We just showed this to illustrate the use of pointer syntax.
Let's look at both pass by value and pass by reference to make sure we understand the difference. There is a little example in the C++ Syntax Web Pages (the section on Pointers) that illustrates how parameters are passed by value. Here's what that looks like:
int a = 5; int b = 9; exchange(a,b); // main pgm function call ... void exchange(int x, int y) // pass by value { int temp; temp = x; x = y; y = temp; return; }Simple, direct - right? Well yes, but the values of a and b in the main program have not been changed! If that is what you really wanted to do, you should have used pointers to pass the parameters by reference.
To do this, you need to change
the function prototype and header to
void exchange(int & x, int & y)
Here is what the whole program looks like.
#include <string.h> #include <iostream> using namespace std; void exchange (int& x, int& y); int main () { int a = 5; int b = 9; cout << "This program exchanges 2 values." << endl; cout << "Values before the exchange:" << endl; cout << "a= " << a << " b= " << b << endl; exchange(a, b); // code that calls the function cout << "Values after the exchange:" << endl; cout << "a= " << a << " b= " << b << endl; } // function for passing by reference void exchange (int& x, int& y) { int temp; temp = x; x = y; y = temp; return; } // end exchange
struct STUDENT // define the structure { char name[20]; guru's after you delete the associated dynamic data space. e.g.
TmpPtr = NULL; WeightPtr = NULL;
Segmentation fault - core dump.This is a really ugly way of punting you and your program out of computer memory. Unix guru's vi, you can search for a particular string (such as the name of a pointer) by entering: /search_string/
Now, read this description carefully as you proceed through each step.
cp /net/data/ftp/pub/class/170/ftp/cpp/struct.cpp struct.cpp
#include <string.h> #include <iostream> using namespace std; struct STUDENT { char name[20]; int id; int mark[3]; }; void InitStudent(STUDENT* StuPtr);You need to add a line to the main function to declare an instance of STUDENT, and another line to call the new function InitStudent feeding it the address of (that was a hint) the new instance.
NOTICE: You've already got the code in the main program to print out an instance. Just move that code to a function and modify it so that it uses pointers.
Work in the main function here - don't worry about new functions.
Don't forget a call to that function you created to display the contents of an instance.Don't forget a call to that function you created to display the contents of an instance.
Once you have the last step completed and debugged, you will see that this next step combines the use of structure pointers and dynamic data arrays.
You need to add statements to calculate the weighted mark for the scores for the new student. (The formula would be something like this: ((m1 * wt1) + (m2 * wt2) + (m3 * wt3)) / 100) Of course you'd likely implement that in a loop.
The algorithm for this bit of code is:
STUDENT * sPtr = & NewStudent;
There, that took you through a few steps to practice these new tools. If you didn't get time to finish this off during the lab period, be sure to finish it off before next week's lab. Remember you can go to CL119 during posted office hours for help. You can also email your lab instructor if you have a specific question. It's important that you master these tools in this simple exercise so that you can use them easily in the more elaborate routines you will need for class assignments. | http://www.cs.uregina.ca/Links/class-info/170/10-pointers/Pointers/Longpointers.html | CC-MAIN-2017-43 | refinedweb | 648 | 67.08 |
PyGame is a popular 2D game framework for the Python programming language available at. PyGame has been under active development since the year 2000 and continues to see updates to this day. Today we are going to look at the basics of getting up and running with PyGame.
First obviously you are going to need to have Python 3.x installed and configured on your machine. The Python programming langauge is available for all major platforms and can be downloaded here, any 3.x version should suffice. When you install make sure that python is installed into your system path when prompted. After installation is complete you should be able to test Python by opening a command line and typing:
python –version
And the results should look something like:
Assuming that worked correctly, next we need to make that pip is up to date. Pip is a python package manager and should have installed automatically when you installed python. To do this, on Windows run:
python -m pip install -U pip
If you are on Linux or Mac, you can omit the python -m bit. This will upgrade pip to the most current version. Now it’s time to install PyGame and you guessed it, we will use pip for this. On Windows the command is:
python -m pip install pygame
Once this completes you should be ready to go. You may be interested in knowing exactly where pygame was installed. To discover that you simply enter:
pip show pygame
The results should look something like:
You can open the file in location and see the installation of pygame. You will notice there is a directory called examples, with tons of example projects to get you started. You can run these by running -m pygame.examples.examplename. For example:
python -m pygame.examples.stars
Will run the stars.py example in the examples directory. These examples are a good way to get to terms with the features of pygame. Next let’s create our own simple pygame game. I personally am using Visual Studio Code, but you can use whatever text editor you desire, just make sure your game’s name ends with .py. If you are using Visual Studio Code, it will autodetect the .py extension and ask to install everything you need, let it.
Now lets do some simple code:
import pygame from pygame.locals import * pygame.init() done = False screen = pygame.display.set_mode((640,480)) while not done: for event in pygame.event.get(): if event.type == pygame.QUIT or event.type == pygame.KEYDOWN: done = True screen.fill((255,255,255)) pygame.draw.circle(screen,(255,0,0),(320,240),25) pygame.display.update() pygame.quit()
It is important to remember that Python is a whitespace sensitive language, so spaces, newlines and tabs matter! Now in the directory you created the .py file, simply run (keeping in mind yours might have a slightly different name):
python game.py
Congratulations, you just created your first PyGame game! You can see the process in action in the video below. If you are interested in learning about different Python game engines, be sure to check out our guide available here. | https://gamefromscratch.com/getting-started-with-pygame/ | CC-MAIN-2021-25 | refinedweb | 530 | 75.61 |
Branching Logic vs. Guard Logic When It Comes To Function Control Flow
When it comes to Functions in computer programming, the Return statement is pretty badass. When your program's control flow hits a return statement, it completely exits out of the current context, halting the execution of the function. In the past few weeks, since I've started playing with Node.js (a heavily asynchronous environment), I've noticed myself starting to use the return statement in lieu of the branching whenever possible. And, I've been loving it.
I don't feel like a classically trained computer programmer (despite the fact that I went to school for computer science). As such, I am quite sure that I misuse terminology all the time. So, for the sake of this blog post only, let's just get on the same page for a few concepts:
- Branching Logic - This is the term I am going to use to indicate two or more possible control flows within a function that may each terminate with a Return statement (ie. IF-ELSE).
- Guard Logic - This is the term I am going to use to indicate a single branch in control flow that either terminates with a return statement or returns to the primary control flow of the function.
In the past, I think I would err on the side of branching. But, in recent times, I've started to use guard-style logic and I'm actually finding it much easier to read. Instead of thinking about my logic in terms of two separate-but-equal paths (ie branching), guard logic allows me to think of a single primary path with multiple exit opportunities.
To illustrate the difference, take a look at this function:
NOTE: I am leaving many of the critical tag attributes out of this code so as to draw attention directly to the control flow aspects.
- <cffunction name="doSomethingWithBranching">
- <!--- Define arguments. --->
- <cfargument name="style" />
- <!--- Check to see if the value indicates branching. --->
- <cfif (arguments.style eq "branching")>
- <cfreturn true />
- <cfelse>
- <cfreturn false />
- </cfif>
- </cffunction>
As you can see, the control flow of this function uses a branching IF-ELSE statement. This allows both branches to exit in a return statement.
Now, take a look at this function, which accomplishes the same exact intent with guard-style logic:
- <cffunction name="doSomethingWithGuard">
- <!--- Define arguments. --->
- <cfargument name="style" />
- <!--- Check to see if the value indicates guard. --->
- <cfif (arguments.style eq "guard")>
- <cfreturn true />
- </cfif>
- <!---
- If we have made it this far then no other conditions
- held true. As such, simply return false.
- --->
- <cfreturn false />
- </cffunction>
As you can see, both versions of the function have two return statements. However, in the former, those return statements both reside in a separate branch of logic; in the latter, only one of the return statements exists in a branch - the other remains in the primary control path of the function.
Given that both of these approaches yield the same outcome, I believe I am favoring guard-style control flow because it's easier to mentally model. When it comes to branching, you have to juggle at least 3 things - the primary control of the function and at least two branches (IF and ELSE). With guard-style statements, you only need to juggle 2 things - the primary control flow of the function and the IF statement. This means that at any time, you are either in or out of the primary control flow of the function. And, that's exactly the kind of duality that my brain can handle more efficiently.
So what would you do in the case of three possible exits?
Would you do:
<cfif x = y>
<cfreturn 1>
</cfif>
<cfif x = z>
<cfreturn 2>
</cfif>
<cfreturn many nested if/else statements, a bit of refactoring is probably in order anyway...
@Jessie,
Honestly, yeah, that might be what I would do. Of course, it always depends on a bit of context. Typically, the innards of the branching is more complex than a single return statement; in those cases, I do find the guard-style logic much easier to read and understand.
But, to be fair, if all I had were conditions with single return statements, I'd probably just stick to IF/ELSE; I don't think I'd get much readability benefit from the guard-style approach.... not until the branching logic got more complex.
@Seb,
Yeah, the nested IF statements is definitely one of those things that you can start to cut down on if you leverage the Return statement as more of a primary control flow entity.
Food for thought is always good - I am finding that I am constantly tweaking the methodology with which I code.
@Jessie - cfswitch with defaultcase?
@Michael,
I still tend to use use CFSwitch cases when dealing with including many different templates (depending on a value - ie. an "action" variable). points, especially when heavily nested, to be confusing. If possible, I try to use a single exit point at the end of the function and leverage variables to determine how to exit.
For example:
<cffunction name="doSomething">
<cfargument name="style" />
<cfset var result = false />
<cfif (arguments.style eq "guard")>
<cfset result = true />
</cfif>
<cfreturn result />
</cffunction>
Ben, good stuff. For "branching" how about "procedural"? I was given a lecture by a bad mannered client with a computing degree, and this is the only part I remember.
@Scott,
I tried to keep the examples simple in order to demonstrate the difference between the two; I can definitely see the "betterness" of either approach not coming through. And, as you say, it can be very subjective - for me, it's a mental modeling limitation; I can simply keep guard statements in my head more effectively.
As far as the single return statement, I have heard of this before; though, I am not sure what the original intent behind this concept was.
@Scott,
Usually guard clauses are used when the function does normally does something non-trivial, but for some inputs a trivial result can be returned.
<cffunction name="sluggingPercentage">
<cfif variables.cachedsluggingPercentage neq "">
<cfreturn cachedsluggingPercentage>
</cfif>
<cfif arrayLen(variables.atBats) eq 0>
<cfreturn 0>
</cfif>
<!---
This part shall be left to the imagination, as it was during
my childhood, before the internet ruined everything.
--->
<cfreturn computedSluggingPercentage>
</cfif> excessive complexity or I really want to make the "guard" nature very clear.
All of that being said, I like your idea of putting terms to these different approaches to make the decision a little easier to see and conceptualize.
Not only that, but I think this makes an argument that I have likely been to strict in my "a function should only have a single return" philosophy.
@Steve,
I'm pretty sure I was taught at one point that functions should only have one return value. But, I honestly can't remember what the reasoning was. Just because you can see that there is a return statement doesn't necessarily mean that value contained within the return is any more clear.
Meaning, that even with a single return statement, there is no implicit value to the value. You would still have to trace the path of branching to figure out what that would be.
The nice thing to seeing a Return statement is that it very clearly indicates: "This is the last thing you have to worry about in the function."
If you have branching AND a single return value, even if you get to the bottom of the branch, you still need to keep reading through the function to see if any additional logic gets applied to the value.
Maybe that's what appeals to me it lately - the definitive ending of each branch.
One of the places I find "Guard Logic" to be useful is in my Model-Glue apps. In Model-Glue, if a certain condition is met, you can issue a statement in your controller function to add a "result" to the event object. That result ends up acting like a return statement/interrupt that skips over any of the other message broadcasts (which are calls to other controller functions to execute model code) in that event handler and goes straight to the result code. It's a nice way of avoiding unnecessary code execution when you've already reached a success or failure condition.
I guess it's fine as long as your function is short. However, multiple return points are not encouraged when I was in college. They prefer a short if block for guards and long if block for actual "Branching Logic", and then follow by a single return statement. - sort of like....
Using a struct in a standard format for all non-trivial functions lets me pass a status value and message back and makes it really easy to bubble-up error conditions.
It also makes the logic really easy to read as exception conditions are just 'thrown' out as they occur, leaving what amounts to a pretty liniar, easy to understand flow in the rest of the function.
I guess this is the 'guard logic' model, but with the added benefit of a bail-out which you can nevertheless guarantee passes through a single 'exit' point.
@Ian,
I definitely use a Try/Catch approach when it comes to developing an API control flow. Since so much is involved with APIs - credentials, input validation, format validation, return type validation, etc., there are many opportunities for errors to arise in each request. Try/Catch has been awesome for that (especially when using several different "typed" CFCatch tags).
@Henry,
I believe I was taught that also. But, I can't remember what the reasoning was.
@Brian,
That sounds cool. I don't know much about the Model-Glue framework.
Like you, I prefer what you're calling guard logic.
I REALLY like how it keeps indention down.
Although it's fallen into disfavor in recent years, another advantage of guard logic is that you can often get away with not coding braces on an immediate return:
Most folks nowadays would code
The purpose of braces is to group together MULTIPLE statements, but it seems like religion nowadays that we have to always code braces, just in case we want to add more statements in the future, I guess.
But even the most code-like-me-or-you're-uncool firebrands seem to tolerate a braceless break, continue or return as the only statement following an if.
And this is the same thing (no braces), but now you'll REALLY think I'm crazy:
I hope the code tag lines up columns the way I did when I wrote it. Isn't it REALLY easy to read? You know exactly what's going on in a glance.
*sigh* I'll get the hang of the code tag here someday, I *promise*.
3 spaces were truncated before the first 2 "return true" statements.
6 spaces were truncated before the first .onchange() in the onsubmit.
@WebManWalking,
Ha ha, sorry - I wish my Code tag was better :) I used to be more flexible; but I realize that the flexibility broke after 3 sets of 2-spaces (I didn't know if it was supposed to be three sets or 2 tabs.
While I like the guard logic, I also am a huge fan of braces to define code blocks. I personally find non-brace too hard to follow since I don't code that way. I've been so conditioned to believe that braces will be there.
I call this Short Circuit programming, as you're short circuiting the rest of the logic and taking the quickest route out of the method.
I've been using it for years and it creates VERY fast and readable code. Additionally, there are branching limitations. I've come across nasty validation logic code that consists of a ton of nested if/else statements. Coldfusion (actually java) returns an error about something to do with exceeding small int branching branching paths 128 after an upgrade to CF8. I presume it was using a signed byte to count how many branching paths, and when it reaches 128, it's just too complex. Most of that code got broken into discreet functions and short circuiting logic. Speed also drastically improved as well.
@Jim,
128 maximum branches :) Awesome. That just seems like a huge number.
It's reassuring to hear that you've been using this type of approach and are also finding it very readable. Sometimes, I get concerned that maybe its only readable because I am the one that wrote it.
@Ben,
I also use it in conjunction with formatted structs as a lazy (nay, Creative and Efficient!) way to bubble up nested error messages without relying on try catch when I don't need to.
crude example:
inside component:
inside cfm:
The 'universal' error keys in the struct only exist if Success is false (and no data will be present other than the error keys. don't want partial data. Either success, or nothing). If success is true, the data keys i expect I know will be present.
@Ben,
A more practical example: that have returns and no else because you can easily find code duplication and refactor for AOP style advice later.
ex.
function example(...) {
if (...) return true;
if (...) return true;
// compute something
return computation;
}
Both of those return statements might be candidates for refactoring into advice. If we had a bunch of nested if statements that'd be harder to notice though.
@Jim,
That's exactly the kind of stuff I am talking about.
@Elliott,
I had never even considered AOP stuff for this kind of logic; but that makes sense. Excellent point!
statements, cause thats just useless and a waste of time. I always use the guard logic, not because I read about it, it's just logic to me; one main stream down and whathever doesn't follow, get out right away.
I know you tackled this question in ColdFusion, but I just had a revelation that this could kill JS performance and jsperf confirmed it: return/assignments.
Note that a decent JS compiler may rewrite the entire function to remove the early return (or add one). And that all modern browsers are going to turn both into very efficient assembly code when the JIT kicks in. Language constructs have very little performance impact (except "with" which turns off optimizations and makes everything slow...)
@Elliott,
Math.random() probably is affecting the performance, but so is the function call itself. Branching logic has a major impact on performance this was just not a good test of it. A true test would remove the function call as well.
well write this test in C.
@Elliott,
@Elliott,
I wanted to test returns inside a function, I can't test those without paying the cost of opening a function :P. So obviously, calling a method costs far more than premature returns 'guarded logic' inside it.
Of course, some code that requires no if/then/else would be faster than some that did, so thats not relevant. If the CPU can just burn through the numbers, it would outpace having to make decisions along the way. Again, this isn't what I was looking into, I wanted to see if returning early had an impact on performance.
@Drew Your test is flawed. When doing short circuiting logic, you typically do such in a function with a high amount of comparisons such as validation of a whole form. In this case, the first instance you fail and return early, then better as you jump over comparisons that don't need to be made. When your method returns an object, you will have some default state of the object, only filling out and returning a more complete object later in the method if you need to get that far. Your test doesn't do nearly enough work to be a valid comparison.
@Drew,
I'm a bit late to this conversation; but, I think we wouldn't want to test a return vs. no-return. We're already in a use-case where we're in a function that has to return a value. As such, the case where no value is return doesn't necessarily apply.
@All,
I know this thread is old, but I've been recently making a lot of mistakes in an asynchronous workflow when I forget to use return():
Seems like a related-enough topic. | http://www.bennadel.com/blog/2195-branching-logic-vs-guard-logic-when-it-comes-to-function-control-flow.htm | CC-MAIN-2014-49 | refinedweb | 2,743 | 61.87 |
I
Events – Forge Accelerators, DevDay, RTC and AU
Here are my main upcoming events:
- Oct. 19 – Forge and BIM, Porto University
- Oct. 20-22 – RTCEU Revit Technology Conference Europe, Porto
- Oct. 24-28 – Forge Accelerator, Munich
- Nov. 4 – Forge and BIM Workshop, Darmstadt University
- Nov. 14-17 – Autodesk university, Las vegas
- Dec. 5 – DevDay Europe, Munich
- Dec. 6-9 – Forge Accelerator, Munich
I'll present my projects and material for these as soon as I get around to preparing them.
Real soon now!
Accessing the MacroManager to Delete Document Macros
Next, I address the Revit API discussion forum thread on obtaining the MacroManager as well as Frederic's comment on What's New in the Revit 2014 API:
Question: I'm stuck with getting MacroManager object. There are much more class members listed in API reference then really available. What am I doing wrong?
Or is there any other way to delete all macros from document?
Jeremy says: I should think this can be done quite easily. Look at What's New in the Revit 2014 API and search for MacroManager API.
Revitalizer answers: Add
RevitAPIMacros.dll to your VS project.
Response: Revitalizer, thank you very much! It's got to be that easy I knew it :-)
Actually, a reference to
RevitAPIMacrosInterop.dll solved the problem at last (not to
RevitAPIMacros.dll)!
Revitalizer answers: I cannot believe that
RevitAPIMacrosInterop.dll solves the problem since it does not contain the
MacroManager definition.
RevitAPIMacros.dll does:
Jeremy says: Look at The Building Coder samples new CmdDeleteMacros.cs module in release 2017.0.129.0.
Just as Revitalizer suggests, I was forced to add references to
RevitAPIMacros.dll and
RevitAPIUIMacros.dll in The Building Coder samples Visual Studio project specifically for this command.
using Autodesk.Revit.Attributes; using Autodesk.Revit.DB; using Autodesk.Revit.DB.Macros; using Autodesk.Revit.UI; using Autodesk.Revit.UI.Macros; using System.Linq; using System.Diagnostics; namespace BuildingCoder { [Transaction( TransactionMode.ReadOnly )] class CmdDeleteMacros : IExternalCommand { public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements ) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; UIMacroManager uiapp_mgr = UIMacroManager .GetMacroManager( uiapp ); UIMacroManager uidoc_mgr = UIMacroManager .GetMacroManager( uidoc ); int nModulesApp = uiapp_mgr.MacroManager.Count; int nModulesDoc = uidoc_mgr.MacroManager.Count; int nMacrosDoc = uidoc_mgr.MacroManager .Aggregate<MacroModule, int>( 0, ( n, m ) => n + m.Count<Macro>() ); TaskDialog dlg = new TaskDialog( "Delete Document Macros" ); dlg.MainInstruction = "Are you really sure you " + "want to delete all document macros?"; dlg.MainContent = string.Format( "{0} application module{1} " + "and {2} document macro module{3} " + "defining {4} macro{5}.", nModulesApp, Util.PluralSuffix( nModulesApp ), nModulesDoc, Util.PluralSuffix( nModulesDoc ), nMacrosDoc, Util.PluralSuffix( nMacrosDoc ) ); dlg.MainIcon = TaskDialogIcon.TaskDialogIconWarning; dlg.CommonButtons = TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.Cancel; TaskDialogResult rslt = dlg.Show(); if(TaskDialogResult.Yes == rslt ) { MacroManager mgr = MacroManager.GetMacroManager( doc ); MacroManagerIterator it = mgr.GetMacroManagerIterator(); // Several possibilities to iterate macros: //for( it.Reset(); !it.IsDone(); it.MoveNext() ) { } //IEnumerator<MacroModule> e = mgr.GetEnumerator(); int n = 0; foreach( MacroModule mod in mgr ) { Debug.Print( "module " + mod.Name ); foreach( Macro mac in mod ) { Debug.Print( "macro " + mac.Name ); mod.RemoveMacro( mac ); ++n; } // Exception thrown: 'Autodesk.Revit.Exceptions // .InvalidOperationException' in RevitAPIMacros.dll // Cannot remove the UI module //mgr.RemoveModule( mod ); } TaskDialog.Show( "Document Macros Deleted", string.Format( "{0} document macro{1} deleted.", n, Util.PluralSuffix( n ) ) ); } return Result.Succeeded; } } }
This command is destructive in spite of being read-only, so it first prompts you for confirmation before proceeding to delete all document macros:
After doing its dirty deed, it confesses and reports in full:
Getting Started and Changing the Colour of a Wall
Next, let's look at Nalika's comment on displaying a webcam image on a building element face:
Question: I'm very new to Revit and very much grateful if you could help me in solving my problem.
Currently I'm trying to change the colour of a wall according to a certain value. For example: value 20 will make the wall red when I click on it and if I click on the wall again it will be green according to a new value. The values are stored in an array and currently have 4 values. I use the sample library project
WorkThread and it uses the same
SetupDisplayStyle function to set the display style. There I pick the colour from array values. However, the wall is coloured in 4th colour when I click on the wall for the 4th time, and the first three times the wall isn't coloured at all. Could you please tell me in which function/method should I change/iterate through in order to have different colours (defined from array values) every time I click on a wall.
Answer: If you are new to the Revit API, I would strongly suggest that you work through the Revit API getting started material first of all, especially the DevTV and My First Revit Plugin video tutorials.
If you want to dive in deeper, go through the ADN Revit API Training Labs after that.
Then start implementing your own add-ins.
The
WorkThread and
SetupDisplayStyle samples do not sound suitable for what you are trying to achieve.
By the way, what are you trying to achieve, and why?
Maybe you should look at the Revit SDK sample collection first? It might contain exactly what you are looking for.
One very flexible way to set colours on specific elements is by using view filters, and there is a nice sample demonstrating how to drive that programmatically as well:
ElementFilter /
ViewFilters.
Before looking at the Revit API at all, you definitely need some understanding of Revit from an end user point of view.
It provides a huge amount of complex functionality right out of the box.
If you start programming Revit with insufficient understanding of the basic Revit end user functionality and the optimal workflows and best practices to make use of it efficiently is doomed for disaster.
Take heed, have fun, and good luck!
Getting Started and Using the Visual Studio Revit Add-In Wizard Auto-Installer
While we are at it, we might as well also reproduce Juan E. Calvo Ferrándiz' comment on the wizard auto-installation:
Question: Thanks for this work! Is amazing.
The add-in wizard setting exports the
.dll to the
bin folder and the
users/xxx/AppData... folder, right?
Then, it also creates two copies of the
.addin manifest, one to the project folder and another one to the
AppData... folder.
Revit loads the
.dll and
.addin from the
AppData... folder?
Revit doesn't need the
.pdb file? It's just additional information when troubleshooting the DLL, right?
Answer: Yes, exactly, correct on all points.
You, the developer, write the add-in manifest
.addin, and the source code, in C# or whatever you like.
The compiler generates the output DLL assembly in the directory you specify, by default
bin/Debug and
bin/Release.
Your post-built events copy the add-in manifest and the DLL to the appropriate Revit add-ins folder.
The
PDB file contains the program debug information and is not required except for debugging.
The mother of all information on installing a Revit add-in is provided by the Revit online help > Developers > Revit API Developers Guide > Introduction > Add-In Integration > Add-in Registration. | http://thebuildingcoder.typepad.com/blog/2016/09/macromanager-materials-kiss-and-getting-started.html | CC-MAIN-2017-22 | refinedweb | 1,198 | 52.15 |
I'm one of the many people downloading every EAP release of IDEA 4.0 to check out what new features, refactorings, etc. they put in the upcoming release. One of the ones that I've been playing with a lot is the new WebLogic integration. IDEA 4.0, when it ships will support complete integration with WebLogic.
Some of the features of the WebLogic integration include support for creation and management of Weblogic specific deployment descriptors, connect to running WebLogic server instances, start/stop the server and deploy war, ejbs and ear files directly from IDEA. Neat features, but I've been doing that with WebLogic and IDEA for years — Not sure what's really new here. Yeah, the deployment descriptor editor is nice and the built-in support for start/stopping server is nice but I am still trying to figure out why someone should upgrade if this is the only new thing they want to try out. Don't get me wrong – I am a total IDEA bigot and will continue to pay my maintanance fee to get the 4.0 upgrade. I guess I need to continue playing with the latest EAP builds to discover and document new features that make the upgrade worth the cost and hassle.
Before JPDA (Java Platform Debugger Architecture), I had a simple Java class that would load WebLogic from inside the IDE. It's not really rocket science – Here's the simple class:
public class WebLogicDebugger {
public static void main(String[] args) {
System.getProperties().put("bea.home", "c:/bea");
System.getProperties().put("weblogic.Domain", "vinny");
System.getProperties().put("weblogic.Name", "myserver");
.
.
.
try {
weblogic.Server.main(args);
System.out.println("finished weblogic.Server.main");
} catch (Throwable t) {
System.err.println(new java.util.Date() + "####**** ERROR ***###");
t.printStackTrace();
}
}
}
Once WebLogic server is up and running inside IDEA or your IDE of choice, you can use the Ant integration to build and deploy the end result (war, ejb jar or ear) to the deploy directory of the running instance of WebLogic.
The integration offered by IDEA is pretty neat and I must give kudos to the developers. Here's a simple walkthrough of setting up WebLogic Integration inside IDEA. The first setup allows you to start the WebLogic integration configuration:
Once the WebLogic Server Integration option is selected, IDEA will automatically sniff out the version of WebLogic installed and find the bea.home directory. You can then setup one of more WebLogic servers by setting the Admin user/password and the domain path. Any additional program parameters (-D parameters) or VM attributes can be specified.
Once the server is up and running, you can deploy/re-deploy applications. I am still having issue with build 1120 and can't seem to get the deployment piece working correctly. I can use my Ant task to deploy, but cannot seem to use the built-in deployer. Need to follow up with the EAP forums.
| http://m.mowser.com/web/www.j2eegeek.com%2Fblog%2F2004%2F02%2F01%2Fidea-40-and-weblogic%2F | crawl-002 | refinedweb | 489 | 54.22 |
This is your resource to discuss support topics with your peers, and learn from each other.
10-30-2013 09:37 PM
this is the page, what am i doing wrong?
import bb.cascades 1.0
Page {
id:addPage
property variant appScene: Application.scene
// Custom signal for notifying that this page needs to be closed
signal done ()
titleBar: TitleBar {
title: qsTr("Add Location") + Retranslate.onLocaleOrLanguageChanged
dismissAction: ActionItem {
title: "Cancel"
onTriggered: {
// Emit the custom signal here to indicate that this page needs to be closed
// The signal would be handled by the page which invoked it
addPage.done();
}
}
}
Container {
background: Color.Transparent
TextField {
id: cityfield
hintText: qsTr("Enter City or Postal Code") + Retranslate.onLocaleOrLanguageChanged
inputMode: TextFieldInputMode.Text
input.submitKey: SubmitKey.Search
}
}
onAppSceneChanged: {
// This triggers focus if the application scene is set to
// this QML Page.
cityfield.requestFocus();
}
}
Solved! Go to Solution.
10-31-2013 11:24 AM
Do you want the text field to get focus (and pull up the virtual keyboard on Z-devices) as soon as the page is loaded?
Try creating a property on the qml page:
property bool showVKB: false
And add this method in your qml:
onShowVKBChanged: { if (showVKB) { // This focus request shows the VKB if the Page is created via a ComponentDefinition (see main.qml) tfWord.requestFocus(); } }
And then in your qml page that pushes this page, set the showVKB property:
navigationPane.push(page); page.showVKB = true;
10-31-2013 03:50 PM
10-31-2013 11:53 PM
03-01-2014 04:09 AM
cool,that's i want.... | http://supportforums.blackberry.com/t5/Native-Development/problems-with-request-focus-for-a-textfield/m-p/2652335 | CC-MAIN-2016-07 | refinedweb | 255 | 55.64 |
Why does set of a pandas dataframe return column names of the dataframe?
I was just tinkering around and found this amusing:
>>> import pandas as pd >>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]}) >>> x = set(df) >>> x {'col2', 'col1'}
Why does pandas return column names as set values?
2 answers
- answered 2018-10-11 20:16 jpp
Because that's how
__iter__is defined in the source code for
NDFrame, of which
pd.DataFrameis a child:
def __iter__(self): """Iterate over infor axis""" return iter(self._info_axis)
pd.DataFrame._info_axisis used internally to store column labels:
df = pd.DataFrame(columns=list('abcd')) df._info_axis # Index(['a', 'b', 'c', 'd'], dtype='object')
setiterates the
pd.DataFrameinstance via
__iter__, hashes each element, and returns a
setof values corresponding to unique column labels.
- answered 2018-10-11 20:17 user3483203
You can find the implementation for
__iter__in
DataFrame's parent class
NDFrame:
def __iter__(self): """Iterate over infor axis""" return iter(self._info_axis)
It's essentially the same as calling
keyson a DataFrame, defined in the same location. I'm including it here because the docstring is more helpful, and describes the differences in
_info_axisbetween
Series,
DataFrameand
Panel
def keys(self): """Get the 'info axis' (see Indexing for more) This is index for Series, columns for DataFrame and major_axis for Panel. """ return self._info_axis. | http://quabr.com/52768061/why-does-set-of-a-pandas-dataframe-return-column-names-of-the-dataframe | CC-MAIN-2019-09 | refinedweb | 222 | 53.92 |
Unit tests are a great benefit to nearly any project. A set of proper tests can help in many ways, the most obvious being to catch bugs early. Unfortunately a number of the test libraries end up requiring a lot of boilerplate code and become a pain to write. As such, when looking for a testing library the number one goal was to find something as minimal and non-intrusive as possible. At the same time, a mocking system is also useful to have for larger and more complicated testing purposes. The Google Mock library googlemock supplies both the mocking and unit test libraries and it is very simple to use.
Download
and uncompress it somewhere if you don't have it from Part 2 of the series.
Parts 1 2 3 4 5
Shared Libraries
The final target type which we have not implemented as of yet is the shared library. At the basic level it is no different than using a static library and in fact, on Linux and OsX it is identical except it is a shared library. Unfortunately Windows is significantly more complicated due to the requirements of importing and exporting functions. We'll start by ignoring the problems on Windows for now and getting the basics functioning on Linux and OsX.
The first thing to do is add a new set of directories for the shared library:
Create the following directories under CMakeProject/libraries:
World Include Source
Now edit the CMakeProject/libraries/CMakeList.txt as follows:
ADD_SUBDIRECTORY( libraries/Hello ) ADD_SUBDIRECTORY( libraries/World )
Finally add the new files:
CMakeProject/libraries/World/CMakeLists.txt:
SET( INCLUDE_DIRS ${CMAKE_CURRENT_LIST_DIR}/Include ) INCLUDE_DIRECTORIES( ${INCLUDE_DIRS} ) SET( INCLUDE_FILES Include/World.hpp ) SET( SOURCE_FILES Source/World.cpp ) ADD_LIBRARY( World SHARED ${INCLUDE_FILES} ${SOURCE_FILES} ) # Export the include directory. SET( WORLD_INCLUDE_DIRS ${INCLUDE_DIRS} PARENT_SCOPE )
CMakeProject/libraries/World/Include/World.hpp:
#pragma once const char* const WorldString();
CMakeProject/libraries/World/Source/World.cpp:
#include <World.hpp> const char* const WorldString() { return "World!"; }
Regenerate the build and you now have a shared library. If you are using Linux or OsX, your library is complete and can be used by simply adding it to a target the same way the static library was added. Let's make a couple minor modifications in order to use this library and link against it.
CMakeProject/libraries/Hello/Source/Hello.cpp:
#include <Hello.hpp> const char* const HelloString() { return "Hello"; }
CMakeProject/tests/Hello2/main.cpp:
/* Hello World program */ #include <iostream> #include <functional> #include <Hello.hpp> #include <World.hpp> int main( int argc, char** argv ) { std::cout << HelloString() << " " << WorldString(); return 0; }
CMakeProject/tests/CMakeLists.txt:
CMAKE_MINIMUM_REQUIRED( VERSION 2.6.4 ) INCLUDE_DIRECTORIES( ${HELLO_INCLUDE_DIRS} ${WORLD_INCLUDE_DIRS} ) PROJECT( HelloWorld ) ADD_EXECUTABLE( Hello2 main.cpp ) TARGET_LINK_LIBRARIES( Hello2 Hello World )
With the given changes, Linux and OsX can build and run the modified 'Hello2' project and the string for "Hello" comes from a static library function and the "World!" comes from a shared library function. Unfortunately Windows is not so lucky and will fail to link.
The Windows DLL
As with the OsX specific fix, using shared libraries with Windows is something of a black art. I don't intend to explain all the details, that would take another article. I will simply explain the basics of the fix and make the code work on all three platforms again.
The basic problem with using shared libraries on Windows requires a little description. First off they are called dynamic link libraries (aka DLL) on windows. Second they are split into two pieces, the actual DLL portion which is the shared library where the code lives and a link library which is like a static library. Confusingly the link library usually has the file extention 'lib' just like an actual static library so don't get them confused. At this time, we are not telling the compiler to generate this intermediate file.
Generating the intermediate file is simple enough but you have to deal with it in a cross platform nature or you break Linux and OsX builds. Exporting the library symbol and making the link library is as simple as changing the function declaration to be the following:
__declspec( dllexport ) const char* const WorldString();
If you go ahead and make this change, the project compiles on Windows, but it will not run because it can't find the DLL. This problem is an annoyance with how VC tends to layout the projects when divided up in the manner suggested in this series of articles. Fixing this digs into the darker recesses of CMake properties which, for the moment we will avoid by cheating. For the time being, just copy the dll manually:
Copy from CMakeProject/build/vc11/libraries/World/Debug/World.dll to CMakeProject/build/vc11/tests/Hello2/Debug/World.dll
At this point Windows is functioning again, though with obvious cheats and actually a glaring error, though the error doesn't cause a problem at the moment. What's the error? Well, to be proper you are supposed to use '__declspec( dllexport )' only in the code building the DLL and then '__declspec( dllimport )' in code which uses the library. While it works as it is, it is best to follow the rules as closely as possible so as not to get strange behaviors/errors at a later time.
So, we'll extend the code to correct the issue of import versus export:
#ifdef BUILDING_WORLD # define WORLD_EXPORT __declspec( dllexport ) #else # define WORLD_EXPORT __declspec( dllimport ) #endif WORLD_EXPORT const char* const WorldString();
Rebuild and now you get a warning: "warning C4273: 'WorldString' : inconsistent dll linkage"
The reason is, we have not defined 'BUILDING_WORLD'. Since we want to define this only for the 'World' library, we edit the CMakeProject/libraries/World/CMakeLists.txt as follows:
SET( INCLUDE_DIRS ${CMAKE_CURRENT_LIST_DIR}/Include ) INCLUDE_DIRECTORIES( ${INCLUDE_DIRS} ) SET( INCLUDE_FILES Include/World.hpp ) SET( SOURCE_FILES Source/World.cpp ) ADD_DEFINITIONS( -DBUILDING_WORLD ) ADD_LIBRARY( World SHARED ${INCLUDE_FILES} ${SOURCE_FILES} ) # Export the include directory. SET( WORLD_INCLUDE_DIRS ${INCLUDE_DIRS} PARENT_SCOPE )
Notice the new CMake command: 'ADD_DEFINITIONS'. As the name states, we are adding a definition to the macro preprocessor named 'BUILDING_WORLD' to the 'Hello2' target.
Windows is happy, we are following the rules and other than having to manually copy the DLL for the moment, it functions. There is one last issue, the macro will be applied to all platforms, something we don't want. So back in CMakeProject/libraries/World/Include/World.hpp, make the following change:
#ifdef _WINDOWS # ifdef BUILDING_WORLD # define WORLD_EXPORT __declspec( dllexport ) # else # define WORLD_EXPORT __declspec( dllimport ) # endif #else # define WORLD_EXPORT #endif WORLD_EXPORT const char* const WorldString();
CMake inserts per OS specific definitions based on the platform being targetted. In this case, as with using Visual Studio without CMake, '_WINDOWS' is defined by default. So, we can rely on this and now the code is safely cross platform and ready for commit.
Changing Output Directories
In order to finish correcting the Windows build we have to use a bit of CMake voodoo which is not often documented particularly well. Changing output directories. What we want is to output the executables and the libraries (shared and static) to a single output directory while leaving intermediate files wherever CMake/VC wants to store them. This is not required for OsX and Linux as the output generators there follow a more simplified directory structure. We also want to do this only for Visual Studio and not change the default behavior of nmake, CodeBlocks and other generators.
Modify the CMakeProject/CMakeLists.txt to be the following: ) IF( MSVC ) SET( CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/Binaries ) SET( CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/Binaries ) SET( CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/Binaries ) ENDIF( MSVC ) INCLUDE( libraries/CMakeLists.txt ) ADD_SUBDIRECTORY( tests )
Note that the detection for Visual Studio is performed after the 'PROJECT' command. There is a reason for this. CMake does not initialize many variables until after the 'PROJECT' command is issued. Among the variables not initialized is of course 'MSVC'. The reason for the delayed definition is that CMake reads the locally catched data at the point where it see's the 'PROJECT' command. So, while knowing the platform being run on and being able to modify the compile and linker flags can be done before the 'PROJECT' command, the specifics such as the generator in use are not known until the cache data is processed.
The next item to note is: why three directories? CMake divides the directories into three pieces to match the three target types, runtime for the executables, archive for static libraries and library for shared/dynamic libraries. While you could just set the executable and shared library paths, I include the static libraries in case something external to this build system wanted to link against the libraries. It is not required but makes things easier in advanced usages.
Finally, what is the 'PROJECT_BINARY_DIR' variable being used? Before we define any of the targets, this variable simply points to the directory CMake was launched from as it's out of source build location. In my case on Windows, I'm using '<root>/CMakeProject/build/Vc11' and as such that is what 'PROJECT_BINARY_DIR' is initialized with. There are many other variables, some which will also point to this location and could have been used. I just like this one because it is related to what I'm trying to accomplish, which is put all the final compiled binaries in one place.
Regenerate the project, rebuild all and you will now have a single directory with all the binary outputs within it. You can run the examples using Visual Studio and it will no longer complain that it can not find the DLL to load.
Unit Testing
With a title that states "Test Driven Development" in it, you would probably think that adding unit tests would have been done a bit earlier. The funny thing is that you have had a unit testing framework the entire time, it is built right into CMake itself called CTest. The downside is that I don't much like the way the built in functionality works and incorporating an external library is a good learning experience. So, we will start using googlemock in a little bit.
During the course of writing this series I initially thought that I would stick to an 'all lower case' naming convention. In the process of writing, I mostly added code quickly and as such fell back on my habitual way of doing things without paying much attention. Other than to say I'm going to use camel case for the names, we'll skip the reasons and simply start with a fresh empty environment based on all the work we have done and also adding the final target divisions, so download the following and we'll start adding the unit test library:
The New Environment
There is not much changed in the new environment other than applying the mentioned capitalizations and adding a couple new subdirectories along with the removal of 'tests'. The directories are intended as follows:
- Build: A placeholder for where you can use CMake to store its cache files and such. I tend to use subdirectories such as: Vc11, Xcode, Makefiles, etc.
- External: The location we will be storing external libraries such as googlemock.
- Libraries: Static and shared libraries used by the projects.
- Applications: Your game, potentially another game and anything which is not a tool but uses the libraries.
- Tools: Obviously things which are used in the creation of the game. Exporters, converters, big level builders, etc.
Go Get GoogleMock
Download the gmock-1.6.0.zip file from googlemock and decompress it into the 'CMakeEnvironment/External' directory. You should end up with a new folder: 'CMakeEnvironment/External/gmock-1.6.0' which contains the library source. If you go looking around in the folder you will notice that it uses autoconf and m4 scripting to build on Linux/OsX and supplies a solution and project file for Visual Studio. This is normally fine for simple things but I want it integrated with the CMake build environment more tightly such that if I change global compiler flags it will rebuild along with the other sections of the project.
As you will see, all the little steps we've gone through in setting up the environment with CMake in a clean manner will start to pay off as we integrate the library. Thankfully, as with many other Google libraries, the source contains a 'fused-src' directory which means we can add two headers and a source file to our project and almost be done with it. I say almost, since I want to make sure we integrate the library within the environment as cleanly as possible and make no modifications to the unzipped directory. Start by adding the following (and creating the new directories):
CMakeEnvironment/External/CMake/GMock/CMakeLists.txt:
# Use a variable to point to the root of googlemock within # the External directory. This makes it easier to update # to new releases as desired. SET( GOOGLEMOCK_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../../gmock-1.6.0" ) # Make the file lists. SET( INCLUDE_FILES ${GOOGLEMOCK_ROOT}/fused-src/gtest/gtest.h ${GOOGLEMOCK_ROOT}/fused-src/gmock/gmock.h ) SET( SOURCE_FILES ${GOOGLEMOCK_ROOT}/fused-src/gmock-gtest-all.cc ) # Setup some build definitions for VC2012. IF( MSVC ) ADD_DEFINITIONS( -D_VARIADIC_MAX=10 ) ENDIF( MSVC ) # Add as a static library target. ADD_LIBRARY( GMock STATIC ${INCLUDE_FILES} ${SOURCE_FILES} )
This will allow GMock and GTest to compile on Windows and Linux. Unfortunately nothing ever seems to work without problems. The library refuses to compile on OsX due to Clang being detected as GCC and making a bad assumption about the availability of tr1 files. After arguing with it and even hacking the source I decided that for the time being, the easiest and most time effective method was to cheat. The benefit of cheating is under rated when you need to get things done and don't want to hack on external code. So, what exactly is this cheat? We'll add a directory for tr1 and a file for tuple, the file will simply alias the to C++11 tuple in order to meet the requirements. (I won't detail the changes, check out the various CMakeLists.txt if you are curious.)
Additionally, we have a link problem with the Linux environments to fix. If you tried to link against the GMock library and build you will get link errors, given the output it becomes pretty apparent that we've missed the threading libraries. In order to fix this, we get to learn a new command in CMake: FIND_PACKAGE. Anytime you need a set of specific includes and/or libraries to link against, there is usually a module which CMake supplies (or the community supplies) for the item. In this case we need to find the 'Threads' package. Once we do this, we add a new target link library to our binaries: '${CMAKE_THREAD_LIBS_INIT}'. This will take care of the linking on Linux and also because it is a variable, it will be empty on other platforms which don't need explicit linkage to an additional library.
As with static libraries in general, we know it is easy to link against the library but a bit more of a challenge to get the include paths setup. Additionally, the variadic work around for VC needs to be pushed out as a global item for all projects, otherwise they will fail to compile. This is all stuff we've dealt with before so it becomes easy. In the root CMake file move the 'ADD_DEFINITIONS' command to be just under the output path changes we made and also insert the FIND_PACKAGE command for all builds:
CMakeEnvironment/CMakeLists.txt:
# ############################################### # Make VC happy and group all the binary outputs, # also make sure GMock headers will compile in # all targets. IF( MSVC ) SET( CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/Binaries ) SET( CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/Binaries ) SET( CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/Binaries ) ADD_DEFINITIONS( -D_VARIADIC_MAX=10 ) ENDIF( MSVC ) # ############################################### # Find the threading package for this machine. FIND_PACKAGE( Threads )
Remove the definition line from the GMock/CMakeLists.txt and add the following to the bottom of the file:
SET( GMOCK_INCLUDE_DIRS ${GOOGLEMOCK_ROOT}/fused-src PARENT_SCOPE )
Controlling Tests
The last thing to be done is to control if unit tests are compiled and built. When you start working this is not a big deal of course as you will likely only have a couple libraries and tests. After a while though, you may end up with more little "test" targets than actual libraries and applications. So, it is a good idea to go ahead and add the ability to disable tests from day one. Add the following item:
CMakeEnvironment/CMakeLists.txt:
# ############################################### # Allow unit tests to be disabled via command # line or the CMake GUI. OPTION( BUILD_UNIT_TESTS "Build unit tests." ON )
Add this just under the 'PROJECT' command and it will show up in the CMake GUI as something you can turn on and off.
Putting The Results To Use
Two and a half articles later, we are finally ready to put our work to good use. I'm going to start by writing a 3D vector class since it is a common item and easily unit tested. The first thing to do is of course get the completed environment. This file includes the googlemock library so it's quite a bit larger than the prior items:
The Math Library
I'm going to keep this very simple for the purposes of this article. I will not be implementing the actual class, just enough to show a unit test in action. Future articles will likely build off this work but this is going to close out the CMake work for the time being so we want to keep things simple. Let's start by adding the directories for the new 'Math' library:
CMakeEnvironment Libraries Math Include Math Source Tests
Ok, so the first question is likely to be why did I duplicate the directory 'Math' under the 'Include' directory? This is simply a polution prevention item. Let's say you have a custom 'Collections' library and within that there is a 'Vector.hpp' file and of course the math library could have a 'Vector.hpp' file. If you include without the prefix of 'Collections' or 'Math', which file are you including? With the way we will setup the libraries, this problem is solved by forcing the users of the libraries to qualify the includes as follows:
#include <Math/Vector.hpp> #include <Collections/Vector.hpp>
This is another one of the personal preference items but I prefer avoiding problems from day one and not simply assuming they won't happen. If you don't like this, once we get done feel free to remove the nested directory. But be warned that in future articles you'll see some good reasons to use this pattern which can greatly simplify normally difficult processes.
Let's fill in the hierarchy with files now, add the following:
CMakeEnvironment/Libraries/Math/CMakeLists.txt:
SET( INCLUDE_DIRS ${CMAKE_CURRENT_LIST_DIR}/Include ) INCLUDE_DIRECTORIES( ${INCLUDE_DIRS} ) SET( INCLUDE_FILES Include/Math/Math.hpp Include/Math/Vector3.hpp ) SET( SOURCE_FILES Source/Vector3.cpp ) ADD_DEFINITIONS( -DBUILDING_WORLD ) ADD_LIBRARY( Math STATIC ${INCLUDE_FILES} ${SOURCE_FILES} ) # Export the include directory. SET( MATH_INCLUDE_DIRS ${INCLUDE_DIRS} PARENT_SCOPE )
Add empty files for:
Include/Math/Math.hpp
Include/Math/Vector3.hpp
Source/Vector3.cpp
Tests/Main.cpp
Regenerate the environment and you should have your new Math library.
The First Unit Test
The first thing we want to do is add a unit test holder before we add any code to the library. What we need is a simple executable which can include the files from the library. Since this is part of the math library, we can simply add the test within 'CMakeEnvironment/Libraries/Math/CMakeLists.txt'. Additionally, we want the test to honor the flag we setup such that the test is not included when tests are disabled. Add the following to the end of the Math libraries CMake file:
# Make a unit test holder for the Math library. IF( BUILD_UNIT_TESTS ) # Add the gmock include directories. INCLUDE_DIRECTORIES( ${GMOCK_INCLUDE_DIRS} ) ADD_EXECUTABLE( _TestMath Tests/Main.cpp ) TARGET_LINK_LIBRARIES( _TestMath Math GMock ${CMAKE_THREAD_LIBS_INIT} ) ADD_TEST( NAME _TestMath COMMAND _TestMath ) ENDIF( BUILD_UNIT_TESTS )
Regenerate and you get a new target '_TestMath'. In the CMake GUI if you set 'BUILD_UNIT_TESTS' to 'FALSE' and regenerate, the new target goes away as we desired. But, there is actually one more thing we want to do to make this even better in the future. In the root CMake file with the 'OPTION' command defining the 'BUILD_UNIT_TESTS' variable, add the following bit right afterward:
# ############################################### # Enable the CMake built in CTest system if unit # tests are enabled. IF( BUILD_UNIT_TESTS ) ENABLE_TESTING() ENDIF( BUILD_UNIT_TESTS )
Make sure to set 'BUILD_UNIT_TESTS' back to 'TRUE' and regenerate. A new target shows up in the build: "RUN_TESTS". This is a nice little target when you have many more tests then we will have here. Basically if you attempt to build this target is runs all the executables you add with 'ADD_TEST'. It is also great for automated build/continuous integration environments since running the target is easy compared to finding all the individual tests.
Now, lets add the actual unit test code:
CMakeEnvironment/Libraries/Math/Tests/Main.cpp
#include <gmock/gmock.h> int main( int argc, char** argv ) { ::testing::InitGoogleTest( &argc, argv ); return RUN_ALL_TESTS(); }
This is a do nothing bit of code right now until we add some code to the Math library and of course add some tests. So, let's fill in the vector class real quick:
CMakeEnvironment/Libraries/Math/Include/Math/Vector3.hpp:
#pragma once #include <Math/Math.hpp> namespace Math { class Vector3f { public: Vector3f() {} Vector3f( float x, float y, float z ); float X() const {return mX;} float Y() const {return mY;} float Z() const {return mZ;} private: float mX; float mY; float mZ; }; }
CMakeEnvironment/Libraries/Math/Source/Vector3.cpp:
#include <Math/Vector3.hpp> using namespace Math; Vector3f::Vector3f( float x, float y, float z ) : mX( x ) , mY( y ) , mZ( z ) { }
Rebuild and the library should build, the test case should build and even run with the following output:
[==========] Running 0 tests from 0 test cases. [==========] 0 tests from 0 test cases ran. (1 ms total) [ PASSED ] 0 tests.
So it is time to add our first tests. Add the following files:
CMakeEnvironment/Libraries/Math/Tests/TestAll.hpp:
#include <Math/Vector3.hpp> #include "TestConstruction.hpp"
CMakeEnvironment/Libraries/Math/Tests/TestConstruction.hpp:
TEST( Math, Vector3f ) { Math::Vector3f test0( 0.0f, 0.0f, 0.0f ); EXPECT_EQ( 0.0f, test0.X() ); EXPECT_EQ( 0.0f, test0.Y() ); EXPECT_EQ( 0.0f, test0.Z() ); Math::Vector3f test1x( 1.0f, 0.0f, 0.0f ); EXPECT_EQ( 1.0f, test0.X() ); EXPECT_EQ( 0.0f, test0.Y() ); EXPECT_EQ( 0.0f, test0.Z() ); Math::Vector3f test1y( 0.0f, 1.0f, 0.0f ); EXPECT_EQ( 0.0f, test0.X() ); EXPECT_EQ( 1.0f, test0.Y() ); EXPECT_EQ( 0.0f, test0.Z() ); Math::Vector3f test1z( 0.0f, 0.0f, 1.0f ); EXPECT_EQ( 0.0f, test0.X() ); EXPECT_EQ( 0.0f, test0.Y() ); EXPECT_EQ( 1.0f, test0.Z() ); }
Modify CMakeEnvironment/Libraries/Math/CMakeLists.txt by adding the test headers:
ADD_EXECUTABLE( _TestMath Tests/Main.cpp Tests/TestAll.hpp Tests/TestConstruction.hpp )
And include the 'TestAll.hpp' from the file CMakeEnvironment/Libraries/Math/Tests/Main.cpp:
#include <gmock/gmock.h> #include "TestAll.hpp" int main( int argc, char** argv ) { ::testing::InitGoogleTest( &argc, argv ); return RUN_ALL_TESTS(); }
Regenerate, build and run. The test should output the following:
[==========] Running 1 test from 1 test case. [----------] Global test environment set-up. [----------] 1 test from Math [ RUN ] Math.Vector3f [ OK ] Math.Vector3f (0 ms) [----------] 1 test from Math (1 ms total) [----------] Global test environment tear-down [==========] 1 test from 1 test case ran. (5 ms total) [ PASSED ] 1 test.
Congratulations, you have a unit test for your new Vector3 class.
The completed environment and example unit test can be downloaded here
Please provide feedback on any build problems you might have and I'll attempt to get things fixed.
Conclusion
In this article we covered dealing with OS specific difficulties involving Windows and a couple more OsX issues. It has been a long haul to get to this point dealing with nitpicky items and a lot of explanation. The final result is a fairly easy to use and maintain environment which you can use to build unit tests and apply test driven development features to your coding. In a future article I intend to expand on the Math library and show some of the big utilities of using an environment such as this day to day. For now, my fingers are tired and my own code calls to me.
License
GDOL (Gamedev.net Open License)
Last few weeks I am moving from Win-only (Visual Studio) build to portable CMake version. One of few things to still figure out is unit testing integrated into the process. I came back after Easter and see this series - best gift I could ask for
Great work and thanks for doing this!
I might be missing something but:
1) should gmock/gtest results be displayed in VS "Output" window during the build?
2) breaking a test (say: Math::Vector3f test0( 0.0f, 0.0f, 0.0f ); EXPECT_EQ( 1.0f, test0.X() ); ) does not break the build and basically all looks OK. Is that desired behavior?
Since you mentioned ADD_DEFINITIONS...: how do you deal with #defines that have to be added only in specific variant of the build (like debug)?
The default behavior for GMockGTest is to dump the test output to std::cout and it doesn't know about OutputDebugString. I was considering adding an example of how to do that but this article was already quite large so skipped it. I should have probably mentioned that the way I usually work in Windows is to just set a break point at the end of the main, not a great solution but you can tab back to the output and see if the tests completed and all passed.
For #2, GMock/GTest catch and eat all errors, even full on program crashes are usually caught correctly and simply output as a failed test, which is proper.
This one gets to be a bit more difficult. I was considering if I should cover this later as at this point you get into some of the less well understood areas of CMake. But, there is a relatively simple solution if you need per build type definitions. CMake will add "_DEBUG" flags in all of the generators. So, if you need to differentiate some flags, just "#if _DEBUG" for the debug versions "#else" for the release versions.
Actually that is not what I meant. ATM my VS build is configured in this pretty sweet way:
gtest_main executable is executed as post-build step of dependent target which most importantly causes fail of main build (tests binary returns non-zero to VS) on failed test. On top of that, since testing is now part of the build, every test result is displayed in "Output" window and on error you can just double-click in it and it jumps to failed ASSERT/EXPECT (like wit normal errors and warnings).
I just love articles that explain a single problem in much detail, especially when it comes to the most basic thing before you start developing: the environment itself. Combined with the TDD approach, I'll definitely be using this in my own project.
One little thing: could you please correct the navigation links? The link to part 2 points to part 1. ;)
I took a look at the description you mentioned. That seems like a nice integration. I'll look into it further.
The one thing about the integration though is I will often have a couple tests which fail as I do refactoring work, so I don't want the tests to cause a failure when I run things most of the time. I just want to know which ones failed as I make changes. Especially when you have say 100+ tests going, a single failure may not be a horrible problem though knowing about it is a good idea.
Err, oops..
I'm traveling at the moment but I'll try to get it fixed up. Thanks for the feedback though, glad you like it.
As a note, I haven't yet decided what to do with the fourth article. The original intention was to get to an x-plat SIMD capable math library and use that to show some of the useful bits of the setup and why I use the embedded extra named directory. I'm trying to decide if I should continue on with the CMake first though as the setup and such has updated quite a lot. There are some things in the posted one done in less than the best manners, functional yes but intended for simplicity instead of using the absolute best practices. (With CMake it is not always obvious what the best case is of course.
)
I may attach the more advanced version up as a little after note to part 3 but the features will take another article to describe. Some of the interesting bits for folks would likely be the use of a configure system to generate a "Config.hpp" specific to your target and settings. The new settings include IOS support, control over SIMD (SSE1-AVX for Intel and Neon for Arm) and general cleanup and moving things around. Also of note was that In the posted version I forgot to properly cover the Xcode specific attribute variables which means Xcode can sometimes be a bit annoying since some things may fail once in a while. (It's just a random "I don't support Cxx11' compiles, the next time it will likely work.)
Anyway, that is a bunch more stuff which could take another part added to the article. Probably a good idea to go ahead and do that and push the other stuff a bit later.
If you add executing the individual test as a post-build step, the test will be run as a part of the build (and rerun every time the test is recompiled due to changes).
As this will make the compile fail if any test fails (and make will not build anything else if that happens unless started with -i), you should wrap the ADD_CUSTOM_COMMAND with an IF and only enable it on request (for use with IDEs).
EDIT: Note that MSVC will happily build the other targets even if tests fail, so the test failing during development isn't really an issue (but you get the information right away which is good!)
A very good point, unfortunately I had not introduced that CMake command and I didn't want to suggest anything which I had not documented and shown a more substantial example of. I want to keep this to the level of "practical" and not dig into every little feature of CMake, I figured a later article could show integration with CruiseControl or something like that and these items are a great place to discuss the custom commands.
For me personally, I just prefer to right click run tests when I'm done editing in VC since "building" is part of my process, even though I may not run the result yet, it is just a double check of my code to that point. So a failure during the build because I broke unit tests would annoy my normal working pattern. Not to mention that a couple of my tests are stressful and can take 10 seconds each to complete. Those are mock based tests though they get merged into the test results as normal.
Anyway, it is a good point and I wanted to revisit this now that I'm back from my trip. We'll see where it goes after Part 4 is posted.
Hi,
very interesting series, and really useful as I'm in the process of moving to CMake for a couple of projects I'm currently working on.
hi Abi,
First item: Oops!
Think I fixed it later but didn't update the various zip file attachments. GameDev needs a better method of integrating code into articles as the zip files are a pain to keep maintained.
Second: I'm not sure I'm following the idea. Though I suspect perhaps you are saying something like:
a .cmake file in the projects/libraries etc directories we include and each of those then defines what to include/use so we are only at one step removed? I might have to play with this, but honestly, I'm not sure it really changes the problem, just moves it. I'll have to think about it, I still have a couple more articles going so perhaps I'll hit a CMake part 5 with suggestions and fixes included.
Well, I'm just saying that after a PROJECT (<MYLIBNAME>) directive, it seems like cmake makes the <MYLIBNAME>_SOURCE_DIR variable defined to point where sources for that project are, so if <MYLIBNAME>'s includes are in a well defined relative path from its sources, you can get a valid pointer to their location everywhere by just using such variable e.g. <MYLIBNAME>_SOURCE_DIR/../Includes if there's an "Includes" folder at the same level where a Sources folder is.
Hope this clarifies my idea a bit, and looking forward parts >=5 for additional great content!
Think I understand now. Unfortunately it leaves a couple problems to be solved. There are three things which need to be exported from the libraries:
:The library to link against, and any which it may need to add to the build. For instance, if I link in a network library, I'd also need to pull ws_32.dll on windows to make it function.
:The various extra defines for the library, sometimes you have some extra's required, again picking on Window's you might need to define an OS version.
:The include directory of course but it can actually be multiple directories. Say for instance you have a renderer, it may need to include D3D/OpenGL directories also.
I'll keep looking at this but for the time being I think I like the explicit nature of the current version. It is a bit verbose but that let's it adapt to any edge cases. I'll keep thinking about it though.
I hit the same problem as you did with TR1 tuple lib in Xcode. Apparently google guys already saw that coming and added few compiler flags.
Just add one of the following to root CMakeLists.txt
# To force Google Test to use its own tuple library
ADD_DEFINITIONS( -DGTEST_USE_OWN_TR1_TUPLE=1 )
# or if you don't want Google Test to use tuple at all
ADD_DEFINITIONS( -DGTEST_HAS_TR1_TUPLE=0 )
Hope that helps.
I had tried to use the various flags, such as that one, but never got a working build for some reason. I decided that a little cheatery was just as easy as figuring out the problems. I will give it another try at some point but I was hoping the library would be updated before I tried again. | http://www.gamedev.net/page/resources/_/technical/general-programming/cross-platform-test-driven-development-environment-using-cmake-part-3-r2998?st=0 | CC-MAIN-2014-49 | refinedweb | 5,808 | 63.09 |
In many cases Go's default one thread concurrency is all you need to create concurrent programs that remain responsive to the outside world. After all many a modern programming language - JavaScript, Python and so on manage with a single thread or single UI thread.
If you do want to work with more than one thread then there are a number of ways of doing so but the simplest is to use the GOMAXPROCS method of the runtime.
For example if you add GOMAXPROCS(2) to the start of the previous example:
import ( "fmt" "runtime" "time")func main() { runtime.GOMAXPROCS(2) go count() time.Sleep(1) fmt.Println("end") for { } }func count() { for i := 0; i < 1000; i++ { fmt.Println(i) time.Sleep(1) }}
import (
"fmt"
"runtime"
"time"
)
func main() {
runtime.GOMAXPROCS(2)
go count()
time.Sleep(1)
fmt.Println("end")
for {
}
}
func count() {
for i := 0; i < 1000; i++ {
fmt.Println(i)
time.Sleep(1)
Notice that now the main program ends with an infinite loop.
What would you expect to happen in the single thread case?
The main program would release the thread to the goroutine which would print zero and then block, so releasing the thread back to the main program which then enters an infinite loop and keeps the thread busy.
This is not what happens.
As we have allocated two threads to the program the go routine starts to run as soon as it is called on a separate thread to the main program. It prints zero and then blocks for 1 millisecond. The main program continues to run on its thread and also blocks for 1 millisecond. When the main program restarts it prints "end" and starts an infinite loop. However in this case the goroutine isn't blocked because it is running on a different thread. When its sleep is over it continues to print the rest of the values up to 999.
This is a true multithreaded program and while it can be more powerful it can be more difficult.
In particular if you are using multiple threads your programs are no longer deterministic because the order that things occur in depends on how the threads are scheduled.
For example if you run the demo program repeatedly you will sometimes see:
01end2
and sometimes
0end12
depending on how fast the thread running the goroutine is.
So far the facilities for concurrent programming look a little ad-hoc if easy to use. The whole thing suddenly starts to make sense when you learn about channels. A channel is a simple data structure - something like a typed array or buffer - that can be shared safely between goroutines.
To declare a channel you use something like:
ch:=make(chan type,size)
where type is the type of data stored int he channel and size is the number of elements. If you don't specify a size you get a single element or unbuffered channel.
To assign a value to a channel you use the <- operator and to retrieve a value you use the -> operator. For example:
ch <- a
and
a <- ch
This is where things get interesting. As well as allowing values to be passed channels also act as a blocking mechanism that frees a thread to run another goroutine. For a single element channel the rules are:
a routine that performs a channel read blocks until a value is available.
a routine that performs a channel write blocks until the value has been read by another routine
These two rules result in the more or less automatic passing of the thread of execution between goroutines - you don't need to worry about calling Sleep or another blocking operation simply reading and writing to a channel frees the thread to run another goroutine.
To see this in action consider the following main program:
func main() { ch := make(chan int) go count(ch) j := <- ch}
ch := make(chan int)
go count(ch) j := <- ch}
This creates an unbuffered int channel calls a goroutine, passing it the channel and then retrieves a value from the channel. When the main program reached the channel read it blocks because the goroutine is also blocked and there is no value in the channel. The thread is freed up and runs the goroutine which could be something like:
func count(ch chan int) { ch <- -1}
func count(ch chan int) {
ch <- -1
This stores -1 in the channel and blocks so freeing the thread of execution which returns to the the main program. This retrieves the value from the channel and ends along with the goroutine.
You can see that the channel in this case both allows communication between the two routines i.e. the passing of the value -1 and the automatic sharing of the thread of execution. That is when the main program needed a value from the goroutine it blocked which allowed the goroutine to execute until it had the value that the main program needed when it blocked and the main program started. All very neat!
For a slightly more advanced example consider:
func main() { ch := make(chan int) go count(ch) for { j := <-ch if j < 0 { break } fmt.Println(j) }}
go count(ch)
j := <-ch
if j < 0 {
break
}
fmt.Println(j)
This calls the goroutine count and then blocks waiting for values that it returns until it gets a -1 which it treats as a "terminate" condition. The goroutine is:
func count(ch chan int) { for i := 0; i < 10; i++ { ch <- i } ch <- -1}
for i := 0; i < 10; i++ {
ch <- i
}
Notice that the for loop in the goroutine blocks and is effectively suspended until the main program has finished processing the value and asks for another. This is more subtle than you might think at first because while the goroutine unblocks when the main routine reads the value from the channel it doesn't get the thread back until the main routine asks for another value and blocks. Consider how this would be different if you allocated two threads to run program.
Go's channel based concurrency is subtle but mostly safe and easy to use. The trick is that for a goroutine to run it has to be unblocked and there has to be a thread free to run it.
Now we have to look at buffered channels. In the case of a buffered channel the blocking rules are that the routine that reads from the channel blocks until there is something to read. The routine that writes only blocks only if the channel is full and a value cannot be written.
Buffered channels basically allow situations where a goroutine can fill the buffer before giving up the thread to other routines to empty the buffer. It can also be used to implement classic concurrency object such as the semaphore. You can use the size of the buffer to limit the number of routines accessing a resource.
It is difficult to find a very simple example of using buffered channels but this one is as close to simple as I can manage. Consider the following main program:
func main() { ch := make(chan int, 2) go count(ch) for { j := <-ch if j < 0 { break } fmt.Println("main", j) }}
ch := make(chan int, 2)
break
fmt.Println("main", j)
This simply sets up a channel with two elements and then reads values from it printing them as it goes - again -1 is taken as a signal to stop.
The goroutine is just:func count(ch chan int) { for i := 0; i < 10; i++ { ch <- i fmt.Println("goroutine", i) } ch <- -1}
func count(ch chan int) { for i := 0; i < 10; i++ { ch <- i fmt.Println("goroutine", i) } ch <- -1}
fmt.Println("goroutine", i)
This adds values to the channel and then prints the value.
What you will see is:
goroutine 0goroutine 1main 0main 1goroutine 2goroutine 3main 2main 3
goroutine 0goroutine 1main 0
goroutine 0
goroutine 1
main 1goroutine 2goroutine 3main 2main 3
main 1
goroutine 2
goroutine 3
main 2
main 3
and so on.
What happens is that the goroutine gets the thread when the main routine asks for a value and blocks. It places two values in the channel and prints them out. When it tries to add a third value it blocks because the channel is full and so the thread returns to the main routing which prints two value and then blocks because the channel is empty. The goroutine then adds two more values and blocks and so on until its all done.
Try changing the size of the channel to 3 and you will see each routine print three values each time.
Consider how all of this changes if there is more than one thread of execution.
In these three brief looks at Go we have examined the key features that make it special - types, objects and concurrency. Go is still a very young language and it has lots of room to expand, but currently you have to admit that it is light and flexible. It is a language to keep an eye on for the future..
<ASIN:0321817141>
<ASIN:1478355824> | http://www.i-programmer.info/programming/other-languages/6678-a-programmers-guide-to-go-with-liteide-part-3-goroutines.html?start=1 | CC-MAIN-2014-42 | refinedweb | 1,526 | 67.79 |
.]]>
By .]]>.
D..
I.]]>
Since.]]>
I.]]>
For.]]>
One
of the most common
Flex Builder debugger complaints is that when you bring up the dialog to add a
new expression to the Expressions view (e.g. via right-click > Add Watch
Expression), you cannot dismiss this dialog using the keyboard alone. The
dialog has a multi-line edit box, and if you press Return, that just adds a
carriage return to the edit box. Similarly, trying to tab out of the edit box
doesn’t work – it just inserts a tab character into the edit box.
This drives keyboard-heavy users (like me) crazy. However, it turns out that there is a way to dismiss this dialog from the key:
Type Shift+Return instead of Return.
There is, in fact, a good reason why this dialog has a multi-line edit box. As explained in this Eclipse bug, some languages (including Java) allow you to enter more than just a simple expression into this box. And since the dialog comes from Eclipse’s code rather than from Flex Builder’s, we can’t just change it to have a single line.
Since this is such a common point of frustration for Flex Builder users, in the above-linked bug I have asked that they find some way to make this easier for people to deal with, e.g. by perhaps having a short message in the dialog mentioning Shift+Return. But in any case, you now know the secret handshake – enjoy!]]>
Even.]]>
Suppose.]]>
I.”)]]>
Thanks to everyone who came to David’s and my talk at MAX today, Extending Flex Builder. I promised to post the sample code for the part of the talk which discussed design.xml.
So here it is. This ZIP file contains two projects:
MyLibraryis the main interesting part. It contains
design.xml, a Flex manifest, and a sample component. See the slides (linked above) for an explanation of how all this stuff hooks together.
MyFlexProjectis just a simple Flex Project that has
MyLibrary.]]>.]]>
I.
Click for a closer view::
Hope to see you there!]]>.]]>
This a little Firefox Greasemonkey.
It only works with the Firefox web browser. If you are using another browser, such as Internet Explorer or Safari, Netflix Notes won’t work for you.
I would love it if Netflix obsoleted my work by integrating this functionality natively into their website! But in the meantime, you can use my program...
I am excited to announce that Adobe, in its continuing efforts to port AIR to as many platforms as possible, has begun work on porting AIR to CP/M. Today I brought my beautiful old Osborne 1 in to the office to get started on the job.
The project is off to a slow start – at this point, the computer still doesn’t boot.
]]>.
The.
I use Gmail, and although I love it in general, one thing that is a little tedious is that when you want to send someone an attachment, you can’t drag and drop the attachment onto your message like you can with most native email clients – instead you have to click “Attach a file,” then click “Browse,” and then browse to the file that you want to attach.
But dragdropupload is a slick little Firefox extension that addresses this problem. Once you install it, you can drag and drop any file from your computer on top of the words “Attach a file” in Gmail. Sweet! (You can also drag and drop onto any other website that does file upload, but Gmail is where I find it most useful.)]]>
Today I typed “wikipedia” into Google. Look at the weird subcategories that showed up under the main wikipedia.org link:
What the?!?
So of course I clicked ‘em all. “Wikipedia:Hauptseite” and “Accueil” take you to the home pages of the German and French versions of Wikipedia, respectively. “Tirol” takes you to the German-language page describing Tirol, which is apparently “a historical region of Western Central Europe” (according to the corresponding English-language page). The last three links take you to the English-language pages for the movie Chitty Chitty Bang Bang, Denzel Washington, and commodity markets.]]>
This is hilarious. Lacra, one of the Flex engineers on our team in Romania, filed this bug, which points out a place in Flex Builder where there is a list of country codes that includes “Romania, Socialist Republic of (RO).” As she writes, “The list of countries in the dialog that opens mentions Romania as a socialist republic! It hasn’t been one in 18 years :) It is a (democratic) republic.”]]>
I’ve been meaning to post this ever since we released Flex Builder 3 Beta 2 a few weeks ago. There are some nice debugger enhancements I wanted to tell you about (in addition to the features that were in beta 1, which I described in June).
Reduces clutter in the Variables view by grouping all superclass members in a separate tree node, so by default you only see the members of the current class.
Previously, if any variables such as “this” were expanded in the variables view (so that their members were visible), then single-stepping in the debugger was somewhat slow. It is now much, much faster – in fact, single-stepping with variables expanded is just as fast as single-stepping with variables collapsed. In one quick test I just ran, single-stepping in Flex Builder 3 was twenty times faster than in Flex Builder 2. In Flex Builder 3, I can just hold down F5, and even on a slow machine, it is executing about ten single-steps per second.
Now when the Flash player runs a debuggable application (swf) but can’t find a debugger, it just runs the app, with no annoying dialog. (If you want to force it to prompt for a debugger, do right-click > Debugger on the swf running in the browser.)
binfolder.
Flex Builder 2 created YourApp.swf and YourApp-debug.swf – and also
YourApp.html and YourApp-debug.html. Flex Builder 3 no longer creates the
"*-debug" files. This speeds up compilation – Flex Builder only has to
create one swf – and greatly simplifies writing code that has to refer to
other swfs by filename.
In Flex Builder 3, the files in the “bin” directory are debug files. (Before we ship, we will probably rename that folder to “bin-debug”.) To get the release files, use the Export Release Version command, which creates a separate “bin-release” directory. There are more details in this blog post and in this video.
]]>]]>!]]>).]]>
Please.]]>
I’ve been meaning to post this for a while – here is the PowerPoint presentation for the debugger talk I gave at 360Flex: Flex Builder Debugger]]>
As cool as I think E4X is, there are a few things about it that can throw you off when you’re getting started (they certainly took me a while to get used to). I thought I would pass on these tips.
It is a very common mistake to think that your E4X expression needs to specify
the top-level
var personNodes:XMLList = myService.lastResult.people.person; // wrong
That doesn’t work. You should think of the
myService.lastResult as being
synonymous with the top-level node. So the way you get a list of the
var personNodes:XMLList = myService.lastResult.person; //
To fix this, you instead use an E4X expression that specifies exactly which
child nodes of the
// iterate over all immediate children for each (var mouse:XML in cats.*) { ... } // or if you prefer: iterate over only those immediate // children that are <mouse> nodes for each (var mouse:XML in cats.mouse) { ... }
‘myPetRabbit’ held a list of more than one node,
myPetRabbit.@name is still a
legal expression; it simply returns a list of all “name” attribute nodes of all
of those:
]]>.
${project}
MyProject.
${application}
MyApp.
${version_major}
9for version 9.0 r28. You can change this and the other
${version_...}macros by going to Project > Properties, then “Flex Compiler” or “ActionScript Compiler,” and then changing the player version number in the “HTML wrapper” section.
${version_minor}
0for version 9.0 r28.
${version_revision}
28for version 9.0 r28.
${build_suffix}
"-debug"when building the debug version of the SWF, and
""when building the release version.
${swf}
.swfextension, e.g.
MyAppor
MyApp-debug. This is essentially a convenience macro which is equivalent to
${application}${build_suffix}.
${bgcolor}
backgroundColorattribute of the
<mx:Application>tag, or, in the case of ActionScript-only projects, in the
backgroundColorfield of the
[SWF]metadata attribute of the main application class, e.g.
[SWF(backgroundColor="#ffffff")] public class MyApp extends Sprite(see this post for more information on setting the width, height, and background color of an ActionScript project). The result is in the form
#rrggbb, e.g.
#ffffff. This can actually be a little tricky to use, because by default, the background of a Flex app is actually a gentle gradient from one color to another; if you want the HTML background to match the background of your Flex app, you may need to fiddle with both the
backgroundColorand
backgroundGradientColorsattributes of the
<mx:Application>tag.
${width}
widthattribute of the
<mx:Application>tag, or, in the case of ActionScript-only projects, in the
widthfield of the
[SWF]metadata attribute of the main application class, e.g.
[SWF(width="300", height="400")] public class MyApp extends Sprite.
${height}
heightattribute of the
<mx:Application>tag, or, in the case of ActionScript-only projects, in the
heightfield of the
[SWF]metadata attribute of the main application class, e.g.
[SWF(width="300", height="400")] public class MyApp extends Sprite.
${title}
pageTitleattribute of the
<mx:Application>tag, or, in the case of ActionScript-only projects, in the
pageTitlefield of the
[SWF]metadata attribute of the main application class, e.g.
[SWF(pageTitle="flex r00lz")] public class MyApp extends Sprite.
Meet.)]]>
Yesterday.]]>
Where is the bug in this program? It seems to run just fine. But there is a bug. Can you find it?
package { import flash.display.Sprite; import flash.events.Event; public class MyClass extends Sprite { public function MyClass() { this.addEventListener(Event.ENTER_FRAME, function(e:Event):void { trace("enter frame") }, false, 0, true); } } }
Ly.}.
E.]]>
Okay,: .”
So, from now on, I plan to specify a frame rate of 60 for all of my Flex applications:
<mx:application
and ActionScript applications:
[SWF(frameRate="60")] public class MyApp extends Sprite { ... }
A.]]>.]]>
For a Flex project with MXML files, it is obvious how to set the width and height of the project:
<mx:Application
But for pure-ActionScript projects, it isn’t so obvious. The way to do it is
to use the
SWF metadata attribute above the declaration of the class:
package { [SWF(width="300", height="200")] public class MyApp extends Sprite { ... } }
The values specified there are pixel sizes; in this context, you are not allowed to use percentage values such as 100%.]]>
Let’s write a plugin for the Flex Builder debugger. This will be a simple panel called Expression Tracker, which is like the Expressions view except that it does not refresh its displayed values each time you step. Don’t expect anything useful or beautiful here; this is just a barely-functional sample with a pretty rotten UI. But it’s a start.
I should warn you that creating Eclipse plugins takes a large investment of effort to understand how they fit together.
You’ll need to be using the plugin-based version of Flex Builder rather than the standalone version. This means that first, you have to install Eclipse version 3.1.2 from. Then, you have to install the plugin version of Flex Builder:
The standalone version of Flex Builder is only for writing and debugging Flex applications. But the plugin version is a set of plugins that you install on top of Eclipse, to enable the creation of Flex projects in addition to other types of projects. Flex Builder plugins are written in Java.
File > New > Project; Plug-in Development > Plug-in Project.
Project name: “ExpressionTracker”. Click Next, then Next.
Use the “Plug-in with a view” template, so Eclipse will fill in some boilerplate code for us:
Click Next, and change the classname and a few other settings as follows. The “View Class Name” is the name of the Java class; the “View Name” is the name displayed to the user in the tab for that view; and the “View Category ID” and “View Category Name” control where it shows up under “Window > Show View > Other”:
The above settings will cause your view to show up in the “Flex” category
of views. If you would rather have your plugin show up in the “Debug”
category, then use a View Category ID of
org.eclipse.debug.ui, and a view
category name of “Debug”. Or, make your own new category if you want, such
as “Acme Awesome Flex Extensions.” and exploring for a bit. The
various Eclipse templates are very useful for showing you how to hook
everything together. In here, you will see some simple examples of
context-menu commands, double-click handlers, and so on.
Insert these two functions into
ExpressionTrackerPlugin.java. You should
put these in every Eclipse plugin you make, and whenever you have caught an
exception that indicate an error condition, you should call
«YourPluginClass».log(), to send it to the “Error Log” view:
/** * Logs the given status to this plug-in's error log. * * @param message * general message, e.g. "Error during initialization" * @param t * exception associated with this error, or null */ public static void log(String message, Throwable t) { getDefault().getLog().log(createStatusError(message, t)); } /** * Create and return an IStatus object with ERROR severity and the given * message and exception. */ public static IStatus createStatusError(String message, Throwable t) { if (message == null) { message = t.getLocalizedMessage(); if (message == null) message = ""; } return new Status(IStatus.ERROR, getDefault().getBundle() .getSymbolicName(), IStatus.ERROR, message, t); }
Replace your
ExpressionTrackerView.java with this completed
version.
Let’s go through that new version and look at the interesting debugger-related parts. Given an expression, how do you get its value? Answer: You get a reference to Eclipse’s global “expression manager;” tell it to create an expression; tell that expression to evaluate itself in a specified context (stack frame); and then wait until Eclipse sends you an event telling you the evaluation has completed. The relevant source:
ExpressionTrackerView constructor: Start listening for all debug events.
public ExpressionTrackerView() { // We register to be notified of all debug-related events, so that // we will be notified whenever an expression has been evaluated. DebugPlugin.getDefault().addDebugEventListener(this); }
ExpressionAndValue constructor: the user has said to add a new expression to
the view. Create it, and tell it to evaluate itself.
// Get the expression manager, and create a new watch expression IExpressionManager expressionManager = DebugPlugin.getDefault().getExpressionManager(); watchExpr = expressionManager.newWatchExpression(expr); // Figure out the "context" of this watch expression -- that is, which // stack frame is currently selected in Eclipse's "Debug" view? IDebugElement debugElement = null; IAdaptable debugContext = DebugUITools.getDebugContext(); if (debugContext != null) debugElement = (IDebugElement) debugContext.getAdapter(IDebugElement.class); if (debugElement == null) { value = "<no debug context>"; } else { // Have the watch expression begin evaluating itself. When it is // done, it will dispatch a DebugEvent, which we will see in our // handleDebugEvents() function. value = "..."; watchExpr.setExpressionContext(debugElement); watchExpr.evaluate(); }
ExpressionTrackerView.handleDebugEvents(): Called by Eclipse whenever any
debugger-related event takes place – a process starts or terminates, a
breakpoint is hit, etc. Our code will look for debug events that indicate that
one of our expressions has been evaluated, and when it has, call
ExpressionAndValue.doneEvaluating():
public void handleDebugEvents(DebugEvent[] events) { for (int i=0; i<events.length; ++i) { DebugEvent event = events[i]; if (event.getKind() == DebugEvent.CHANGE) { Object source = event.getSource(); if (source instanceof IWatchExpression) { for (int j=0; j<items.size(); ++j) { ExpressionAndValue item = (ExpressionAndValue) items.get(j); if (item.watchExpr == source) { item.doneEvaluating(); break; } } } } } }
ExpressionAndValue.doneEvaluating(): Check if the expression evaluation
encountered errors, such as syntax errors. If so, display the error;
otherwise, display the vlaue.
if (watchExpr.hasErrors()) { String[] errorMessages = watchExpr.getErrorMessages(); if (errorMessages.length > 0) { // We should really display all the error messages, // not just the first... this.value = errorMessages[0]; } else { this.value = "Error"; } } else { IValue exprValue = watchExpr.getValue(); if (exprValue != null) this.value = exprValue.getValueString(); else this.value = ""; }
That is pretty much all the debugger-related functionality in the code. Give it a try now. Run a child instance of Eclipse again. Create a Flex Builder project. Open the Expression Tracker view. Right-click, and add an expression or two.
A masterpiece.
The main thing you need to know is: File > Export > Deployable plug-ins and fragments. This command will package up your plugin in a form that is easy to publish.]]>ools.]]>.]]>
When you create a new project, Flex Builder creates a directory in the project
called
html-template, which contains a generic HTML wrapper for your Flash
application. The files in that directory are based on the project properties
under the “Flex Compiler” tab (for Flex projects) or the “ActionScript
Compiler” tab (for ActionScript projects).
If you want to customize the template for a single project, that’s easy – just
modify the files that are in
«myproject»\html-template.
If you want to modify the templates that are generated for all new projects, that can be done too, although it takes a little more effort. The HTML wrappers are in
«myworkspace»\.metadata\.plugins\com.adobe.flexbuilder.project\html-templates
where
«myworkspace» is, um, your workspace – that is, the directory you see
if you do File > Switch Workspace. (After doing File > Switch Workspace and
copying the dir, you can just click Cancel, to sta in the current workspace.)
In that directory, you will see six subdirectories. These correspond to the different options in the above-mentioned project properties page:
So, go to those directories; customize all you want; and then re-launch Flex Builder. From then on, any new projects you create will use the modified templates.
I should warn you that if you make any customizations in this area, there is a chance they may get clobbered when the final release of Flex Builder comes out.]]>
Beta.]]>
David Zuckerman, also on the Flex Builder team, has written a totally awesome extension plugin for Flex Builder. It provides “Quick Fix” – with a quick keystroke or two, you can tell Flex Builder to automatically fix certain common errors and warnings. For example, say you wrote this:
function f() { return "hello"; }.]]>:
]]>
Flex Builder 2.0 has some really great ways to quickly navigate through your source code – e.g. “go to definition” and stuff like that. Most of these are based on similar features in Eclipse’s Java editing environment (the JDT).
Ctrl-O: Lightweight popup with list of functions in current file. Great for quick navigation within a file.
Ctrl-Shift-T: Open type. A quick way to go to the source for any class.
Ctrl-Click or F3: Go to definition. Ctrl-click on just about anything – function name, variable name, etc. – to go to its definition. F3 does the same thing.
Alt-Left, Alt-Right; or yellow arrows on toolbar: Back, Forward navigation, like in a web browser.
Ctrl-Shift-O: Organize imports – makes them alphabetical and tidy.
Ctrl-Space: Code hinting (of course).
Ctrl-Shift-Space: Restores tooltip showing the args of the function you are trying to call, e.g. if you have already written “foo(” but then moved somewhere else so the codehint had gone away]]>
I’m a freelance software developer. I spent eight years at Adobe, working on Flash Builder and Dreamweaver. Before that, I spent ten years at Microsoft, where I worked on Visual Studio’s debugger for a number of years, then on interactive TV, and then on sidewalk.com.]]> | http://feeds.feedburner.com/mikemo | CC-MAIN-2018-26 | refinedweb | 3,287 | 65.12 |
- NAME
- SYNOPSIS
- DESCRIPTION
- FEATURES
- WHENCE MOOS
- ON SPEED
- SEE ALSO
- AUTHORS
NAME
Moos - Moo s{imple,peedy,ingle}
SYNOPSIS
package Foos; use Moos; extends 'Boos'; with 'Cloos'; has this => (); has that => 42; has other => ( builder => 'build_other', lazy => 1, ); sub BUILD { my $self = shift; # build, build, build } sub BUILDARGS { my ($self, @args) = @_; # munge, munge, munge return {%munged_args}; }
DESCRIPTION
Moos completes the M to Moose sequence of Perl OO modules.
This one is pure Perl, single file and mostly Moose compatible (for what it does). Moos has no non-core dependencies, but certain features (roles, debugging functions, legacy Perl support) do require additional modules. If you steer away from those features, you don't need those additional modules.
FEATURES
Here's a quick list of the Moose compatible features that are supported by Moos.
strict/warnings
Turns on
strict and
warnings for you.
Helpful exports
The ever useful
blessed (from Scalar::Util) and
confess (from Carp) are exported to your namespace.
extends
For inheritance.
Moos::Object is the default base class.
package MyClass; extends 'MyBaseClass';
Supports multiple inheritance, by allowing multiple classes on a single invocation.
with
Moos can consume roles using the
with keyword. Using this feature requires Role::Tiny to be installed.
with 'ThisClass', 'ThatClass';
has
Accessor generator. Supports the
is,
default,
build,
lazy,
clearer,
predicate,
required,
handles and
trigger options, described below. The supported options are about the same as Moose. Other arguments (e.g.
isa and
coerce) are currently ignored.
has this => ();
NOTE: Class::XSAccessor will be used for simple accessors if it is installed. This can be disabled by setting $Moos::CAN_HAZ_XS to false or by setting the PERL_MOOS_XS_DISABLE to true.
- is
Specify which type of attribute accessor to provide. The default is "rw", a read-write accessor. Read-only "ro" accessors are also supported.
has this => ( is => "ro" ); has 'this'; # read-write has that => (); # read-write
Unlike Moose, Moos cannot generate differently named getters and setters. If you want your setter named something different (e.g. a private method), then you could do something like:
has this => ( is => 'ro' ); sub _set_this { $_[0]{this} = $_[1] }
- required
Require that a value for the attribute be provided to the constructor or generated during object construction.
has this => ( required => 1 );
- lazy
Don't generate defaults during object construction.
has this => ( builder => '_build_this', lazy => 1 );
- trigger
A coderef which will be called when the attribute is assigned to via a method call or the constructor. (But not when an attribute is implicitly given a value via a default or builder.) The coderef is called with the instance as the first parameter, the new value as the second parameter, and the old value (if any) as the third parameter.
has age => ( trigger => sub { croak "non-numeric age" unless looks_like_number($_[1]); } );
Triggers can be used to emulate Moose's type constraints, coercion and weakened reference features, but if you find yourself doing this frequently then you should consider upgrading to Moo or Moose.
- handles
Delegated method calls.
has wheels => (handles => [qw/ roll /]);
This accepts a hashref or arrayref, but not the other possibilities offered by Moose.
- builder
Specify the method name to generate a default value.
has this => ( builder => '_build_this' ); has that => ( builder => 1 ); # accept default name for method
- default
Specify the sub to generate a default value.
has this => ( default => sub { 42 } );
Moos provides a shortcut for specifying the default. If the number of arguments (after the name) is an odd number, then the first argument is the default. The following forms are valid:
has a => 42; has b => 'string' => (lazy => 1); has c => {}; has d => [1, 2, 3, 4];
These all result in creating a Moos
defaultargument. If the default is an array or hash reference, a shallow copy is made.
- clearer
Creates a clearer method.
has this => ( clearer => "clear_this" ); has that => ( clearer => 1 ); # accept default name for method
- predicate
Creates a predicate method, which can be used to check if the attribute is set or unset.
has this => ( predicate => "has_this" ); has that => ( predicate => 1 ); # accept default name for method
Class and Object Methods
- new
A constructor class method.
my $object = MyClass->new(this => 'nice', that => 2);
- BUILD
Custom object construction. If you define BUILD, it is passed the value of the new object during construction. You can modify the object. Any value you return is ignored.
sub BUILD { my $self = shift; ... }
- BUILDARGS
Custom constructor argument processing. If you define BUILDARGS, you can control how the constructor's arguments are built into the object hashref.
sub BUILDARGS { my ($class, @args) = @_; ... }
- dump
Returns a textual dump of the object.
- meta
Returns a Moos::Meta::Class object for the class. This has a very limited subset of Moose::Meta::Class' functionality, including implementations of the following methods:
name,
attribute_metaclass,
add_attribute,
add_method,
superclasses,
linearized_isa,
new_object,
get_all_attributes,
get_attributeand
find_attribute_by_name.
The attribute introspection methods return Moos::Meta::Attribute objects which provide a very limited subset of Moose::Meta::Attribute's functionality, including implementations of the following methods:
name,
associated_class,
predicate,
clearer,
default,
builder,
trigger,
required,
lazyand
documentation.
- does/DOES
Methods to check whether the classobject performs a particular role. The methods differ in that
doeschecks roles only in the MooseMoo/Role::Tiny sense;
DOESalso takes into account UNIVERSAL::DOES.
Roles
If you need roles, then Moos classes have experimental support for Role::Tiny, Moo::Role and Moose::Role roles. (Moos provides a
with command that uses Role::Tiny to do the work.)
{ package Local::Class; use Moos; with "Local::Role"; ...; }
Limitations: Note that Moo and Moose each allow type constraints for attributes; Moos does not. This means that if you compose, say, a Moose::Role into a Moos class, you end up with a strange situation where the accessor methods will enforce type constraints (because they were generated by Moose) but the constructor will not (because it is inherited from Moos::Object).
See also Moos::Role.
Method Modifiers
If you need method modifiers, then try Class::Method::Modifiers.
Development Options
Moos has a couple of builtin dev options. They are controlled by environment variables.
- PERL_MOOS_ACCESSOR_CALLS
By setting this environment variable, Moos will warn everytime an accessor method is called.
- PERL_MOOS_XXX
By setting the environment variable, Moos will export the XXX debugging keywords.
WHENCE MOOS
I(ngy) created Moos during Pegex development. Pegex uses a clone of Moos called Pegex::Base. (Moos ships with a commandline utility called
remoos that does this cloning.)
Pegex is a parser framework and needs to be fast. While looking into speed issues I noted that accessor calling was the biggest hit. I tried all the various Mo* solutions and Mouse was the fastest.
I was happy until I remembered that Mouse uses XS, and for various reasons this broke my toolchain (TestML, Module::Install, etc).
So I made a single module/file Moose clone and it worked out well. I've shared Pegex::Base as Moos in case any other projects want it.
Later on, Toby Inkster added a bunch of low-cost but very handy features from Moose.
The name Moos was chosen because it was the only name left between M and Moose. (Thus adding to the epic confusion that we embrace as Perl Mongers! :)
ON SPEED
In the end, I got Pegex to run even faster with Moos than it originally did with Mouse. I'll tell you my secret...
Accessors (usually) do not need to be method calls.
Replace these:
my $foo = $self->foo; $self->foo($foo);
with:
my $foo = $self->{foo}; $self->{foo} = $foo;
And your code will be faster (and a bit uglier).
The only time that you need to call an accessor method is when you are accessing a property and it might invoke a
lazy
builder,
default or
trigger method. Otherwise you are just wasting time. At least with the minimal feature set offered by Moos.
The PERL_MOOS_ACCESSOR_CALLS feature described above is for finding these method calls.
Note that third parties can still use your module's accessor methods like they would expect to.
I'm sure I've missed some subtleties, and would be glad to hear opinions, but in the meantime I'm happy that my code is faster and pure Perl.
SEE ALSO
AUTHORS
Ingy döt Net <ingy@cpan.org>
Toby Inkster <tobyink@cpan.org>
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See | https://metacpan.org/pod/release/INGY/Moos-0.30/lib/Moos.pod | CC-MAIN-2019-43 | refinedweb | 1,391 | 65.22 |
Hi there, I have just installed office XP on my
system yesterday and I am quite pleased with
the interface and look of the frontpage.
However I got some problem when I want to
import pictures in from Paint to Frontpage
via the cut-and-paste method
Like for example, I drew something on Paint, and
then I just copy and paste it to Frontpage. Before
XP I uses Office2000 and it worked just fine, but
now the image that I paste to frontpage becomes
‘deformed’ - Any idea about this one?
I tried to look in option or tools hoping that there’s
some option that can configrue this image handling
features but it seems that FrontapgeXP doesn’t have
that features to configure at all.
well ? | https://forum.kirupa.com/t/a-question-on-office-xps-frontpage/4020 | CC-MAIN-2020-45 | refinedweb | 127 | 65.59 |
Crust Vol. 2
Turbulence
"ahhhh!", Telbur exclaimed, crashing to the deck plates, feeling his ankle shatter, under the unforgiving and sudden return of artificial gravity, as his breath was forced from his already recovering lungs.
Struggling to regain focus, amidst the onslaught of warning lights and sirens, he cried out, "Silya, what happened?"
"I have just reinitialized the artificial gravity inducers and..."
"I know that!!!", Telbur snapped, feeling the pain reverberating up and down his right leg.
Doing his best to regather his senses, he collected his thoughts and asked, exasperatedly, "Did we come out in an... asteroid field?"
"No. We are straddling a temporal stream. I am attempting to stabilize our vector."
Momentarily forgetting the excruciation pain, threatening to overcome his body, Telbur felt his heart drop to the pit of his stomach.
How could this be. I ordered us to enter before the probe.
"Telbur, your vital signs are sporadic. I recom..."
"Never mind that, I'm fine, for now!"
Blasted A.I.!!!,Telbur thought, condemning the "mandated" protocols of artificial intelligence, "to do no harm and preserve life". He often thought that the programmers must have never been in an actual emergency!
"Silya, did you exit at a parsec, before the temporal probe, as specified?"
"Affirmative. Sensors did not detect any anomaly."
"Damn", Telbur thought.
"This is bad.", he said, half-heatedly, to himself.
"Yes. It is bad. However..."
"Shut up, Silya!", he said, managing to smack his face.
"Wait! However, what?"
It was as if Silya expected the question.
"However, the temporal stream appears to be fluctuating in a repeating recurrence, which is allowing my sensors and processors to extrapolate a slip point of exit."
Imperceptibly, to all sensors--so he thought--Telbur released a sigh of relief, at the good news.
"Is there any way to smooth out our ride?", he asked, dreading the thought of the slow crawl to the Bejiri chamber.
"I have compensated our natural course, to match the temporal stream."
There was a pause, and then, "Might I suggest you make your way to the Bejiri chamber? I have summoned the medihic."
Good, ole Silya. The medihic is functional.
"Thank you, Silya". An unnecessary etiquette, but human.
"I will revive you, should circumstances change".
To be continued...
oh oh - - this sounds quite serious. Hope this robot knows what it's doing! Could it have slipped past a point of no-return (for human, at any rate)? Yegads! | http://hubpages.com/literature/Crust-Vol-2 | CC-MAIN-2017-09 | refinedweb | 406 | 70.09 |
Interview with Don Kretsch
By Darryl Gove on Apr 04, 2014
As well as filming the "to-camera" about the Beta program, I also got the opportunity to talk with my Senior Director Don Kretsch about the next compiler release.
As well as filming the "to-camera" about the Beta program, I also got the opportunity to talk with my Senior Director Don Kretsch about the next compiler release.
Here's a short video where I talk about the Solaris Studio 12.4 Beta programme..
The preview docs for Solaris Studio 12.4 are now available.....
This was a complete surprise to me. A box arrived on my doorstep, and inside were copies of Multicore Application Programming in Chinese. They look good, and have a glossy cover rather than the matte cover of the English version.
The slides from all the JavaOne and Oracle Open World presentations have been posted. You can find my slides at:
I'm very excited to have been invited to present at the UK Oracle User Group conference in Manchester, UK on 1-4 December.
Currently I'm down for two presentations:
As you might expect, I'm very excited to be over there, I've not visited Manchester in about 20 years!
I.
Just); } }..
fprintf() does buffered I/O, where as write() does unbuffered I/O. So once the write() completes, the data is in the file, whereas, for fprintf() it may take a while for the file to get updated to reflect the output. This results in a significant performance difference - the write works at disk speed. The following is a program to test this:
#include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <stdio.h> #include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> static double s_time; void starttime() { s_time=1.0*gethrtime(); } void endtime(long its) { double e_time=1.0*gethrtime(); printf("Time per iteration %5.2f MB/s\n", (1.0*its)/(e_time-s_time*1.0)*1000); s_time=1.0*gethrtime(); } #define SIZE 10*1024*1024 void test_write() { starttime(); int file = open("./test.dat",O_WRONLY|O_CREAT,S_IWGRP|S_IWOTH|S_IWUSR); for (int i=0; i<SIZE; i++) { write(file,"a",1); } close(file); endtime(SIZE); } void test_fprintf() { starttime(); FILE* file = fopen("./test.dat","w"); for (int i=0; i<SIZE; i++) { fprintf(file,"a"); } fclose(file); endtime(SIZE); } void test_flush() { starttime(); FILE* file = fopen("./test.dat","w"); for (int i=0; i<SIZE; i++) { fprintf(file,"a"); fflush(file); } fclose(file); endtime(SIZE); } int main() { test_write(); test_fprintf(); test_flush(); }
Compiling and running I get 0.2MB/s for write() and 6MB/s for fprintf(). A large difference. There's three tests in this example, the third test uses fprintf() and fflush(). This is equivalent to write() both in performance and in functionality. Which leads to the suggestion that fprintf() (and other buffering I/O functions) are the fastest way of writing to files, and that fflush() should be used to enforce synchronisation of the file contents.
There's an interview with Rick Hetherington about the new T5 processor. Well worth a quick read.
Vijay Tatkar will be talking about developing on Solaris next week Tuesday at 9am PST..
I
My co-conspirator Rick Weisner has written up a nice summary of malloc performance, including evaluating the mtmalloc changes that we got into S10 U10.. find the timeline view in the Performance Analyzer incredibly useful, but I've often been puzzled by what causes the gaps - like those in the example below:
One of my colleagues pointed out that it is possible to figure out what is causing the gaps. The call stack is indicated by the event after the gap. This makes sense. The Performance Analyzer works by sending a profiling signal to the thread multiple times a second. If the thread is not scheduled on the CPU then it doesn't get a signal. The first thing that the thread does when it is put back onto the CPU is to respond to those signals that it missed. Here's some example code so that you can try it out.
#include <stdio.h> void write_file() { char block[8192]; FILE * file = fopen("./text.txt", "w"); for (int i=0;i<1024; i++) { fwrite(block, sizeof(block), 1, file); } fclose(file); } void read_file() { char block[8192]; FILE * file = fopen("./text.txt", "rw"); for (int i=0;i<1024; i++) { fread(block,sizeof(block),1,file); fseek(file,-sizeof(block),SEEK_CUR); fwrite(block, sizeof(block), 1, file); } fclose(file); } int main() { for (int i=0; i<100; i++) { write_file(); read_file(); } }
This is the code that generated the timeline shown above, so you know that the profile will have some gaps in it. If we select the event after the gap we determine that the gaps are caused by the application either opening or closing the file.
But that is not all that is going on, if we look at the information shown in the Timeline details panel for the Duration of the event we can see that it spent 210ms in the "Other Wait" micro state. So we've now got a pretty clear idea of where the time is coming from.:
Adding and removing filters is now just a matter of right clicking. This allows you to rapidly drill down on the profile data. For example filtering out activity by processor, call stack, and so on..
SPARC.
Steve Clamage has provided a nice summary of the trade-offs between the various STL options. I'll summarise it here:
I'd also add that stlport4 and stdcxx4 typically have much better performance than the default library.
The other point that bears repetition is that you can only include one STL per application. So you cannot use different implementations for different libraries or for the application.
Socialising Solaris Studio
By Darryl Gove] | https://blogs.oracle.com/d/tags/solaris | CC-MAIN-2014-15 | refinedweb | 977 | 65.93 |
Interactive Applications with React & D3
If you’re thinking of doing data visualization in React, take a look at Semiotic, a data visualization framework I developed for React.
Bringing together D3.js and React is one of those things that isn’t new but is still not well-established enough to point to one sure way to do it. In this excerpt from my book D3.js in Action, Second Edition, I’ll show you the main techniques for combining React and D3 and explain their strengths and weaknesses. The code for this example can be found in the React chapter code on D3.js in Action’s repo.
We start with a design for our dashboard. Designs can be rough sketches or detailed sets of user requirements. Let’s imagine you work for the leading European online seller of table mats, MatFlicks, and you’re in charge of creating a dashboard showing their rollout to North America and South America. The genius CEO of MatFlicks, Matt Flick, decided the rollout strategy would be alphabetical, so Argentina gets access on Day 0 and every day one more country gets access to the amazing MatFlicks inventory. They need to see how the rollout is progressing geographically, over time and in total per country. The figure below shows a simple sketch to achieve this using several of the charts I explore throughout D3.js in Action. We’re going to randomly generate MatFlicks data, with each country only generating random data in billions of dollars of revenue per day after its rollout.
With a data dashboard like this, we want to provide a user with multiple perspectives into the data as well as the ability to drill down into the data and see individual datapoints. We’ll use a line chart to see the change over time, a bar chart for raw total changes, and a map so that users can see the geographic distribution of our data. We also want to let users slice and dice their data — functionality that is readily achieved using a brush.
From the sketch, you can easily imagine interaction possibilities and changes that you may want to see based on user activity; for instance, highlighting which elements in each chart correspond to elements in other charts, or giving more detail on a particular element based on a click. That kind of dynamic filtering and interactivity is explored in the full chapter. The CSS for the dashboard isn’t much for this example, just the fill and stroke for the map we’ll make. As with most data visualization, much of the styling will be inline.
Dashboard CSS
path.countries {
stroke-width: 1;
stroke: #75739F;
fill: #5EAFC6;
}
Getting started with React
React is a view lifecycle management system that’s part of a very popular application framework and development pattern. React is the view layer, and lets you define HTML components with custom behavior, which is super useful for composing applications. It uses a JavaScript + HTML language called JSX that disgusted me when I first saw it, but now I love it. I didn’t like it because I always felt like JavaScript and HTML should live in totally separate worlds, but I found out later that writing HTML inside JavaScript could be incredibly useful when you’re manipulating the DOM like we have been with vanilla D3 throughout this book.
Typically when you see examples of React, they pair it with a kind of state management system like Flux or Redux. We won’t be doing that in this chapter. This is a single chapter, and you can find entire books about React.
You’re going to need node and node package manager (npm) installed on your system as well as a slight amount of comfort with the command line. There are great books on React, such as React Quickly, so this will only scratch the surface, but just this chapter will get you to the point of a fully self-contained React data visualization application.
Why React, why not X?
React is obviously the best library ever made and if you like Angular, you’re dumb, bro (and don’t even get me started on Ember). No, not really. That’s horrible, and it’s too bad that people get so invested in the righteousness of their particular library.
Actually, I just wanted to show people how to deal with D3 in a modern MVC-like environment and I know React best. Even if you never use React, you’ll probably see patterns in this chapter that apply to other frameworks. And even if you hate application frameworks, you can use most of the code in this chapter in your own custom, hand-rolled, beautifully opaque bespoke dashboard.
Fundamentally, React consists of a component creation framework that lets you build self-contained elements (like
div or
svg:rect) that have custom rendering methods, properties, state, and lifecycle methods.
Render
One of the major features of React is that it keeps track of a copy of the DOM, known as the Virtual DOM, which it can use to only render elements that need to change based on receiving new data saving cycles and speeding up your web applications. This was React’s big selling point when it first dropped, but it’s become popular with other view rendering systems. The
render() function in each React component returns the elements that will be created by React (typically described using JSX, which is introduced in this chapter).
Props
Attributes of a component are sent to it when it’s created and are known as props. These props of a React component are typically available in the component functions via the this context as
this.props. In certain cases, such as stateless components or constructors, you won’t use this to access them, but we won’t do that in this chapter so you’ll need a book dedicated to React to get to know the other patterns. This structure lets you send data down from parent components to child components and you can use that data to modify how the component is rendered. You’ll see this in detail when we get into the code.
State
While props are sent down to a component, the state of a component is stored and modified internally within the component. Like this.props, there’s a corresponding this.state that will give you the current state. When you modify state (using
this.setState in a component) it will automatically trigger a re-render unless you’ve modified
shouldComponentUpdate (a lifecycle method dealt with in the next section).
Lifecycle methods
React components expose lifecycle methods that fire as the component is created and updated and receives its props. They are incredibly useful and even necessary in certain use cases, as we’ll see later. You have, for instance,
shouldComponentUpdate, which lets you specify the logic for whether or not the component re-renders when it receives new props or state. There’s also
willComponentUpdate and
didComponentUpdate to add functionality to your component before or after it updates, along with similar methods for when the component first mounts or exits (and a few more). I’ll get into these methods as they apply to our data visualization needs but I won’t touch on all of them.
react-create-app: setting up your application
One of the challenges of modern development is getting your environment set up. Fortunately, there’s a command line tool that gets you started and it’s supported by the React team: create-react-app
In OSX you can open your terminal window and run the following commands:
npm install -g create-react-appcreate-react-app d3iacd d3ia/npm start
Setting up your React app is that easy. If you navigate to localhost:3000 you’ll see the boilerplate create-react-app page below. If you have any issues or need instructions for Windows, see.
Along with starting your node server running the code, this will create all the structure you need to build and deploy a React application that we’re going to use it to build our dashboard. That structure contains a
package.json file that references all the modules included in your project and to which we need to add a couple more modules to make our dashboard. We add modules using NPM and while we could include the entire D3 library and keep coding like we have, you’re better off installing the individual modules and understanding how importing those modules works. In your project directory run the following to install the d3-scale module:
npm i –SE d3-scale
This command (
npm i is short for
npm install) installs the latest version of
d3-scale (which gives us access to all those wonderful scales we’ve been using in the last eight chapters) and the
–SE tag saves the exact version to your
package.json so that when you want to deploy this application elsewhere
d3-scale is installed. Along with d3-scale, do the same thing with the following modules:
d3-shape
d3-svg-legend
d3-array
d3-geo
d3-selection
d3-transition
d3-brush
d3-axis
By installing modules individually like this, you reduces the amount of code you’ll deploy with your application, decreasing load time and improving maintainability.
JSX
JSX refers to JavaScript + XML, an integrated JavaScript and HTML coding language that lets you write HTML inline with your JavaScript code. It requires that the code be transpiled to plain JavaScript — your browser can’t natively run JSX — but as long as you have your transpiling set up (which react-create-app already does for us) you can write code like this:
const data = [ 'one', 'two', 'three' ]const divs = data.map((d,i) => <div key={i}>{d}</div>)const wrap = <div style={{ marginLeft: '20px' }}{divs}</div>
And you can create an array of three div elements, each of which will have the corresponding string from your array as content. Notice a few things going on here. One, when we start writing in HTML we have to use curly braces (bolded for emphasis above) to get out of it if we want to put js there. If I hadn’t put curly braces around the
d, for instance, then all my divs would have had the letter “d” as their content. Another is that style is an object passed to an element and that object needs CSS keys that usually are snake case (like
margin-left) turned into camelcase (
marginLeft). When we’re making an array of elements, each needs a “key” property that gives it a unique key (like the optional key when we’re using
.data() with D3). Finally, when you want to set an element’s CSS class, you need to use
className, because
class is reserved.
There’s more to JSX but that should be enough to let you make sense of the code you’re going to see. When I first saw JSX, I was convinced it was a horrible idea and planned to only use the pure JavaScript rendering functions that React has (you don’t need to use JSX to use React), but after a couple weeks, I fell in love with it. The ability to create elements on the fly from data really appealed to me because of my experience with D3.
Traditional D3 rendering with React
The challenge of integrating D3 with React is that React and D3 both want to control the DOM. The entire select/enter/exit/update pattern with D3 is in direct conflict with React and its virtual DOM. If you’re coming to React from D3, giving up your grip on the DOM is one of those “cold, dead hands” moments. The way most people use D3 with React is to use React to build the structure of the application, and to render traditional HTML elements, and then when it comes to the data visualization section, they pass a DOM container (typically an
<svg>) over to D3 and use D3 to create and destroy and update elements. In a way, it’s similar to the way we used to use Java applets or Flash to run a black box in your page while the rest of your page is rendered separately. The benefit of this method of integrating React and D3 is that you can use all the same kind of code you see in all the core D3 examples. The main difficulty is that you need to create functions in various React lifecycle events to make sure your viz updates.
The listing below shows a simple bar chart component built using this method. Create this component in your
src/ directory and save it as
BarChart.js. In React, component filenames and function names are typically differentiated from other code files and functions by using camelcase and capitalizing the first letter like this.
BarChart.js
import React, { Component } from 'react'
import './App.css'
import { scaleLinear } from 'd3-scale’
import { max } from 'd3-array'
import { select } from 'd3-selection'class BarChart extends Component {
constructor(props){
super(props)
this.createBarChart = this.createBarChart.bind(this)
} componentDidMount() {
this.createBarChart()
} componentDidUpdate() {
this.createBarChart()
} createBarChart() {
const node = this.node
const dataMax = max(this.props.data)
const yScale = scaleLinear()
.domain([0, dataMax])
.range([0, this.props.size[1]]) select(node)
.selectAll('rect')
.data(this.props.data)
.enter()
.append('rect')
select(node)
.selectAll('rect')
.data(this.props.data)
.exit()
.remove()
select(node)
.selectAll('rect')
.data(this.props.data)
.style('fill', '#fe9922')
.attr('x', (d,i) => i * 25)
.attr('y', d => this.props.size[1] — yScale(d))
.attr('height', d => yScale(d))
.attr('width', 25)
}render() {
return <svg ref={node => this.node = node}
width={500} height={500}>
</svg>
}
}
export default BarChart
A few explanations about what’s going on in the code here:
- Because we’re importing D3 functions from modules, they don’t have the
d3.prefix, instead they’re the imported function like
scaleLinear.
- In the constructor, you need to bind the component as the context to any new internal functions if you want access to
this.propsor
this.statein that function (this doesn’t need to be done for any existing lifecycle functions) .
- By executing this.createBarChart in
componentDidMountand
componentDidUpdate, whenever the component first mounts or receives new props/state fire the bar chart function.
this.nodeis set in the
refproperty of the
svgelement and acts as a reference to the actual DOM node generated by React, so you can hand that DOM node over to your D3 functionality.
sizeand
dataare passed down as props to the component, so you access them with
this.props.sizeand
this.props.datato your D3 code.
- Render is just returning an SVG element waiting for your D3 code. Below we’ll see how to use React to generate the entire chart.
Making these changes and saving them won’t show any immediate effect because you’re not importing and rendering this component in
App.js, which is the component initially rendered by your app. Change
App.js to match the following listing.
Referencing BarChart.js in App.jsimport React, { Component } from 'react'
import './App.css'
import BarChart from './BarChart'class App extends Component {
render() {
return (
<div className='App'>
<div className='App-header'>
<h2>d3ia dashboard</h2>
</div>
<div>
<BarChart data={[5,10,1,3]} size={[500,500]} />
</div>
</div>
)
}
}export default App
The changes here are that we’re importing our newly created component (
BarChart.js) and we’re passing down some data and size to that component (that’s how we’re accessing it on props.data and props.size in
createBarChart).
When you save
App.js with these changes, you’ll see something pretty cool if you have your server running: it automatically updates the page to show you what’s in the figure below. That’s Webpack — the module bundler included in create-react-app — automatically updating your app based on changes in your code.
You can already imagine improvements like scaling the bars to fit the width, which we’ll see later. But for now let’s move on to the other method of rendering data visualization using D3 and React.. There are challenges with this approach in creating animated transitions and draggable elements but otherwise it’s preferable because it will create code that will be more maintainable by your less D3-inclined colleagues.
The code below shows how we can do this to recreate one of the maps made in the geospatial data visualization chapter of D3.js in Action. In this example we import geographic data (in this case
world.js) instead of loading geodata like traditional examples show. That’s done by transforming the geojson .js file by adding a little ES2015
export syntax to the beginning of the JSON object (you can see the code on the github repo). The code in the next listing is similar to what we’ve seen before, except now we’re using it to create JSX elements to represent each country and we’re including the geodata rather than using an XHR request.
WorldMap.js
import React, { Component } from 'react'
import './App.css'
import worlddata from './world'
import { geoMercator, geoPath } from 'd3-geo'
class WorldMap extends Component {
render() {
const projection = geoMercator()
const pathGenerator = geoPath().projection(projection)
const countries = worlddata.features
.map((d,i) => <path
key={'path' + i}
d={pathGenerator(d)})
return <svg width={500} height={500}>
{countries}
</svg>
}
}
export default WorldMap
Rather than fiddling with async calls (using
d3.json for instance) we can just import the map data since it won’t be changing. I think it’s better to transform any static assets to .js and import them rather than use XHR requests. We use native
Array.map to map the arrays to
svg:path elements and populate the
d attribute of each of those
path elements using D3’s geo functionality. That array of paths is just dropped into some curly brackets inside the svg and that’s all there is to creating a choropleth map in React with D3. It’s almost exactly the same as the data-binding pattern we see in D3, except that we use native
Array.map to map the individual data elements to DOM elements because of the magic of JSX.
In my own practice I prefer to use this method, because I find the lifecycle events in React as well as the way it creates and updates and destroys elements to be more comprehensive than dealing with it via D3. And as React and other frameworks like it mature, the issues with developing interactivity and animation become less and less difficult.
In chapter 9 of D3.js in Action this example continues with the addition of a streamgraph, brush, responsive sizing and more. But this shows you the two main ways to approach integrating D3 and React. | https://medium.com/@Elijah_Meeks/interactive-applications-with-react-d3-f76f7b3ebc71 | CC-MAIN-2020-34 | refinedweb | 3,145 | 60.95 |
On 08/13/2012 10:19 AM, Eric Blake wrote: >. Found the root of the issue - it's libvirt's fault. Gnulib's maint.mk takes the initial definition of local-checks-to-skip, and from that, creates a macro 'local-checks' using a := rule: local-check := \ $(patsubst sc_%, sc_%.z, \ $(filter-out $(local-checks-to-skip), $(local-checks-available))) But libvirt's cfg.mk is conditionally running the local-checks-to-skip rule, via: # Most developers don't run 'make distcheck'. We want the official # dist to be secure, but don't want to penalize other developers # using a distro that has not yet picked up the automake fix. # FIXME remove this ifeq (making the syntax check unconditional) # once fixed automake (1.11.6 or 1.12.2+) is more common. ifeq ($(filter dist%, $(MAKECMDGOALS)), ) local-checks-to-skip += sc_vulnerable_makefile_CVE-2012-3386 else distdir: sc_vulnerable_makefile_CVE-2012-3386 endif Because distdir depends on the full sc_ name, rather than the sc_.z rewrite, maint.mk's timing rules don't get properly run, so the .sc-start-* file doesn't get cleaned up. I think with a bit more tweaking to libvirt's cfg.mk, I can get this working again. Meanwhile, would gnulib like to incorporate this hack from libvirt? After all, the current Automake vulnerability only affects you if you run 'make dist' or 'make distcheck'; it does not impact normal day-to-day development. Therefore, running the syntax check only in the vulnerable cases, and in such a way that the syntax check stops make before the vulnerability can actually be triggered, without penalizing day-to-day development for people relying on their distro rather than using a hand-built automake, seems like it would be nice to share among multiple packages. [It's a shame that more than a month after the CVE was reported and both Fedora 17 and RHEL 6.3 are still vulnerable, but that's a story for another day.] -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library
Attachment:
signature.asc
Description: OpenPGP digital signature | https://www.redhat.com/archives/libvir-list/2012-August/msg01137.html | CC-MAIN-2015-11 | refinedweb | 347 | 58.08 |
You already cite the correct wiki page about the purpose of
std_msgs.
For integer/float values, there are the
MultiArray messages, which could suite your needs for numbers. For strings, you either have to create a new custom message, or wriggle your way through something like adding a seperator between all users concatenated into a single string...
In short: There is no way to create a message type to be sent over ROS or written to the bag file without properly creating a
.msg file. This is required for creation of the language specific representations, such that you can
#include or
import them. | https://answers.ros.org/answers/314720/revisions/ | CC-MAIN-2022-21 | refinedweb | 103 | 59.23 |
Amazon Web Services (AWS)
Page Contents
Course Notes
These are notes from the Udemy course AWS Certified Developer - Associate 2020. It's a great course, give it a go!
Aws Samples ^^ This GitHub page has a load of AWS examples. Really worth a flick through! E.g. For deploying PHP, Containers and NGinx:
Iam - Identity Access Management
- See - For management of users and their access level to AWS console. - Centralised control of AWS account - Shared access - Granular permissions - Multifactor authentication - Integrates with AWS services - Groups - Collection of users with common permission set. - Roles - Define set of permissions that can be assigned to AWS resources/entities. Secure way to grant permissions to entities that you trust. Ex, IAM user in another account or application code running an an EC2 instnace that needs to permorm actions on AWS resources etc. E.g.: Give an EC2 instance permissions to write a file to an S3 bucket. Create role. Select the service that the role will use - EC2 instance in this example. Attach the S3 policy of choice, e.g. write access, to the role. This role can then be applied to any new EC2 instance created. - Policies - Document that defines >= 1 permissions that can be assigned user, groups, or roles. For example, a policy could define the read permisison on a dynamoDB table and then read/write on a specific S3 bucket and so on. Its a collection of permissions of varying specificity. USERS GROUP POLICY James --------> Supper Group ----> Eat policy John -------/ `---> Drink policy Paul ------/ - In console access under "Security, Identity and Compliance" - When creating users you will have - User name For AWS console login. - Access key ID For PROGRAMATIC access. i.e., via CLI, scripts etc. - Secret Access Key. For PROGRAMATIC access. i.e., via CLI, scripts etc. This will only be displayed once. You can download as a CSV if you can keep it securley. Note, once the secret has been hidden you canNOT access it again. You would have to generate a new key. - Password For AWS console login. Instance Profiles ----------------- EC2 --- See An instance profile is a container for an IAM role that you can use to pass role information to an EC2 instance when the instance starts ... When you then use the Amazon EC2 console to launch an instance with an IAM role, you can select a role to associate with the instance. Elastic Beanstalk ----------------- See Cognito -------- USER POOLS: user directories that provide sign-up and sign-in options for your ... app users ... app users can sign in either directly through a user pool, or federate through a third-party identity provider (IdP) ... After a successful authentication, your ... app will receive user pool tokens from Amazon Cognito ... IDENTITY POOLS: provide AWS credentials to grant your users access to other AWS services. Web Identity Federation ----------------------- Lets you give your users access to AWS resources after they have successfuly authenticated with a web-based identity provider like Amazon, FB or Google. After authentication, user gets auth code from Web ID provider, which they trade for temporary AWS security credentials. Cognity provides Web Identity Federation with following fetures: - Sign up and sign in - Access for guests - ID broker between app and Web ID providers so no need to write additional code - Sync user data for multiple devices Acts as broker handling all interactions with Web ID providers. E.g. user can login to FB, get an authcode which it exchanges with AWS for a temporary access credential (which maps to an IAM rolw allowing specific access rights), which it can then use to access an S3 bucket, for example, or parts of a database or event a website behind an ALB acting as a reverse authentication proxy. Cognito User Pools ------------------ - User pools are USER DIRECTORIES used to MANAGE SIGN-UP/IN in functionality for web apps. - Can sign-in directly to pool or via Web ID provider (FB, Google, Amazon etc). Successfull auth generates a number of JSON Web Tokens (JWTs) - Enable creation of unique IDs for users and ability to authenticate users with ID pools. - APP CLIENT - Is what we use to call the various APIs on our behalf. E.g. API to reg a new user or sign in an existing etc. See In app client settings: Need to configure an identity provider. Click "Cognito User Pool" Then configure callback URLs - The URL the user is redirected to after they have successfull signed in or signed up. The logout URL will invlidate the access tokens supplied after a successful login.
Going Serverless
Lambdas ------- See EC2 launced in 2006. At time of writing it is 14 years old! Infrastructure as a service! Serverless means you don't need to control the server, you don't need to provision the hardware or worry about the OS its running - its no longer something you need to worry about. Also don't have to worry about scaling and response to load and keeping them running etc. Lambda allows you to use your code without any need to provision servers, install software, deploy containers or worry about any low level details and can parallelize code. All this is taken care of for you. E.g. Alexa is using Lambdas every time you make an Alexa query. So, don't need any EC2 instances, and EBS instances etc etc - THERE IS NOTHING TO MANAGE! Use: - Event driven compute service - AWS Lambda runs code in response to events, e.g. changes to data in S2 bucket or DynamoDB table. - Compute service - run code in response to HTTP requests using Amazon API gateway or API calls made using AWS SDKs. This can be massively parallel - many requests launch many Lambdas, which all use the same code but represent difference request instances with associated data etc. Each AWS Lambda function runs in its own isolated environment, with its own resources and file system view. AWS Lambda uses the same techniques as Amazon EC2 to provide security and separation at the infrastructure and execution levels. AWS Lambda natively supports Java, Go, PowerShell, Node.js, C#, Python, and Ruby code, and provides a Runtime API which allows you to use any additional programming languages to author your functions. Priced on #requires and duration. Configure A Lambda Function --------------------------- - Click - Services > Compute > Lambda > Create Lambda Function. - Create from scratch - Add name and platform. If you've not used Lambda before will need to create a new role to give Lambda permission to execute. Use policy "Simple Microservice Permissions". - Click "Create function" . - Paste in your Lambda code. - Add your trigger... can be sooo many things: including but no where near limited to API Gateway, CloudFront, S3, DynamoDB, and more... - - TODO COMPLETE ME! API Gateway ----------- Use API Gateway to create RESTful APIs endpoints. These are services your web app etc need from a backend server. For example, a login management endpoint. This could be implemented using your own server, or a server running on an EC2 instance. But why bother managing your own service?! Lets AWS do that fo you and instead just give you some end point URLs and things that can happen based on someone accessing them! So, API Gateway gives you an end point URL to use. You get to say what happends when the end point is accessed: use another AWS service or run a Lambda. See: Watch out for costs!! Free tier (as seen on 03-Oct-2020): The Amazon API Gateway free tier includes one million API calls received for REST APIs, one million API calls received for HTTP APIs, and one million messages and 750,000 connection minutes for WebSocket APIs per month for up to 12 months. Amazon API Gateway - fully managed service - publish APIs at any scale to act as "front door" for apps to access data etc from back-end services, such as apps on EC2 instances, code on Lambdas etc. - Expose HTTPS enpoints to define a RESTful API API gateway gives us a HTTPS address to make API calls to, and then configure how the API responds to those calls - e.g. get data from a DynamoDB or fire off a Lambda etc etc to return the response. - Lets you serveless-ly connect to services like Lambda & DynamoDB. - Can send each API endpoint to a different target. - Run efficiently with low cost & scales effortlessley. - Can track and control usage with API key. - Can throttle requests to prevent attacks. - Can maintain multiple versions of your API How to configure? - Define an API (container) - Define Resources and nested Resources (URL paths) - For each resource: - Select supported HTTP methods, POST, GET etc etc - Set security - Choose target- EC2 Lambda etc - Set resquest & response transformations - Deploy API to a Stage - Use APU Gateway domain by default but you can use your own to hide the fact its AWS - !!!Supports AWS Certificate Manager: free SSL/TLS certs!!! WOO!!! API Caching In API Gateway: can enable API caching. Caches enpoint's response to reduce # calls to endpoint for repeated requests. Also improves latency. Need to be aware of XSS and CORS Example: - - - - Choose the REST API type.
Now you can define the resources you are doing to use and the HTTP methods we want to react to. Create a resource, which is like a URL SEGMENT, like so:
You can select to enable Cross-Origin Resource Sharing (CORS). CORS is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. See: #
Now we have created a URL segment, which is a resource. It can't be used, however, until the requests that it should handle are defined. To do this, select the end point resource and then from the actions menu select "Create Method". Then you can define which HTTP method you want the resource to respond to (ANY, DELETE, PUT, PUSH, GET etc etc). E.g if a GET method was created: #
A mock will allow you to create a dummy response. If you create a mock you can use the integration response to return dummy data.
Add some dummy response data like this:
Next goto ACTIONS > DEPLOY API. It will then ask you to deply your API. You can deploy to an existing or new stage. Stages allow management of different versions of the API, e.g. dev v.s. production versions. Simple Serverless Website Using Route53, API Gateway, Lambda and S3 ------------------------------------------------------------------- Domain name in Route53 and bucket name need to be the same. They MUST BE THE SAME (toplevel exluding the .com). Must enable static website hosting for bucket. If you don't want to spend money on AWS domain you can just use the S3 bucket address, Steps: 1. In the Bucket name list, choose the bucket that you want to use for your static website. 1.1. Choose Properties. 1.2. Choose Static website hosting. 1.3. Choose "Use this bucket to host a website". 1.4. Note down the end point. E.g. my last endpint was Endpoint : 2. Edit block public access settings 2.1 Choose the Permissions tab, and edit, 2.2 Clear Block all public access, and choose Save -- anyone on the internet can access your bucket!! 3. Add Bucket Policy: To make the objects in your bucket publicly readable, you must write a bucket policy that grants everyone s3:GetObject permission. 3.1 Choose "Bucket Policy" under "Permissions" tab for your S3 bucket, 3.2 Add the following: { "Version": "2012-10-17", "Statement": [ { "Sid": "PublicReadGetObject", "Effect": "Allow", "Principal": "*", "Action": [ "s3:GetObject" ], "Resource": [ "arn:aws:s3:::example.com/*" << PUT YOUR S3 BUCKET ARN HERE ] } ] } 4. (Optional) Add Route53 entry for your domain to point to S3 endpoint.
Forward And Reverse Proxies
Ref: Forward Proxy ------------- TL;DR: A forward proxy sits in front of a client/clients and ensures that no origin server ever communicates directly with that specific client / those clients. Standard Internet communication: A reaches out directly to computer C, with the client sending requests to the origin server and the origin server responding to the client. With fwd proxy: A sends requests to B (proxy), which forwards the request to C (origin server). C will then send a response to B, which will forward the response back to A. Why? - Avoid state or instituational browsing restrictions Connect to proxy rather than desired illegal site. - Block access to certain content Proxy intercepts all traffic so can deny some requests. - Protect online identity Servers see the proxy's IP, not the clients. Reverse Proxy ------------- TL;DR: Sits in front of web server(s), intercepting client requests. A reverse proxy sits in front of an origin server and ensures that no client ever communicates directly with that origin server. With rev proxy: A sends comms to reverse proxy, B. B then sends request to server C, which replies to B, which B forwards back on to A. Why? - Load balancing. Proxy can forward client requests on to one server from a pool. To client it looks like talking to one server, when it could be one of many. - Security. Server IP is never revelated. Harder to attack it therefore. Reverse proxy generally has higher security and better resource to fend off attack. - Caching. Reverse proxy can cache frequenty requested content. - TLS/SSL encryption. If origin server is low resouce or doesn't support encryption reverse-proxy can do this on the server's behalg.
Elastic Compute Cloud (Ec2)
Stands for Elastic Compute Cloud, abreviated to EC2. Web service providing resizeable compute capacity in the cloud. Virtual machines in a cloud. Pay only for capacity you use - don't have to (over) provision your own kit. Isolate from common failure scenarious. EC2 Options ----------- - On demand - fixed rate per hour/second with no commitment, no upfront payment. Good for app dev or apps with short term, spiky, unpredictable workloads that cannot be interrupted. - Reserved - capacity reservation - pay up front. Good discounts on hourly charge for an instance. One to three year term. Apps with steady state or predictable usage. - Spot - Allows bidding Apps that have very flexible start and end times For apps that are only feasible at very low compute prices. E.g. use compute during off-peak times for cheaper compute cost. - Dedicated hosts - Physical EC2 server for your use only. Regulatory requirements that do not alow multi-tenant virtulization Licensing which does not support multi-tenancy. EC2 Instance Types ------------------- There are different "families" of instance types that provide optimisations for specific requirements like hight speed storage, or memory space, or compute power etc. Families include. FPGA, High Speed Storage, Graphics Intesive, High Disk Througput, Low Cost, Dense Storage, Memory Optimized, General Purpose, Compute optimize, GPU etc. You will mostly use - T2 = Lowest cost, general purpose - Web Servers and Small DBs Elastic Block Store (EBS) ------------------------- EBS allows you to create storage volumes and attach them to Amazon EC2 instances. Once attched, can create FS on top of these volumes, run DBs etc etc. Protect you from failure of single component. Types: General Purpose SSD (GP2), Provisioned OPS SSD(IO1), Throughput Optimized HDD (ST1) Cold HDD (SC1). Elastic Load Balancer (ELB) --------------------------- See Types Of Load Balancers - Application Load Balancer. OSI Layer 7. Can make very clever decisions based on application level logic. Application Load Blancers are best suited for load balancing of HTTP and HTTPS traffic. They operate at Lyer 7 and are application-aware. They are intelligent, and you can create advanced request routing, sending specified requests to specific web servers. For setup see: For authentication see: - Network Load Balancer. Most expensive option. Works at OSI layer 4 (surely 3?!). Fast performance! Best suited for load balancing of TCP traffic where extreme performance is required. Operating at the connection level (Layer 4 - which I think is the transport layer not the network layer, need to double check that), network Load Balancers are capable of halding millioos of requests per secon, while maintaining ultra-low latencies. use for EXTREME PERFORANCE. - Classic Load Balancer (ELB) No longer recommended. Lagacy! Legacy Elastic Load Blanacers. Can ballance layer 7 or 4, but layer 7 is not as intelligent as application load balancer. If your app stops responding ELB returns a 504 error. The load balancer is an extra layer that will "hide" the public IP address of the entity accessing your server. To get the public IP look in the "X-Forwarded-For" header to see the public IP addr. To create a load balancer go back to your EC2 instance and select, in the left hand menu pane, LOAD BALANCING > Load Balancers. Then click the "Create Load Balancer Button". Create the HTTP(S) balancer. Assign a security group. Configure Routing. Create new target group on HTTP port 80. Add /index.html as the health check item. Register targets Review Create Can config ELB to terminate HTTPS connections and deliver messages to backend of HTTP. ELB will handle encrypt/decrypt. - See - Upload certificate to AWS account using the AWS Management Console or the `iam-servercertupload` command, then retrieve the ID of the uploaded certificate. - Create new load balancer which includes an HTTPS listener, and supply the certificate ID from prev step. ELBs can also act as AUTHENTICATING REVERSE PROXIES! See ALB can now securely authenticate users as they access applications, letting developers eliminate the code they have to write to support authentication and offload the responsibility of authentication from the backend MUST USE AN APPLICATION LOAD BALANCER. At time of writing when creating a load balancer classic seems to be the default option. To setup an ALB see: Happy, happy days :D DNS Refresher ------------- See: Fully Qualified Domain Name (FQDN) - Domain name has both a HOSTNAME AND DOMAINNAME For example, accessing a server called bob we might goto "bob.my-buiness-name.com". Bob is the hostname and my-buiness-name.com is the domain name. DNS request: 1. Contact ROOT NAME SERVERS (see) and get the address of the top level domain (TLD) server. So in the bob example we get the COM TLD server address. 2. Next contact the COM TLD server(s) to get the name server responsible for "my-buiness-name". 3. Next conatact the name server for the address of the hose "bob". Two types of DNS servers: 1. Authoritative Do the actual name -> IP address mapping. 2. Recursive (or Caching): Contacted by clients and do the work of the DNS lookup by talking to authoritative servers. They recurse throught the DNS name hierachy to resolve the address for the client. DOMAIN REGISTRAR - service through which you register a domain name and map an IP address to it. Domain registrar deals with registry operators who deal with master domain lists - overall managed by IANA. So, if I register "bob.my-buiness-name.com" the registrar will contact a registry operator, which is overseen by IANA, and adds the name "bob.my-buiness-name.com" to the global list of all domain names (ensuring, of course, that it isn't already registered!). That's all the registrar does. DNS HOSTING PROVIDER - hosts the servers that authoritatively respond to your domain. So, a registrar might have registered "bob.my-buiness-name.com" for me, but it is the DNS hosting provider that has a server that when queried will respond with the IP address for my host! Sometimes a domain registrar will offer DNS hosting and vice versa, but the 2 functions are separate Your DNS hosting provider has to know, when x.y.z is accessed, what the IP address it should map to is. For this is uses something called an "A record". If you own x.y.z, you create, in your hosting providers map of x.z.y an "A record" and fill it with your server's IP address. You can also setup aliases. If for x.y.z you setuup a "CNAME record", you can specificy that when x.y.z is resolved by your DHS hosting provider that it should re-direct the querier to another url instead.". For example, to map to zone-apex, example.com, the record might look like:. CNAME example.com. example.com. A 192.162.100.100. Route53 ------- - Amazon's DNS service - Allows mapping of domain names to EC2 instances, load balancers and S3 buckets. - Log into AWS console, then Services > Network > Route 53 - Click Domains > Registered domains Click "Register Domain". Select a domain and choose a name. Add it to your cart and click "Continue" - Fill in registrant information - Domain registration can take up to 3 days to complete. - Click Dashboard > "hosted zones" Should see our registers domains. Click "Goto record sets" to create our DNS records. Create "A" record. Says where you're domain is going to go. There are lots of record set type you can choose. An "A" record points to an IPv4 address, and "AAAA" record points to an IPv6 address etc. Create a type "A" record set. Use the NAKED DOMAIN NAME - that is the name without the "www." prefix. This is also sometimes refered to as the "zone apex record". In order to do this HAVE TO USE AN ALIAS. You create an alias for the zone apex. Aliases are only supported by DNS record types A and AAAA. Pick the alias target - it can be for an S3 website, an ELB website, Elastic Beanstalk, CloudFront etc. This is why we needed to setup the ELB... doesn't seem to support directly using an EC2 instance. Thus MUST CREATE ELB THEN PUT AN EC2 INSTANCE BEHIND THE ELB. Select your ELB from the target list and hit create :) From Wikipedia: A Canonical Name record (abbreviated as CNAME record) is a type of resource record in the Domain Name System (DNS) which maps one domain name (an alias) to another (the canonical name).[1] ... Also referred to as a CNAME record, a record in a DNS database that indicates the true, or canonical, host name of a computer that its aliases are associated with. ... When referring to IP addressing, canonical means the authoritative host name stored in a DNS database that all of an IP address' aliases resolve to. From AWS Certified Solutions Architect Practive Tests Book: A zone apex record is a DNA record at the root, or apex, of a DNS zone. So amazon.com is an apex record (sometimes called a naked domain record). From NS1.com: DNS servers create a DNS record to provide important information about a domain or hostname, particularly its current IP address. The most common DNS record types are: - Address mapping record (A Record) - a.k.a DNS host record, stores hostname and its corresponding IP. -). ... .... Setup Simple Webserver ----------------------- - From console goto Services > Compute > EC2 - Click on "Launch Service" button. - This will start us on the journey to launching first instance. instances are created from Amazon Machine Images (AMIs). - Select an AMI of your choice and then choose the type of this instance you want. Here you select the family type talked aboute in the section above, "EC2 Instance Types". I will want a T2 instance, probably one eleigable for the free teir. - Choose it, eg "T2 micro" and click the NEXT button to go and configure the instance details. - Then add tags. - Configure security groups. This is like a "virtual firewall" where you can specify what traffic you allow in and out of your instance. So for websever, for e.g. we need to enable port 80 for TCP. - Create a new security group most porbably and give it a name. - Allow SSH to remote adminthe EC2 instance. - Allow HTTP access, (and HTTPs access if you need it) - Click "Review and Launch" and review details. - Click "Launch" Need to either add or create a key pair that will allow you to access the instance. We store the private key somewhere locally and SECURELY The public key is stored by AWS NEVER SHARE THE PRIVATE KEY otherwise anyone can access the server! Name the key pair and then download it, saving it somewhere safe and secure. - Click "Launch Instance" Can take a little time for instance state to say "running". Once running it will give you your public IP address, which you can then use. Go to directory with your downloaded key pair Change permissons. needs to be quite locked down to use with EC2: chmod 400 MyNewKerPair.pem ssh ec2-user@<servier-ip-from-console> -i MyNewKeyPair.pem Inside ssh session sudo su yum update -y #Or use apt depending on server version used # install apache yum install httpd -y # start it service httpd start # make sure apache auto boots on restart chkconfig httpd on # See service status service httpd status # Create stub web page echo "<html><body>HELLO</body></html>" > /var/www/html/index.html How To Install LetsEncrypt SSL Certificate in AWS EC2 Instance Notes -------------------------------------------------------------------- Ref: See:, How to Setup SSL certificate in CentOS 7 using LetsEncrypt Notes ---------------------------------------------------------------- Ref: See:,
S3 (Simple Storage Service)
* Object based storage - secure, scalable, durable. Data spread across multiple device and facilities. * Files are stored in Buckets (like a folder) * Key/Value store (with Version ID optional & Metadata) * Universal namespace - names must be unique globally! From AWS website:. Amazon S3 does this by using a shared name prefix for objects (that is, objects have names that begin with a common string). Object names are also referred to as key names. * Data consistency model * PUTS of new objects - read after write consistency. A read after a write is immediately valid * Overwrite PUTs and DELETEs - eventual consistency - can take some time to propogate * Subresources - bucket specific config * Bucket polocies, acess control lists) * Cross Origin Resource Sharing (CORS) - files located in one bucket can be allowed to access files in other buckets * Transfer acceleration for multiple uploads * Guarantee 99.9% availability (i.e., service uptime), 99.999999999% durability! * Tiered storage available * Lifecycle management (automatic movement between tiers) * Versioning * Encryption * Max file size 5 TB!! Storage Tiers: * Regular - Stored across multiple devices and facilities. Can sustatin loss of 2 data centers! Guarantee 99.9% availability (i.e., service uptime), 99.999999999% durability! * IA (Infrequently Accessed) - Less frequent access but rapid. Charged per retrieval. * S3 One Zone IA - Less availablility than IA. Less cost. 20% less. * Reduced Redundancy Storage - Durability down to 99.99%. Use for data that can be re-created if lost. E.g. thumbnails. * Glacier - Very cheap but archival only. Takes 3-5 hours to restore from Glacier!! * Intelligent Tiering - Data has unknown or unpredictable access patterns Auto moves your data to most cost-effective tier. 2 tiers - frequency and infrequent access. If obj not accessed for 30 consecutive days it goes to infrequent tier. When accessed goes back to frequent tier. Same durability and reliability as regular. Charges * Storage per GB. * Requests. * Storage Management Pricing - e.g. for analytics. * Data Management Pricing - moving data OUT of S3. * Transfer Acceleration - extra charges for accelleration. S3 Security ----------- * Default - new buckets are PRIVATE * Can configure public access if required. * Use * Bucket policies - bucket level, JSON * Access Control lists - object level * Can create access logs, written to this/another bucket S3 Access Policies ------------------- From AWS S3 console, select bucket, select "Permissions" tab. Can control public accessibility using ACLs and enable/disable on a file by file basis. The "Bucket Policy" tab just exposes a policy editor. Below the text box is a link to the "Policy generator", which can help you build up your bucket policy. In the generator: * Select type of policy - "S3 Bucket Policy" * Select effect - "allow" or "deny" * Add "Principal" - this is the entity to which you are allowing/denying access to. I.e., who this policy applies to. Could be an IAM user, another S3 bucket or other AWS resource. If it is a user you must enter the uer's ARN, which you get from the Users section in IAM. * AWS service - "Amzon S3" * Actions - * ARN - Enter as displayed at the top of the editor text box. * Hit "Generate policy", and copy and paste the policy code into the editor. S3 Encryption ------------- 1. In transit - TLS/SSL 2. At rest - * S3 managed keys (SSE-S3) Each object encrypted using strong multi-factor encryption. Key also encrypted with master keys. AES-265 bit encryption. * AWS Key Management Service managed keys (SSE-KMS) Uses SSE key management service. Get separate permission for "envelope key", which is the key that encrypts your key. Also get AUDIT TRAIL. * Customer provided keys (SSE-C) AWS manage the encryption/decryption but YOU mange the keys, their rotation and lifetime etc 3. Client side User enecrypts file herself before upload Example syncing dir to encrypted folder: aws s3 sync . s3://your/dir --sse Install & Configure The CLI ---------------------------- apt install awscli aws configure set aws_access_key_id <AWS_ACCESS_KEY> [--profile <PROF_NAME>] aws configure set aws_secret_access_key <AWS_SECRET_KEY> [--profile <PROF_NAME>] aws configure set region "eu-west-1" --profile ci The access key and secret access key will have been created previously in the IAM settings. Then you can do things like: aws [--profile <PROF_NAME>] s3 ls s3://SOME/DIR/ ^ NOTE: Trailing "/" is important if you want to list the directory contents and not just the directory itself. aws [--profile <PROF_NAME>] s3 mv|cp LOCAL_FILE s3://SOME/DIR/ ^ NOTE: Trailing "/" is important! aws [--profile <PROF_NAME>] s3 mv|cp s3://SOME/DIR/FILE LOCAL_FILE
Elastic Beanstalk
MUST READ: TUTORIALS: What Is It? ----------- Elastic Beanstalk is a service for deploying and scaling web applications developing in many popular languages: Java, .NET, PHP, Node.js, Python, Ruby, Go and Docker onto widely used application server platforms like Apache Tomcat, Nginx, Passenger, and IIS. From AWS: having to learn about the infrastructure that runs those applications. Elastic Beanstalk reduces management complexity without restricting choice or control. You simply upload your application, and Elastic Beanstalk automatically handles the details of capacity provisioning, load balancing, scaling, and application health monitoring. []: On the surface, you will find a lot of similarities between Amazon Lightsail and AWS Elastic Beanstalk with EC2 instances. They both run exactly the same web application sets ... However, AWS Elastic Beanstalk can run within a VPC, which means you can run the web applications in an "internal only" configuration (with no connection to the Internet ...). You also get a whole host of flexibility in terms of settings that you don’t get with Lightsail. ... Best for: Your most challenging enterprise apps where access to the underlying OS is required. Developers can focus on writing code and don't need to worry about any of the underlying infrastructure needed to run the application. "Throw it some code in a ZIP file and it will figure it out and configure an environment for you". Upload the code and EB handles deployment, capacity provisioning, load balancing, auto-scaling and app health. You retain full control of the underlying AWS resource pwoering your app and you pay only for the AWS resource required to store and run you app, e.g. the EC2 instances or S3 buckets etc. In summary: - Fastest/simplest way to deply app in AWS. - Scales resources up and down for you including web application server platform. - EC2 instance type is selectable for opimization. - Managed platform updates auto applies to OS and Java/PHP/NodeJS etc etc. EB v.s. CloudFormation - EB configure environment through a GUI, CF is scripted config. NOTE: Free tier eligable instances will not have a load balancer
Nomenclature ------------ Application - Logical collection of Elastic Beanstalk components, including environments, versions, and environment configurations. Think of it like a CLASS definition. Environment - Collection of AWS resources running an application version. Each environment runs only 1 app version at a time, however, you can run the same app version or different application versions in many environments simultaneously. When environment created, EBS provisions resources needed to run the app. Think of it as an INSTANCE of a class. Environment - Identifies a collection of parameters and settings that define how an environment config and its associated resources behave Think of it like the PARAMETERS passed to the CLASS CONSTRUCTOR. Saved - A template that you can use as a starting point for creating unique environment config configurations. Platform - Combination of an operating system, programming language runtime, web server, application server, and Elastic Beanstalk components. Beanstalk Update/Deployment Options ----------------------------------- Beanstalk supports several options for processing deployments (deployment policies): - All at once: - Deploys the new version to all instance simultaneously - All of your instances are out of service while the deployment takes place. - You will experience an outage while the deployment is taking place. - If the update fails, you need to roll back the changes by re-deploying the original version to all you instances. - Rolling Deployment Policies: - Deploys in batches: each batch taken out of service whilst deployment takes places - Environment capacity will be reduced by the #instances in a batch while the deployment takes place. - If update fails, need to roll back the changes via rolling update. - Reduced capacity during deplayment but not an outage. - Rolling wwith Additional Batch deployment Updates. - Maintains full capacity during deployment process. - Launches an addition batch of instances before deploying new instances. - Immutable Deployment Updates. - Deploys new version to a fresh group of instances in new group. On success moved to the existing group, and old instances killed. - Perferred option for Mission Critical stuff. Instance Profiles - "Environment must have instance profile associated with it" ------------------------------------------------------------------------------- See: See: An instance profile is a container for an AWS Identity and Access Management (IAM) role that you can use to pass role information to an Amazon EC2 instance when the instance starts. When you launch an environment using the Elastic Beanstalk console or the EB CLI, Elastic Beanstalk creates a default instance profile, called `aws-elasticbeanstalk-ec2-role`, and assigns managed policies with default permissions to it. If you see the error message, "Environment must have instance profile associated with it", when trying to create an environment, you may not have sufficient priviladges or could be trying to create the environment in the wrong region. It appears you will required permission to use the role `aws-elasticbeanstalk-ec2-role`. How To Deploy Apps ------------------ NOTE: You must, generally, specify an Instance Profile for your EC2 instance From []: An instance profile is a container for an AWS Identity and Access Management (IAM) role that you can use to pass role information to an Amazon EC2 instance when the instance starts. Compute > Elastic Beanstalk Click "Get Started" Create a web app - Spec name and platform and the option "Upload your code" rather than "Sample application", which is the default - Click "Create application" - Select how to load the code - Can be a local file (ZIP) or an S3 bucket. - If you choose to upload a local file, it will create an S3 bucket automatically for you and stash the ZIP there. I was suprised that it doesn't unzip the archive, it just stashes it. - Once you click "Create Application" an environment will be created for your app. By creating an environment, AWS Elastic Beanstalk is allowed to manage AWS resources and permissions on your behalf. If the app was called HelloWorld then the environment is labeled HelloWorld-env. The creation can take up to 5 or 6 minutes so be patient. - When the environment reports itself as successfull launched, in the breadcrumb links select "Applications" to view a list of all applications. Here you should see your new environment, which you can click on to "drill into it". - From the application env you should be able to see recent events and a URL to the website that was created. - From the EBS environment page you can also select from the side menu "Configuration". This is how the environment can be configured. From here you can access security, instances, configure load balacncers, capacity etc and apply these configurations. Further Config/Update - Use the breadcrumbs to go back to the "all applications" page and select "application versions". It will show you the cuurent source and date it was deployed. - Can upload new version by clicking on the "Upload button". - If you are using an S3 bucket you can navigate to the S3 bucket management console and view the contents. Inside you will see all the code ZIPs you ever uploaded as well as a .elasticbeanstalk file and resources directory. - The new version becomes visible but HAS NOT BEEN DEPLOYED to an environment. - You can change your deployment policy to the ones described in the previous section. - Click DEPLOY to deploy you new version. Where is the app stored on the EB instance? It's in the /tmp/deployment/application folder during deployment and the moved to /var/app/current afterward. Configuring Elastic Beanstalk ----------------------------- Environment can be customized using config files - spec packages to install, user groups, shell cmds to run etc etc). Files written in YAML or JSON and have a ".config" suffix and be saved in the folder `.ebextensions`, which must be included in the top-level directory of the app source code bundle. Thus, config files can be placed under source control with the rest of the app code. See also: Examples of commonly used `.ebextensions`: AWS "Getting Started" Elastic Beanstalk Tutorial ------------------------------------------------ Ref: Configuring HTTPS & Certbot .ebextensions File ----------------------------------------------- Docker multi instance, by default does not have a load balancer. To install one follow this guide: In summary: Goto Envionments > your-ebs-envionment > Condig > Capacity (click Edit). Change environment type to "load balanced", and configure max #instances, Click "Apply" This Medium.com article works if you are running an Nginx server. In this case running Smashing in the apline container from github, is just running the "normal" thin server. This will use DNS VALIDATION - You must have control over your DNS entry so that you can add a temporary DNS record to, e.g. `_acme-challenge.your.site.address.com` so that the ACME protocol can verify that you do indeed have control over your domain. Getting Certificates From AWS Certificate Manager ------------------------------------------------- Deploying Docker Images / Web Apps to AWS Elastic Beanstalk ----------------------------------------------------------- MUST READ: Ref: Ref: Ref: TO ACCESS DOCKER VIA EB SSH SESSION: `sudo usermod -aG docker ${USER} && su -s ${USER}` Any web application that you deploy to Elastic Beanstalk in a single container Docker environment must include a Dockerfile or a Dockerrun.aws.json file. Docker images can be deployed to EBS. EBS will setup the EC2 instance for you and can be configured, via a Dockerrun.aws.json JSON file, to map volumes from the EC2 instance into the Docker container as well as mapping EC2 ports too. Thus the web-app can run in the Docker container. Docker multi instance, by default does not have a load balancer. To install one follow this guide: vvvvvvvv CAUTION CAUTION CAUTION CAUTION CAUTION CAUTION vvvvvvvv There is a difference between V1 and V2 of the Dockerrun.aws.json file/ V1 = Single container - "AWSEBDockerrunVersion": "1", V2 = Multi container - "AWSEBDockerrunVersion": "2", The examples below are a little confused... because I was confused whilst looking at them. Some are V1 and some are V2, and the two types are not compatible - i.e., you can't use a V1 Dockerrun file on a multicontainer (V2) instance and vice vera. SEE: SEE: The EC2 instances that EBS creates can have environments that only support a single Docker container per EC2 instance, or multiple containers. NOTE: STANDARD AND PRECONFIGURED DOCKER PLATFORMS ON EBS SUPPORT ONLY A SINGLE DOCKER CONTAINER PER ELASTIC BEANSTALK ENVIRONMENT. In order to get the most out of Docker, Elastic Beanstalk lets you create an environment where your Amazon EC2 instances run multiple Docker containers side by side ... Elastic Beanstalk uses Amazon Elastic Container Service (Amazon ECS) to coordinate container deployments to multicontainer Docker environments. SEE ^^^^^^^^ CAUTION CAUTION CAUTION CAUTION CAUTION CAUTION ^^^^^^^^ * Ports: To map ports, for example, the JSON configuration would include: "portMappings": [ { "containerPort": integer, "hostPort": integer } ... ] Port mappings allow containers to access ports on the host container instance to send or receive traffic. containerPort: - The port number on the container that is bound to the user-specified or automatically assigned host port. - If using containers in a task with the Fargate launch type, exposed ports should be specified using containerPort. - If using containers in a task with the EC2 launch type and you specify a container port and not a host port, your container automatically receives a host port in the ephemeral port range. hostPort: - The port number on the container instance to reserve for your container. - If using containers in a task with the Fargate launch type, the hostPort can either be left blank or be the same value as containerPort. - If using containers in a task with the EC2 launch type, you can specify a non-reserved host port for your container port mapping (this is referred to as static host port mapping), or you can omit the hostPort (or set it to 0) while specifying a containerPort and your container automatically receives a port (this is referred to as dynamic host port mapping) in the ephemeral port range for your container instance operating system and Docker version. * Volumes: To map volumes: specify a list of volumes to be passed to the Docker daemon on a container instance. { "Volumes": [ { "HostDirectory": "/path/inside/host", "ContainerDirectory": "/path/inside/container" } ] ... The following are the types of data volumes that can be used: 1. Docker Volumes: Docker-managed volume that is created under /var/lib/docker/volumes on the container instance. 2. Bind Mounts: A file or directory on the host machine is mounted into a container. Bind mount host volumes are supported when using either the EC2 or Fargate launch types. To use bind mount host volumes, specify a host and optional sourcePath value in your task definition. E.g.: "volumes": [ { "name": "dashboards", "host": { "sourcePath": "/var/app/current/dashboards" } }, NOTE: /var/app/current is the directory on the host machine that contains the deployment artifact, i.e. the .zip file unzipped. And so on. See the reference link at the top of the sub-section for details. - Goto EBS on AWS web console. - Select "Create New Application" - Give the app a name and description - Environment tier = Web Server Prodefined config = Docker Environment type = Load balancing, autoscaling - Select "Upload Your Own" Upload the `Dockerrun.aws.json` file Terminating HTTPS on EC2 instances running Docker - - - - - - - - - - - - - - - - - - - - - - - - - See: See: Above section "Configuring Elastic Beanstalk" Create a file `.ebextensions/https-instance.config`, to configure the NGINX instance. The config will create the following files, which are required by NGINX et al: 1. /etc/nginx/conf.d/https.conf - Configures the nginx server. This file is loaded when the nginx service starts. 2. /etc/pki/tls/certs/server.crt - Creates the certificate file on the instance. 3. /etc/pki/tls/certs/server.key - Creates the private key file on the instance !! CAUTION !!. To configure EBS to download the private keys from S3 during deployment you will need to create `.ebextensions/privatekey.config`. For example: Resources: AWSEBAutoScalingGroup: Metadata: AWS::CloudFormation::Authentication: S3Auth: type: "s3" buckets: ["MY_BUCKET_NAME"]: MY_BUCKET_URL/server.key Private Repositories - - - - - - - - - - - You don't have to use just DockerHub images. You can configure it to deploy images from your own private repos. [] The Docker and Multicontainer Docker platforms for Elastic Beanstalk support the use of Docker images stored in a public OR PIRVATE online image repository. Specify images by name in Dockerrun.aws.json. Note these conventions: - Images in official repositories on Docker Hub use a single name (for example, ubuntu or mongo). - Images in other repositories on Docker Hub are qualified with an organization name (for example, amazon/amazon-ecs-agent). - Images in other online repositories are qualified further by a domain name (for example, quay.io/assemblyline/ubuntu or account-id.dkr.ecr.us-east-2.amazonaws.com/ubuntu:trusty). [] AWS Region as the environment that is using it. For V1 (single Docker container) { "AWSEBDockerrunVersion": "1", ... "Authentication": { "Bucket": "my-bucket", "Key": "mydockercfg" }, "Image": { "Name": "quay.io/johndoe/private-image", "Update": "true" }, ... } For V2 (multi Docker) { "AWSEBDockerrunVersion": 2, ... "authentication": { "bucket": "my-bucket", "key": "mydockercfg" }, ... } [] To use a Docker image in a private repository hosted by an online registry, you must provide an authentication file that contains information required to authenticate with the registry. Generate an authentication file with the docker login command. For repositories on Docker Hub, run docker login: docker login registry-server-url Upload a copy named .dockercfg of the authentication file to a secure Amazon S3 bucket. Build Docker Image On Deployment - - - - - - - - - - - - - - - - - You can also get the deployment to BUILD your Docker image for you, rathen than pull it from a repository: [] Create a Dockerfile when you don't already have an existing image hosted in a repository. Deploying Ruby Applications to AWS Elastic Beanstalk with Git ------------------------------------------------------------- Ref: ^^^ WARNING/NOTE: I think the aricle is out of date. it meansions using the command `eb start`. I have tried this but it does not appear to be a command supported by `eb`: eb: error: unrecognized arguments: start The `eb` help says... To get started type "eb init". Then type "eb create" and "eb open" I have followed its advice and replaced the article's second-half with these suggested steps! WARNING/NOTE: I also found that after successfull setup Puma was having problems. I saw the following error message repeated many times in the Puma logs: connect() to unix:///var/run/puma/my_app.sock failed Nginx, the web-server, is failing to communicate with Puma, the application server. Why do we need both? See - See - A web server is a program that takes a request to your website from a user and does some processing on it. Then, it might give the request to your Rails app. Nginx and Apache are the two big web servers you’ll run into.). It seems routing to app is: NGINX ----[pass CGI reg]----> PUMA ----[Query App]----> ----> APP ----[Use sinatra to build/route REST end points]---->[App API endpoint called] ---->[Return CGI response]----> PUMA ---->[Return CGI response] ----> NGINX The above should help picture what's going on and what the various names like "Puma", "Sinatra" etc etc mean. See this SO thread for solutions:. In short the solution seems to be adding the following 2 lines to `config/puma.rb`: bind "unix:///var/run/puma/my_app.sock" pidfile "/var/run/puma/my_app.sock" See also: Also, the config file may be `${RAILS_ENV}/puma.rb' is RAILS_ENV is defined. Where to find the config? The file is stored in side the app's config directory. The app is a Gem, so I assume we follow this: Use `gem environment` to find out about your gem environment. Look for one of the two lines: - INSTALLATION DIRECTORY: /var/lib/gems/<version a.b.c> - USER INSTALLATION DIRECTORY: /home/<user>/.gem/ruby/<version a.b.c> Then under, probably the global installation directory you will find, for example: /var/lib/gems/2.5.0/gems/puma-4.3.5 Can also use `bundle info <gem name>` to see where the GEM is installed. To add these you will need to SSH into your EBS instance: eb ssh URG... FIDDLY AND TIME CONSUMING JUST TO SETUP A DASH... ABANDONING - WILL USE DOCKER IMAGE. EBS is clever - Gems listed in the Gemfile are AUTOMATICALLY INSTALLED FOR YOU (almost anyway!). To deploy to EBS must download & install AWS Elastic Beanstalk command line tool. Get the install scripts from GitHub: 1. Make sure the following apps are installed: sudo apt install -y build-essential zlib1g-dev libssl-dev libncurses-dev libffi-dev \ libsqlite3-dev libreadline-dev libbz2-dev 2. Clone git clone sudo ./aws-elastic-beanstalk-cli-setup/scripts/bundled_installer Running the install script takes a-g-e-s to install Python, so be patient. It doesn't give you any indication of progress :/ Go make a cup of tea and come back later! 3. Follow the "Finishing up" instructions at the end of the EB install to add EB to your PATH! echo 'export PATH="/home/jh/.ebcli-virtual-env/executables:$PATH"' >> ~/.bash_profile && source ~/.bash_profile 1. Initialize application with the CLI tool by typing: eb init You will need your AWS acces key ID and secret access key to login. Creates .elasticbeanstalk directory in project root. Add to .gitignore. You will also be asked if you want to continue with "CodeCommit". This option will allow you to create and manage Git repositories hosted by AWS CodeCommit with the Elastic Beanstalk: AWS CodeCommit is a fully-managed source control service that makes it easy ... to host ... private Git repositories. ... Get 5 active users per month for free (within limits), after which you pay $1 per additional active user per month. This also creates a Git subcommand - `aws.push`. To use this you must have initialised eb to use CodeCommit! To deploy app can now just type `git aws.push` (but don't use it yet - after the eb start). If you don't want to use CodeCommit you can upload the code from your local machine, or S3 bucket, like you would via the web console by using `eb create` with the `--source` option. Type `eb create --help` for further information. Try also `eb init --help` for more init options. For example you can use `eb init --region eu-west-2` to specify the region on the command line. Seems like which application you use is not specifiable from the CLI... need to enter this :/ 2. Create a new environment: eb create Choose the "application" load balancer Do not enable "Spot Fleet Requests" An example of the command output is useful to look at to see what EBS is doing behind the scenes for us in terms of setting up load blancers, EC2 instances, S3 buckets, security groups etc: INFO createEnvironment is starting. INFO Using elasticbeanstalk-XXXX as Amazon S3 storage bucket for environment data. INFO Created target group named: XXXX INFO Created security group named: XXXX INFO Created security group named: XXXX INFO Created Auto Scaling launch configuration named: XXXX INFO Created Auto Scaling group named: XXXX INFO Waiting for EC2 instances to launch. This may take a few minutes. INFO Created Auto Scaling group policy named: XXXX INFO Created Auto Scaling group policy named: XXXX INFO Created CloudWatch alarm named: XXXX INFO Created CloudWatch alarm named: XXXX INFO Created load balancer named: XXXX INFO Created Load Balancer listener named: XXXX INFO Application available at XXXX.elasticbeanstalk.com. INFO Successfully launched environment: XXXX Type `eb create --help` for further information. Some of the available options include: --source SOURCE - source of code to create from directly; example source_location/repo/branch --region REGION - use a specific region --profile PROFILE - use a specific profile from your credential file --elb-type ELB_TYPE - load balancer type --instance_profile EP - EC2 Instance profile, if you don't want to use the default. By DEFAULT, EBS CLI will AUTOMATICALLY PACKAGE YOUR PROJECT DIRECTORY AS A ZIP FILE AND UPLOAD THIS TO A NEW S3 BUCKET THAT IT CREATES ON YOUR BEHALF. I.e. creates an app archive from the application source code in the local project directory. To DEPLOY AN ARTIFACT INSTEAD OF THE PROJECT FOLDER: See The CLI doesn't by default allow you to use `--source` to specify a local ZIP file. 3. To debug things, under the environment created above, but accessed through the web console you can download server logs. Beanstalk With RDS ------------------ RDS = Relational Database Service, which is a web service that makes it easier to set up, operate, and scale a relational database in the AWS Cloud. Can launch RDS within EBS console - Good for development - Bad for production - DB lifecyle tied to app lifecyle - termination of env terminats DB too. - Prefer decouple of RDS instance from EBS env. I.e., launch outseide of EBS. - Provides more flexibility. - Can then connect multiple environments to same DB. - Wide choices of DB types. - Can tear down app without interfering with DB. To connect EBS to outside RDS - Req additional Security Group - add to environments Auto Scaling group. - Provide connection string config info to app servers (endpoint, pwd etc) using EBS properties. Configuring HTTPS for your Elastic Beanstalk environment -------------------------------------------------------- Simplest method = assign a server certificate to your environment's load balancer. Client to load balancer secure. Balancer to EC2 instance is not, but is hidden behind balancer so should be secure enough? For end-to-end HTTPS in a load balanced environment, can combine instance and load balancer termination to encrypt both connections. With AWS Certificate Manager (ACM), you can create a trusted certificate for your domain names for free. BUT domain names are pay-to-own. SEE NOTE - TO TERMINATE AT LOAD BALANCER When configurating the load balancer, make sure it listens on port 443 using HTTPS but *forwards* traffic to the backend using port 80, HTTP if you whish to terminate the HTTPS connection at the load balancer. Terminate HTTPS on the load balancer 1. Open the Elastic Beanstalk console, and then select your environment. 2. In the navigation pane, choose Configuration. 3. In the Load balancer category, choose Modify. 4. To add the listener for port 443, choose one of the following sets of steps based on the type of load balancer that your Elastic Beanstalk environment has. To add a listener for a Classic Load Balancer: 1. Choose Add Listener. 2. For Port, enter the incoming traffic port (typically 443). 3. For Protocol, choose HTTPS. 4. For Instance Port, enter 80. 5. For Instance Protocol, choose HTTP. 6. For SSL certificate, choose your certificate, and then choose the SSL policy that you want to use from the drop-down menu. 7. Choose Add, and then choose Apply. To add a listener for an Application Load Balancer: 1. Choose Add Listener. 2. For Port, enter the incoming traffic port (typically 443). 3. For Protocol, choose HTTPS. 4. For SSL certificate, choose your certificate, and then choose the SSL policy that you want to use from the drop-down menu. 5. Choose Add, and then choose Apply.
Cloudfront
See:. From AWS Website: Amazon CloudFront is a fast content delivery network (CDN) service that securely delivers data, videos, applications, and APIs to customers globally with low latency, high transfer speeds, all within a developer-friendly environment. Another AWS page:. ... Best for: Pre-packaged static sites provided by marketing organizations that are deployed via drag and drop. Cloudfront may allow FREE encryption using TLS via the AWS certificate manager. - Global content deliver network (CDN) - Application acceleration and optimization - Distributed scalable integrated security controls - Optimised for deliver use cases with intelligent caching. - On-demand, full user control. Cost effective.
Amplify Framework
From AWS Website: Provides a set of libraries and UI components and a command line interface to build mobile backends and integrate with your iOS, Android, Web, and React Native apps. []: an awesome continuous deployment (CD) platform for your web site. It has built in support ... for JavaScript single page applications written in a variety of frameworks like React ... Best for: Static site generators, JavaScript based single page applications.
Lightsail
Lightsail is an easy-to-use cloud platform that offers everything needed to build an app or website, plus a cost-effective, monthly plan. Ideal for simpler workloads, quick deployments, and getting started on AWS. The pricing scheme is way simpler, for example, than EBS. It seems to abstract even further away so that we don't even have to worry about what EC2 cost model and S3 cost model we'd use etc. []: If your app relies on a web language backend (like Ruby or PHP) or you use a common web site platform (like WordPress or Magento), then you might want to choose Amazon Lightsail. ... Best for: Common web stacks like LAMP, MEAN, and PHP, or common web applications like WordPress SSL/TLS Certificates In LightSail --------------------------------- Ref: Lightsail uses SSL/TLS certificates to handle encrypted web traffic (HTTPS requests). You can create certificates, verify domain ownership, and then attach the validated certificates to your Lightsail load balancer.
Dynamo Database
NoSQL databases (aka "not only SQL") are non-tabular, and store data differently than relational tables. NoSQL databases come in a variety of types based on their data model. The main types are document, key-value, ... They provide flexible schemas and scale easily with large amounts of data and high user loads. Dynamo is a NoSQL database. For apps that need single digit millisecond latency at any scale. Supports documents (JSON, XML, HTML) and key-value data models. DOCUMENTS: - See - See - Class of non-relational (NoSQL) database. - Store data in documents similar to JSON (JavaScript Object Notation) objects - Contain pairs of fields & values. - Values can be many things: strings, numbers, arrays, objects etc. - Structure typically aligns with objects developers work with - think objects serialised to JSON. - Powerful query languages. - Unlike relational DBs does not need a pre-defined schema and does less data normalisation, generally TABLES: Class of non-relational (NoSQL) database. Table rows are called ITEMS. Rows are broken up into columns called ATTRIBUTES. TABLE +--------+---------+-----+---------+ |Attrib1 | Attrib2 | ... | AttribN | +--------+---------+-----+---------+ Item 1 | | | | | +--------+---------+-----+---------+ Item 2 | | | | | +--------+---------+-----+---------+ .... | | | | | +--------+---------+-----+---------+ Item M | | | | | +--------+---------+-----+---------+ Each item is basically a set of key-value pairs. Think of each item as a JS object with keys and values or a JSON spec. Data is stored/retrieved based on a PRIMARY KEY. Two types of primary keys: 1. PARTITION KEY Unique attribute. Key is hashed , which determines the partion/physical location where data is stored. No two items can have same partition key. That's why no two items can have same key! 2. COMPOSITE KEY (PARTITION KEY + SORT KEY) E.g. same user posts multiple time to forum. IAM Conditions -------------- They are CONDITIONS which are added to an IAM POLICY. These can be used to restrict a uer's access to only certain items (rows) in a table! IAM conditions contain the following important keys: * "Sid" - STATEMENT IDENTIFIER - A unique identifying name for the policy * "Effect" - Are we allowing/denying etc * "Action"- The actions that this policy allows/denies (see "effect"). For example "dynamodb:GetItem", "dynamodb:PutItem", "dynamodb:UpdateItem" * "Resource" - The unique Amazon resource name for your dynamo db table * "Condition" - This is where you specify the conditions on which the policy applies, e.g., allowing users to acces only the items where the Parition Key value matches their user ID. * "ForAllValues:StringEquals" * "dynamodb:Attributes" Consistency Models ------------------ 1. Strongly consistent - Any write that occur before read are reflected in the read consistent across all locations. 2. Eventuall consistent - Can take up to 1 second for new writes to be reflected in a read across all locations.
Amazon Athena
Serverless interactive query service that makes it easy to analyze data in Amazon S3 using standard SQL. Easy to use: point to your data in Amazon S3, define the schema, and start querying using standard SQL. I.e., Query non database data container in things like CSV and JSON with a shim on top to make it look like a normal database that can be queried with standard SQL. Why Athena? - challenges customers faced - had to do work to get to S3 data, e.g. complex transformations etc: - Significant amount of work required to analyze data in Amazon S3 - Users often only have access to aggregated data sets - Managing a Hadoop clister or data warehouse requires expertise. What Athena gives: Athena is an INTERACTIVE QUERY SERVICE that makes it EASY to analyse data DIRECTLY FROM AWS S3 using STARTARD SQL. Results come back in seconds. It is NOT a database or a data warehouse - it is designed to enable you to write fast SQL queries with nothing to manage. - No infrastructure or administration - Zero spin up time - Transparent upgrades Easy to use - Log into console. - Create a table: - Type in a Hive Data Description Language (DDL) statement. - Use console Add Table wizard. - Start querying :) - Query data in its RAW FORMAT!! - Test, CSV, JSON, weblogs, AWS service logs etc. - Stream data directly from S3. - Query using ANSI SQL - well know language most devs are familiar with Highly available: - Takes afvantage of D3 durability and availability. - Service endpoint or log into console. - 99.999999999% durability. - uses warm compute pools across multiple availability zones.
Codecommit / Code Deploy / Code Pipeline
Code Deploy ----------- Can deploy to EC2 or on-premises systems! 2 approaches: 1. IN PLACE - The app is stopped on each instance and the new release is installed, - AKA ROLLING UPDATE, - Capacity is rediced during deployment, - Lambda no supported, - Roll-back involves a re-deploy, - Good for 1st time deployment. 2. BLUE / GREEN - New instance are provisioned and the new release is installed on the new instances. BLUE == active deployment GREEN == new release The ELB will be configured to route traffic to the green environment, but importantly the blue environment is left in tact. Therefore, rolling back to the previous version is super easy and no down-time on either step is experienced. When green is validated, the blue is just deleted and the green becomes blue, - No capcity reduction during deployment, - You pay for 2 environments until you terminate the old servers, - Safest option! AppSpec File - CodeDeploy Config - - - - - - - - - - - - - - - - The AppSpec file configures the CodeDeploy environment by defining the parameters to be used during deployment. The file specifies 4 main topics: 1. Version (reserved for future use) 2. OS - Which OS should you run 3. Files - the location of application files to be copied and where to copy to 4. HOOKS - Lifecycle event hooks specify scripts that need to be run at set points in the deployment lifecycle. They have a very specific order. Hooks include the following and are used to run scripts. The following shows a few of them in the RUN ORDER. - BeforeInstall - After install - ApplicationStart - ValidateService Doing A Deploment - - - - - - - - -
Elastic Container Service (Ecs) / Fargate & Ec2
Lets you run containerised workloads in AWS. Has deep intrgration with AWS services like Route53, IAM, VPC etc. ECS can run containers in 3 different configurations: 1. ECS - Run containers on a cluster of virtual machines. 2. FARGATE - This is the serverless option - no need to worry about underlying EC2 instances 3. EC2 - Used for fine grained control - control the installation, config and management of the compute environment. Elastic Container Registry (ECR) -------------------------------- Do run Docker services you must create an ECR - Elastic Container Registry. ECR is just a place where Docker images are stored. ECS connects to the ECR and uses the images to deploy Docker containers. Startup: aws configure Login: eval $(aws ecr get-login --no-include-email --region eu-west-2) Create repo: aws ecr create-repository --repository-name my-repo-name --region eu-west-2 Command will return the RESPOSITORY_URL. E.g.: jh@jehtech$ aws ecr create-repository --repository-name JEHTech --region eu-west-2 { "repository": { "repositoryArn": "arn:aws:ecr:eu-west-2:300012345678:repository/JEHTech", "registryId": "300012345678", "repositoryName": "JEHTech", "repositoryUri": "300012345678.dkr.ecr.eu-west-2.amazonaws.com/JEHTech", << THIS IS REPOSITORY_URL "createdAt": 1593780814.0, "imageTagMutability": "MUTABLE", "imageScanningConfiguration": { "scanOnPush": false } } } Upload: docker tag image-i-want-to-upload:version-tag RESPOSITORY_URL/image-i-want-to-upload:version-tag docker push RESPOSITORY_URL/image-i-want-to-upload:version-tag See --- Example Using Smashing Docker Image On ECS ------------------------------------------ Micro Services -------------- Monolothic apps - many distinct parts of an application on one server make it hard to scale because the demands on that one server increase rapidly and the application either has to be duplicated on another server or split up into components which can expand on their own servers. All of this is hard with a monolithic app. You have to SCALE THE ENTIRE APPLICATION. E.g. User profile data, photo uploading an editing, thumbnails, photo viewe etc in one app on one server. Failures in any one compnent of the app would probably bring down the whole application. With microservices you ONLY HAVE TO SCALE THE PARTS THAT NEED IT. Serperates the jobs of an independent server into INDEPENDENT SMALLER services. Gives ability to use smaller resources to handle large tasks. Each service does just its workload. So, now in e.g. requests for auth goto the auth micro service, Photo uploads processes by the upload micro service, the editing by the edit service and so on. Containers are an excellent way to serve micro services. Far Gate -------- Running containers on EC2 is good. But need to keep track of all the pieces you needto manage. You have to manage: 1. The EC2 instances (your cluster) on which the containers sit For example you might have to commision several EC2 instances, have them in different subnets and then connect the subnets together in a Virtual Private Cloud (VPC) - Have to contunaly patch/update the instances and evaluate secutiry robustness - Have to setup autoscaling - Have to have Docker installed on each instance - You will interact with the DOcker instances using ECS - Elastic Continer Service. 2. The containers themselves Each EC2 will have multiple Docker containers running in it. Fargate answers the question HOW CAN YOU RUN CONTAINERS WITHOUT HAVING TO WORRY ABOUT SETTING UP ALL THIS INFRASTRUCTURE?? AWS Fargate is a serverless computing engine and hosting option for container based workloads. Fargate abstracts away the infrastructure management issue. You no longer have to "see" the EC" instance details. You just see fargate clusters and ECS. You only pay when your containers are running.
Kinesis
Which Aws Service To Publish A Website?
Ref: Brilliant article that quotes have been made from in above sections. Summary here: Options include: - Amazon S3 + Amazon Cloudfront Best for: Pre-packaged static sites provided by marketing organizations that are deployed via drag and drop. - AWS Amplify Console Best for: Static site generators, JavaScript based single page applications. - Amazon Lightsail Best for: Common web stacks like LAMP, MEAN, and PHP, or common web applications like WordPress, MediaWiki, and Magento. - AWS Elastic Beanstalk Best for: Your most challenging enterprise apps where access to the underlying OS is required. - AWS EC2 - Do-it-yourself compute / storage / network stack Best for: Your most challenging enterprise apps where you can use a variety of AWS services to augment your service offering. | https://jehtech.com/aws.html | CC-MAIN-2021-25 | refinedweb | 10,948 | 56.76 |
Yes, all I patched was tg3.c and tg3.hThanks.On Tue, 10 Sep 2002, David S. Miller wrote:> From: Steve Mickeler <steve@neptune.ca>> Date: Tue, 10 Sep 2002 17:19:53 -0400 (EDT)>> Compiling in tg3 support using the tg3.c and tg3.h from 2.4.20-pre6> ...> tg3.c: In function `tg3_rx':> tg3.c:1977: warning: implicit declaration of function `netif_receive_skb'>> I pretty sure you mispatched your tree.>> It's there in 2.4.20-pre6:>> bash$ egrep netif_receive_skb patch-2.4.20-pre6> + netif_receive_skb (skb);> +3) instead of netif_rx() we call netif_receive_skb() to pass the skb.> + netif_receive_skb(skb);> + return (polling ? netif_receive_skb(skb) : netif_rx(skb));> +extern int netif_receive_skb(struct sk_buff *skb);> +int netif_receive_skb(struct sk_buff *skb)> + netif_receive_skb(skb);> +EXPORT_SYMBOL(netif_receive_skb);> bash$>[-]-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at | http://lkml.org/lkml/2002/9/10/244 | CC-MAIN-2015-35 | refinedweb | 153 | 71.92 |
Update 2011-06-29: The title of this post should really be “Think about your grammer’s level of nondeterminism before writing an inflamatory blog post about monadic parsing.” I would like to thank the commenters for bringing various solutions to my attention. Also, someone seems to have posted it to reddit and there is a good conversation over there.
This post was written using BlogLiterately. The literate Haskell source file is parse_speed_test.lhs.
In late 2010 I went to a meeting of the Brisbane Functional Programmers Group. Tony Morris talked about using Haskell for parsing large GPS datasets. If I recall correctly, Tony said something like “you need to use arrows for parsing large datasets, not monads, because using monads will be slow.”
Someone from the audience asked why this was the case, but no one was able to give a clear answer. I decided to write a small parser using monads in Haskell and collect some run times. In the code below, I borrowed a few definitions from some slides of an earlier talk by Tony Morris at BFPG, such as bindParser, mapParser, sequenceParser, etc. Tony’s slides are quite good so I won’t attempt to repeat his explanation of how monads can be used for parsing.
> import Data.Char > import Maybe > import System.Environment > > data Parser a = P { > parse :: String -> Maybe (String, a) > } > > instance Monad Parser where > (>>=) = bindParser > return = value > > failed :: Parser a > failed = P (_ -> Nothing) > > character :: Parser Char > character = P (s -> case s of [] -> Nothing > (c:r) -> Just (r, c)) > > (|||) :: Parser a -> Parser a -> Parser a > P p1 ||| P p2 = P (s -> case p1 s of v@(Just _) -> v > Nothing -> p2 s) > > mapParser :: Parser a -> (a -> b) -> Parser b > mapParser (P p) f = P (s -> case p s of Just (r, c) -> Just (r, f c) > Nothing -> Nothing) > > bindParser :: Parser a -> (a -> Parser b) -> Parser b > bindParser (P p) f = P (s -> case p s of Just (r, c) -> parse (f c) r > Nothing -> Nothing) > > value :: a -> Parser a > value a = P (s -> Just (s, a)) > > (>>>) :: Parser a -> Parser b -> Parser b > p >>> q = bindParser p (_ -> q) > > sequenceParser :: [Parser a] -> Parser [a] > sequenceParser [] = value [] > sequenceParser (h:t) = bindParser h (a -> mapParser (sequenceParser t) (as -> a : as)) > > list :: Parser a -> Parser [a] > list k = many1 k ||| value [] > > many1 :: Parser a -> Parser [a] > many1 k = bindParser k (k' -> mapParser (list k) (kk' -> k' : kk')) > > satisfy :: (Char -> Bool) -> Parser Char > satisfy p = bindParser character (c -> if p c then value c else failed) > > is :: Char -> Parser Char > is c = satisfy (== c) > > space :: Parser Char > space = satisfy isSpace > > alpha :: Parser Char > alpha = satisfy isAlpha
Let’s try to parse an XML-like document. For simplicity we will use angle brackets (as in normal XML) and allow any other character in a tag’s name:
> nonAngleBracket c = not $ c `elem` [''] > > xmlTagNameParser :: Parser String > xmlTagNameParser = many1 (satisfy nonAngleBracket)
An open tag has a left angle bracket, some characters for the name, and a right angle bracket. This can be written very succintly in Haskell with do notation:
> openTagParser :: Parser String > openTagParser = do list space > is ' tag_name is '>' > return (head (words tag_name))
Similarly for a closing tag:
> closeTagParser :: Parser String > closeTagParser = do list space > is ' is '/' > tag_name is '>' > return tag_name
The text inside a basic XML structure can be any ASCII character except for an opening bracket.
> xmlTextFieldParser :: Parser String > xmlTextFieldParser = list (satisfy (c -> isAscii c && (c /= '<')))
The simplest XML structure that we will parse is a balanced pair of tags with some text inbetween, such as: hey there.
> xmlTextElementParser :: Parser [(String, String)] > xmlTextElementParser = do open_tag_name text_body close_tag_name if open_tag_name /= close_tag_name then failed else return [(close_tag_name, text_body)]
The other kind of structure that we can parse is a pair of balanced tags with some list of text bits inside, such as:
bar valuemeh value
The top level definition of the parse is thus:
> xmlToTagValueList :: Parser [(String, String)] > xmlToTagValueList = > do open_tag_name body close_tag_name if open_tag_name /= close_tag_name then failed else return ((close_tag_name, "->"):(concat body))
For testing purposes we will try to parse the input file and then report the number of parsed XML-like elements.
> main = do args x let x' = parse (list xmlToTagValueList) x > print (length (head (snd (fromJust x'))))
For testing I will use a file with one line repeated inside a block. The file input10.txt has 10 lines in the inner block:
do de dah bar do de dah bar do de dah bar do de dah bar do de dah bar do de dah bar do de dah bar do de dah bar do de dah bar do de dah bar
Here are some run times on a lightly loaded 2Ghz Xeon running Ubuntu 10.10 with GHC 6.12.1, and the binary compiled with “ghc -O –make”. This parse is clearly impractical if parsing 30 lines of text will take over 1.5 hours:
This kind of issue turns out to be a well known problem with monadic parsing. The answer comes from John Hugh’s 1998 paper Generalising Monads to Arrows, from which I now quote:
Although the idea of programming with combinators is quite old, the design of combinator libraries has been profoundly infuenced in recent years by Wadler’s introduction of the concept of a monad into functional programming[Wad90, Wad92, Wad95]. We shall discuss monads much more fully in the next section, but for now, suffice it to say that a monad is a kind of standardised interface to an abstract data type of `program fragments’. The monad interface has been found to be suitable for many combinator libraries, and is now extensively used. Numerous benefits flow from using a common interface: to take just one example, Haskell has been extended with special constructions to make the use of monads particularly convenient.
It is therefore a matter for some concern when libraries emerge which cannot, for fundamental reasons, use the monad interface. In particular, Swierstra and Duponcheel have developed a very interesting library for parsing LL-1 grammars[SD96], that avoids a well-known inefficiency in monadic parsing libraries by combining the construction of a parser with a `static analysis’ of the program so constructed. Yet Swierstra and Duponcheel’s optimisation is incompatible with the monad interface. We believe that their library is not just an isolated example, but demonstrates a generally useful paradigm for combinator design that falls outside the world of monads. We shall look more closely at their idea in section 3. Inspired by Swierstra and Duponcheel’s library, I sought a generalisation of the monad concept that could also offer a standardised interface to libraries ofthis new type. My proposal, which I call arrows, is the subject of this paper. Pleasingly, the arrow interface turned out to be applicable to other kinds of non-monadic library also, for example the fudgets library for graphical user interfaces [CH93], and a new library for programming active web pages. These applications will be described in sections 6 and 9.
While arrows are a little less convenient to use than monads, they have significantly wider applicability. They can therefore be used to bring the benefits of monad-like programming to a much wider class of applications.
The paper by Swierstra and Duponcheel pretty much sums things up:.
To learn about arrows in Haskell, go here:.
Archived Comments
Date: 2011-06-27 06:12:37 UTC
Author: Heinrich Apfelmus
Errm, while there are some optimizations that can only be done with parser combinators based on Arrows or Applicative, it appears to me that your example is simply a bad case of excessive backtracking. 🙂 Parser combinators are not entirely foolproof, you always have to put a little effort in combinator design and grammar design to get usable performance (aka not exponential).
Date: 2011-06-27 07:38:00 UTC
Author: Vincent Toups
.”
As I understand it, you just need to use the right monad. Your parser monad can be combined with an error monad or a continuation monad to provide more sophisticated error handling features. The last slide of my recent talk about this subject mentions this, briefly:
Date: 2011-06-28 00:48:18 UTC
Author: Malcolm Wallace
The problems with error reporting and performance mentioned in a 15-year-old paper have been addressed long ago, by many researchers. For one treatment of exactly these problems (errors and performance), which even uses your example of simplified XML-parsing, see
Don’t miss the performance tables which (for instance) demonstrate parsing of a 1 million element XML file.
Date: 2011-06-29 15:02:43 UTC
Author: Brandon
Monadic parsers may miss out on some optimizations, but the main problem here is the massive nondeterminism in your grammar. You allow ‘/’ in tag names, so can be interpreted as an opening tag as well.
Change
> nonAngleBracket c = not $ c `elem` [”]
to
> nonAngleBracket c = not $ c `elem` [”, ‘/’]
and a test file with 20,000 lines parses in under a second.
Do you have any tests showing that other styles of parser combinators (or parser generators) can handle handle the original ambiguous grammar any better?
Date: 2011-06-29 21:09:00 UTC
Author: carlo
Brandon: Firstly, WordPress messed up the ” in your comment so I edited it on your behalf – I hope this is ok. I tried your suggestion and indeed it is blazingly fast.
Secondly, no, I have not tried any other styles of parser combinators. | https://carlo-hamalainen.net/2011/02/ | CC-MAIN-2017-51 | refinedweb | 1,564 | 52.63 |
To view parent comment, click here.
To read all comments associated with this story, please click here.
Even simple things like zebra striping in IE8 don't work (via nth-child, or any :nth selectors), selection::, :not, border-radius, TONS of css issues when styling tables (tbody scrolling took so long to only barely work in ie
), opacity issues (have to use the IE filters hacks).
Though IE8 is miles ahead of IE7. In IE8, it usually just doesn't support the feature, in IE7 and IE6, it would botch it terribly instead of letting you gracefully fallback. I can live with having to support IE 8 for a while longer. In the corporate world it'll be common for a while since it's the last IE browser for XP
(that's what I meant by "the new IE6"... it's here for a while)
My biggest issue is knowing that when IE6 became the dominant browser by default (was good enough at the time and Netscape faded and Mozilla was being crazy), MS completely disbanded the IE team and basically held back web development for years with the monstrosity that became so entrenched.
Never again.
Edited 2012-10-02 06:47 UTC
IE 8 doesn't support CSS 3, it supports CSS 2.1. There are plenty of polyfills that are already available.
Yeah I agree with this. Though most of the problems were hasLayout, alpha transparency and some of the default browsers styles were a bit messed up with forms. When I still had to support IE6, I still managed okay with a small IE6 stylesheet and tried to write my CSS to work across everything.
My argument is that corporate internet doesn't need rounded corners and other pretty things.
Member since:
2009-08-18
There is nothing wrong with IE8. Until Firefox 3.0 (I think) it was doing a better job of being Standards compliant.
Also what nobody mentions is that if you add an XML element to an XHTML document, every browser except IE will happily ignore that whether or not the namespace is declared at the top of the document or not, and render it even though it is invalid XML.
There is a lot of stuff IE gets wrong, but other browsers do lots of shitty things as well (until I think Chrome 12 or 13, if you were rendering a legend tag with display:block, it wouldn't render correctly unless you added a padding to the fieldset).
As for the missing CSS 3.0 features most of these weren't actually finalised or proposed by the time IE9 was beta. Chrome and Firefox have a very different release schedule than Internet Explorer and why there is always a discrepancy in features. | http://www.osnews.com/thread?537258 | CC-MAIN-2014-42 | refinedweb | 462 | 68.1 |
Get mininum and maximum dates in backtrader DataFeed
I am trying to simulate a BuyAndHold strategy, following the example given in the BackTrader tutorial. My problem is that my strategy does not run for the full time period that I defined for my data feeds. One possibility would be that the products queried by the DataFeed (I am using YahooFinanceData) were not yet available.
Is it possible to identify the max and min dates that are available in the DataFeed? For instance, the product VGEK.DE is not available before 24.09.2019, hence I would assume that the strategy cannot be back-tested before that data.
Please find my code below.
# Defining Data Feed start=datetime.datetime(2017,1,1) end=datetime.datetime(2020,7,15) pacific_feed = bt.feeds.YahooFinanceData(dataname='VGEK.DE',period='d', fromdate=start, todate=end)
# Defining strategy class BuyAndHold_More_Fund_Pacific(bt.Strategy): params = dict( monthly_cash=700.0, # amount of cash to buy every month ) def start(self): # Activate the fund mode and set the default value at 100 self.broker.set_fundmode(fundmode=True, fundstartval=100.00) self.cash_start = self.broker.get_cash() self.val_start = 100.0 # Add a timer which will be called on the 1st trading day of the month self.add_timer( bt.timer.SESSION_END, # when it will be called monthdays=[1], # called on the 1st day of the month monthcarry=True, # called on the 2nd day if the 1st is holiday ) def notify_timer(self, timer, when, *args, **kwargs): # Add the influx of monthly cash to the broker self.broker.add_cash(self.p.monthly_cash) # buy available cash target_value = self.broker.getcash() + self.p.monthly_cash data_feed = self.getdatabyname(name='VGEK.DE') size = round(target_value/self.data.close,2) order = self.buy(exectype=bt.Order.Market,size=size,data=data_feed) def stop(self): # calculate the actual returns self.roi = (self.broker.get_value() / self.cash_start) - 1.0 self.froi = self.broker.get_fundvalue() - self.val_start print('ROI: {:.2f}%'.format(100.0 * self.roi)) print('Fund Value: {:.2f}%'.format(self.froi)) print ('broker fund value {} broker val start {}'.format(self.broker.get_fundvalue(),self.val_start))
# run back testing cerebro = bt.Cerebro() # Add a strategy cerebro.addstrategy(BuyAndHold_More_Fund_Pacific) cerebro.broker.set_cash(0.000001) cerebro.broker.set_fundmode(True) cerebro.adddata(data_pacific, name='VGEK.DE') print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue()) # Observers cerebro.addobserver(bt.observers.TimeReturn, timeframe=bt.TimeFrame.Days) # Analyzers cerebro.addanalyzer(bt.analyzers.PyFolio, _name='pyfolio', timeframe=bt.TimeFrame.Days) cerebro.addanalyzer(bt.analyzers.PositionsValue, headers=True, cash=True, _name='mypositions') cerebro.addanalyzer(bt.analyzers.TimeReturn,_name='timereturn') results = cerebro.run() print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
What is also not clear to me is why transactions are not completed every month. If I export the transactions:
transactions.head()
amount price sid symbol value
date
2018-02-02 23:59:59.999989+00:00 81.30 42.74 0 VGEK.DE -3474.7620
2018-05-03 23:59:59.999989+00:00 50.55 41.77 0 VGEK.DE -2111.4735
2018-08-02 23:59:59.999989+00:00 46.09 45.77 0 VGEK.DE -2109.5393
2019-01-03 23:59:59.999989+00:00 83.79 41.33 0 VGEK.DE -3463.0407
2019-08-02 23:59:59.999989+00:00 95.61 50.33 0 VGEK.DE -4812.0513
I see that there is not a transaction being completed every month.
Thanks for the help!
@gabrielfior said in Get mininum and maximum dates in backtrader DataFeed:
I see that there is not a transaction being completed every month.
Without getting deeper into the script - you defined amount of shares to buy based on the
closeprice.
btexecutes the order based on the next bar
openprice. If this price is higher than the previous
closeprice, than it is not enough cash to buy and orders are rejected.
Your first issue is not clear.
btworks only if data available, if it is not available, than backtest is meaningless.
@ab_trader said in Get mininum and maximum dates in backtrader DataFeed:
available, if it is not available, than backtest is meaningl
Thanks for the clarification regarding
buy. I will adapt my script.
Rephrasing my first issue: is it possible to check before executing
cerebro.run(), if the data feeds comprise the simulation period? A concrete example:
- I have 2 data feeds, VUSA.DE and VGEK.DE.
- I follow the BuyAndHold strategy and buy a defined size of both products on the 1st day of each month of the simulation
- I want to backtest my strategy between 2015-01-01 and 2020-07-01. If either one of the products is not available previously, I believe that the order is not going to be executed, thus the portfolio will not reflect my strategy correctly (due to the missing data feed). Thus I would like to check beforehand (e.g. by downloading the DataFeed from yahoo to a local file, for instance) if the data feed has data for the whole simulated period.
You can pre-scrub your data using pandas, then if it passes your test, load the data into the backtest.
So, if I understand correctly, than you want to have backtest goes only if all data feeds are available. And if one of them is missing, than don't do anything. If this is what you want, than you can try to do the following:
- in the strategy
initor
startset
self.do_test = False
- in the strategy
nextstartset
self.do_test = True
- in the strategy
notify_timerdo actions only if
self.do_test = True
I didn't test it, but it should work.
Or you can pre-process your data feeds as @run-out proposed.
One other option might be to check the array length of the datas in init or start.
For example if I put in four different stocks with different start dates:
diff_secs = [ ("FB", datetime.datetime(2019, 5, 1)), ("TSLA", datetime.datetime(2019, 6, 1)), ("NVDA", datetime.datetime(2019, 7, 1)), ("MSFT", datetime.datetime(2019, 8, 1)), ] for co in diff_secs: data = bt.feeds.YahooFinanceData( dataname=co[0], fromdate=co[1], todate=datetime.datetime(2020, 7, 8), ) cerebro.adddata(data)
Then you can count the lenght of array:
def __init__(self): for d in self.datas: print(f"stock: {d._name}, length: {len(d.array)}")
Resulting in:
stock: FB, length: 299 stock: TSLA, length: 277 stock: NVDA, length: 257 stock: MSFT, length: 235
@run-out @ab_trader Thanks for the examples and the help.
I will try those approaches in the next days.
Thanks | https://community.backtrader.com/topic/2781/get-mininum-and-maximum-dates-in-backtrader-datafeed | CC-MAIN-2020-34 | refinedweb | 1,076 | 52.76 |
.NET Compact Framework Graphics
- An Introduction to .NET Compact Framework Graphics
- Drawing on the Display Screen
- Raster Graphics
- Vector Graphics
- CONCLUSION
This chapter introduces the basics of creating graphical output from .NET Compact Framework programs.
This chapter describes the support that the .NET Compact Framework provides programs for creating graphical output. As we mention elsewhere in this book, we prefer using .NET Compact Framework classes whenever possible. To accomplish something beyond what the .NET Compact Framework supports, however, we drill through the managed-code layer to the underlying Win32 API substrate. This chapter and the two that follow discuss the .NET Compact Framework's built-in support for creating graphical output; these chapters also touch on limitations of that support and how to supplement that support with the help of GDI functions.
An Introduction to .NET Compact Framework Graphics
In general, programs do not create graphical output by drawing directly to device hardware. [1] A program typically calls a library of graphical output functions. Those drawing functions, in turn, rely on device drivers that provide the device-specific elements needed to create output on a device. Historically, creating output on a graphic device such as a display screen or a printer involves these software layers:
Drawing program
Graphic function library
Graphic device driver (display driver or printer driver)
The core graphics library on desktop Windows is the Graphics Device Interface (GDI, gdi32.dll). With the coming of .NET, Microsoft added a second library (GDI+, gdiplus.dll [2] ) to supplement GDI drawing support. This second library provides a set of enhancements on top of the core GDI drawing functions. While the primary role for GDI+ was to support graphics for the managed-code library, it also provides a nice bonus for native-mode application programmers: the library can be called from unmanaged (native-mode) C++ programs. On the desktop, these two graphic librariesGDI and GDI+provide the underpinnings for all of the .NET graphic classes. And so, with .NET Framework programs running on the Windows desktop, the architecture of graphical output involves the following elements:
Managed-code program
Shared managed-code library (System.Drawing.dll)
GDI+ native-code library (gdiplus.dll)
GDI native-code library (gdi32.dll)
Graphic device driver (display driver or printer driver)
Windows CE supports a select set of GDI drawing functions. There is no library explicitly named GDI in Windows CE. Instead, the graphical output functions reside in the coredll.dll library. These functions are exactly like their desktop counterparts, so even if there is no library named GDI in Windows CE, we refer to these functions as GDI functions.
NET Framework Drawing and Desktop Graphic Device Drivers
With the introduction of the .NET Framework, no changes were required to the graphic device drivers of any version of Microsoft Windows. That is, the device driver model used by both display screens and printer drivers was robust enough to support the .NET drawing classes..
With just 85 of the graphical functions from the desktop's GDI library and none of the functions from GDI+, you might wonder whether Windows CE has enough graphics support to create interesting graphical output. The answer is a resounding: Yes! While there are not a lot of graphical functions, the ones that are present were hand-picked as the ones that programs tend to use most. For example, there is a good set of text, raster, and vector functions. A program can use fonts to create rich text output, display bitmaps along with other kinds of raster data (like JPEG files), and draw vector objects such as lines and polygons.
For graphical output, .NET Compact Framework programs rely on System.Drawing.dll, which is also the name of the graphical output library in the desktop .NET Framework. At 38K, the .NET Compact Framework library is significantly smaller than the 456K of its counterpart on the desktop. While the desktop library supports five namespaces, the .NET Compact Framework version supports one: System.Drawing (plus tiny fragments of two other namespaces). The architecture for drawing from a .NET Compact Framework program is as follows:
Managed-code program
Managed-code library (System.Drawing.dll)
GDI functions in the native-code library (coredll.dll)
Graphic device driver (display or printer)
From the arrangement of these software layers, a savvy .NET Compact Framework programmer can divine two interesting points: (1) The managed-code library depends on the built-in GDI drawing functions, and managed-code programs can do the same; and (2) as on the desktop, display screens and printers require a dedicated graphic driver to operate.
If Possible, Delegate Graphical Output to a Control
Before you dig into .NET Compact Framework graphics, ask yourself whether you want to create the graphical output yourself or can delegate that work to a control. If a control exists that can create the output you require, you can save yourself a lot of effort by using that control instead of writing the drawing code yourself. For example, the PictureBox control displays bitmaps and JPEG images with little effort. Aside from that single control, however, most controls are text-oriented.
Doing your own drawingand making it look goodtakes time and energy. By delegating graphical output to controls, you can concentrate on application-specific work. The built-in controls support a highly interactive, if somewhat text-oriented, user interface.
Sometimes, however, you do your own drawing to give your program a unique look and feel. In that case, you can create rich, graphical output by using classes in the .NET Compact Framework's System.Drawing namespace.
Drawing Surfaces
On the Windows desktop, there are four types of drawing surfaces:
Display screens
Printers
Bitmaps
Metafiles
When we use the term drawing surface, we mean either a physical drawing surface or a logical drawing surface. Two of the four drawing surfaces in the list are physical drawing surfaces, which require dedicated device drivers: display screens and printers. The other two drawing surfaces are logical drawing surfaces: bitmaps and metafiles. These latter two store pictures for eventual output to a device.
Bitmaps and metafiles are similar enough that they share a common base class in the desktop .NET Framework: the Image [3] class. Metafiles are not officially supported in Windows CE, however, and so their wrapper, the Metafile [4] class, does not exist in the current version of the .NET Compact Framework. Because metafiles might someday be supported in a future version of the .NET Compact Framework, they are worth a brief mention here.
Display Screens
The display screen plays a central role in all GUI environments because it is on the display screen that a user interacts with the various GUI applications. The real stars of the display screen are the windows after which the operating system gets its name. A window acts as a virtual console [5] for interacting with a user. The physical console for a desktop PC consists of a display screen, a mouse, and a keyboard. On a Pocket PC, the physical console is made up of a display screen, a stylus and a touch-sensitive screen for pointing, and hardware buttons for input (supported, of course, by the on-screen keyboard).
All graphical output on the display screen is directed to one window or another. Enforcement of window boundaries relies on clipping. Clipping is the establishment and enforcement of drawing boundaries; a program can draw inside clipping boundaries but not outside them. The simplest clipping boundaries are a rectangle. The area inside a window where a program may draw is referred to as the window's client area.
Printers
Printers are the best-established and most-connected peripherals in the world of computers. While some industry pundits still rant about the soon-to-arrive paperless office, just the opposite has occurred. Demand for printed output has continued to go up, not down. Perhaps the world of computerswith its flashing LCD displays, volatile RAM, and ever-shrinking siliconmakes a person want something that is more real.
Printing from Windows CEpowered devices is still in its infancy, which is a nice way to say that this part of the operating system is less feature-rich than other portions. Why is that? The official story is that there is not a good enough business case for adding better printing support, meaning that users have not asked for it. The fundamental question, then, is "Why haven't users asked for better printing for Windows CE?" Perhaps it is because users are used to printing from desktop PCs. Or perhaps the problem stems from the lack of printing support in programs bundled with Pocket PCs (like Pocket Word and Pocket Excel). Whatever the cause, we show you several ways to print in Chapter 17 so that you can decide whether the results are worth the effort.
Bitmaps
Bitmaps provide a way to store a picture. Like its desktop counterparts, Windows CE supports device-independent bitmaps (DIBs) as first-class citizens. In-memory bitmaps can be created of any size [6] and treated like any other drawing surface. After a program has drawn to a bitmap, that image can be put on the display screen.
If you look closely, you can see that Windows CE and the .NET Compact Framework support other raster formats. Supported formats include GIF, PNG, and JPEG. When Visual Studio .NET reads files with these formats (which it uses for inclusion in image lists, for example), it converts the raster data to a bitmap. The same occurs when a PNG or JPEG file is read from the object store into a .NET Compact Framework program. Whatever external format is used for raster data, Windows CE prefers bitmaps. In this chapter, we show how to create a bitmap from a variety of sources and how to draw those bitmaps onto the display screen from a .NET Compact Framework program.
Compressed Raster Support on Custom Windows CE Platforms
Pocket PCs support the compressed raster formats, that is, GIF, PNG, and JPEG files. Custom Windows CE platforms must include the image decompression library, named imgdecmp.dll, to receive that same support.
Metafiles
A second picture-storing mechanism supported by desktop Windows consists of metafiles. A metafile is a record-and-playback mechanism that stores the details of GDI drawing calls. The 32-bit version of Windows metafiles are known as Enhanced Metafiles (EMFs). The following Win32 native metafile functions are exported from coredll.dll but are not officially supported in Windows CE, although they might gain official support in some future version of Windows CE:
CreateEnhMetaFile
PlayEnhMetaFile
CloseEnhMetaFile
DeleteEnhMetaFile
Supported Drawing Surfaces
Of these four types of drawing surfaces, three have official support in Windows CE: display screens, printers, and bitmaps. Only two are supported by the .NET Compact Framework: display screens and bitmaps. Support for bitmaps centers around the Bitmap [7] class, which we discuss later in this chapter. We start this discussion of graphical output with the drawing surface that is the focus in all GUI systems: the display screen.
Drawing Function Families
All of the graphical output functions can be organized into one of three drawing function families:
Text
Raster
Vector
Each family has its own set of drawing attributes and its own logic for how its drawing is done. The distinction between these three kinds of output extends from the drawing program into the graphic device drivers. Each family is complex enough for a programmer to spend many years mastering the details and intricacies of each type of drawing. The drawing support is rich enough, however, so that you do not have to be an expert to take advantage of what is offered.
Text Output
For drawing text, the most important issue involves selection of the font because all text drawing requires a font, and the font choice has the greatest impact on the visual display of text. The only other drawing attribute that affects text drawing is colorboth the foreground text and the color of the background area. We touch on text briefly in this chapter, but the topic is important enough to warrant a complete chapter, which we provide in Chapter 16.
Raster Output
Raster data involves working with arrays of pixels, sometimes known as bitmaps or image data. Internally, raster data is stored as a DIB. As we discuss in detail later in this chapter, six basic DIB formats are supported in the various versions of Windows: 1, 4, 8, 16, 24, and 32 bits per pixel. Windows CE adds a seventh DIB format to this set: 2 bits per pixel.
Windows CE provides very good support for raster data. You can dynamically create bitmaps, draw on bitmaps, display them for the user to see, and store them on disk. A bitmap, in fact, has the same rights and privileges as the display screen. By this we mean that you use the same set of drawing functions both for the screen and for bitmaps. This means you can use bitmaps to achieve interesting effects by first drawing to a bitmap and subsequently copying that image to the display screen. An important difference from desktop versions of Windows is that Windows CE does not support any type of coordinate transformations, and in particular there is no support for the rotation of bitmaps; the .NET Compact Framework inherits these limitations because it relies on native Win32 API functions for all of its graphics support.
Vector Output
Vector drawing involves drawing geometric figures like ellipses, rectangles, and polygons. There are, in fact, two sets of drawing functions for each type of figure. One set draws the border of geometric figures with a pen. The other set of functions fill the interiors of geometric figures using a brush. You'll find more details on vector drawing later in this chapter.
.NET Compact Framework Graphics
The .NET Framework has six namespaces that support the various graphical output classes. In the .NET Compact Framework, just one namespace has made the cut: System.Drawing. This namespace and its various classes are packaged in the System.Drawing.dll assembly. For a detailed comparison between the graphics support in the .NET Framework and in the .NET Compact Framework, see the sidebar titled Comparing Supported Desktop and Smart-Device Drawing.
Comparing Supported Desktop and Smart-Device Drawing
The System.Drawing namespace in the .NET Compact Framework holds the primary elements used to draw on a device screen from managed code. The desktop .NET Framework provides five namespaces for creating graphical output, but in the .NET Compact Framework this has been pared back to two: System.Drawing and System.Drawing.Design (plus some fragments from two other namespaces).
Table 15.1 summarizes the .NET namespaces supported in the desktop .NET Framework, along with details of how these features are supported in the .NET Compact Framework. The System.Drawing namespace supports drawing on a device screen. A second namespace, System.Drawing.Design, helps when building a custom control. In particular, this namespace contains elements used to support design-time drawing of controls (i.e., drawing controls while they are being laid out inside the Designer). The elements of this namespace reside in the System.CF.Design.dll assembly, a different name from the assembly name used for the desktop. The change in the file name makes it clear that this file supports .NET Compact Framework programming.
Table 15.1. Desktop .NET Framework Drawing Namespaces in the .NET Compact Framework
On the surface, it would be easy to conclude that Microsoft gutted the desktop System.Drawing.dll library in creating the .NET Compact Framework edition. For one thing, the desktop version is a whopping 456K, while the compact version is a scant 38K. What's more, the desktop version supports 159 classes, while the compact version has a mere 17 classes. A more specific example of the difference between the desktop .NET Framework and the .NET Compact Frameworkfrom a drawing perspectiveis best appreciated by examining the Graphics class (a member of the System.Drawing namespace). The desktop .NET Framework version of this class supports 244 methods and 18 properties; the .NET Compact Framework version supports only 26 methods and 2 properties. By this accounting, it appears that the prognosis of "gutted" is correct. Yet, as any thinking person knows, looks can be deceiving.
To understand better the difference between the desktop .NET Framework and the .NET Compact Framework, we have to dig deeper into the Graphics class. To really see the differences between the desktop and compact versions, we must study the overloaded methods. If we do, we see that the desktop .NET Framework provides many overloaded methods for each drawing call, while the .NET Compact Framework provides far fewer. For example, the desktop .NET Framework provides six different ways to call DrawString (the text drawing function), while there is only one in the .NET Compact Framework. And there are 34 versions of DrawImage (the function for drawing a bitmap) but only four in the .NET Compact Framework.
We have, in short, fewer ways to draw objectsbut in general we can draw most of the same things with the .NET Compact Framework that we can draw on the desktop. This supports a central design goal of Windows CE, which is to be a small, compact operating system. Win32 programmers who have worked in Windows CE will recognize that a similar trimming has been done to define the Windows CE support for the Win32 API. Instead of calling this a "subset," we prefer to take a cue from the music recording industry and use the term "greatest hits." The .NET Compact Framework implementation of the System.Drawing namespace is, we believe, the greatest hits of the desktop System.Drawing namespace.
In comparing the desktop .NET Framework to the .NET Compact Framework, an interesting pattern emerges that involves floating-point numbers. In the desktop .NET Framework, most of the overloaded methods take floating-point coordinates. For all of the overloaded versions of the DrawString methods, you can only use floating-point coordinates. In the .NET Compact Framework, few drawing functions have floating-point parametersmost take either int32 or a Rectangle to specify drawing coordinates. A notable exception is the DrawString function, which never takes integer coordinates in the desktop .NET Framework; in the .NET Compact Framework, it is the sole drawing method that accepts floating-point values.
It is worth noting that the underlying drawing functions (both in the operating system and at the device driver level) exclusively use integer coordinates. The reason is more an accident of history than anything else. The Win32 API and its supporting operating systems trace their origins back to the late 1980s, when the majority of systems did not have built-in floating-point hardware. Such support is taken for granted today, which is no doubt why the .NET Framework has such rich support for floating-point values.
A fundamental part of any graphics software is the coordinate system used to specify the location of objects drawn on a drawing surface. The desktop .NET Framework supports seven distinct drawing coordinate systems in the GraphicsUnit enumeration. Among the supported coordinates systems are Pixel, Inch, and Millimeter. While the .NET Compact Framework supports this same enumeration, it has only one member: Pixel. This means that when you draw on a device screen, you are limited to using pixel coordinates. One exception involves fonts, whose height is always specified in Point units.
This brings up another difference between the desktop .NET Framework and the .NET Compact Framework: available coordinate transformations. The desktop provides a rich set of coordinate transformationsscrolling, scaling, and rotatingthrough the Matrix class and the 3 × 3 geometric transform provided in the System.Drawing.Drawing2D namespace. The .NET Compact Framework, by contrast, supports no coordinate mapping. That means that, on handheld devices, application software that wants to scale, scroll, or rotate must handle the arithmetic itself because neither the .NET Compact Framework nor the underlying operating system provides any coordinate transformation helpers. What the .NET Compact Framework provides, as far as coordinates go, is actually the same thing that the underlying Windows CE system provides: pixels, more pixels, and only pixels.
While it might be lean, the set of drawing services provided in the .NET Compact Framework is surprisingly complete. That is, almost anything you can draw with the desktop .NET Framework can be drawn with the .NET Compact Framework. The key difference between the two implementations is that the desktop provides a far wider array of tools and helpers for drawing. Programmers of the desktop .NET Framework are likely to have little trouble getting comfortable in the .NET Compact Framework, once they get used to the fact that there are far fewer features. But those same programmers are likely to be a bit frustrated when porting desktop .NET Framework code to the .NET Compact Framework world and are likely to have to rewrite and retrofit quite a few of their applications' drawing elements.
The Role of the Graphics Class
The most important class for creating graphical output is the Graphics [8] class. It is not the only class in the System.Drawing namespace, but only the Graphics class has drawing methods. This class holds methods like DrawString for drawing a string of text, DrawImage for displaying a bitmap onto the display screen, [9] and DrawRectangle for drawing the outline of a rectangle. Here is a list of the other classes in the System.Drawing namespace for the .NET Compact Framework:
Bitmap
Brush
Color
Font
FontFamily
Icon
Image
Pen
Region
SolidBrush
SystemColors
These other classes support objects that aid in the creation of graphical output, but none has any methods that actually cause graphical output to appear anywhere. So while you are going to need these other classes and will use these other classes, they play a secondary role to the primary graphical output class in the .NET Compact Framework: Graphics.
Drawing Support for Text Output
Table 15.2 summarizes the methods of the Graphics class that support text drawing. The DrawString method draws text, while the MeasureString method calculates the bounding box of a text string. This calculation is needed because graphical output involves putting different types of graphical objects on a sea of pixels. When dealing with a lot of text, it is important to measure the size of each textbox to make sure that the spacing matches the spacing as defined by the font designer. Failure to use proper spacing creates a poor result. In the worst cases, it makes the output of your program unattractive to users. Even if a user does not immediately notice minor spacing problems, the human eye is very finicky about what text it considers acceptable. Poor spacing makes text harder to read because readers must strain their eyes to read the text. Properly spaced text makes readersand their eyeshappier than poorly spaced text does.
Table 15.2. System.Drawing.Graphics Methods for Text Drawing
Drawing Support for Raster Output
Table 15.3 summarizes the methods of the Graphics class that draw raster data. We define raster graphics as those functions that operate on an array of pixels. Two of the listed functions copy an icon (DrawIcon) or a bitmap (DrawImage) to a drawing surface. The other two methods fill a rectangular area with the color of an indicated brush. We discuss the details of creating and drawing with bitmaps later in this chapter.
Table 15.3. System.Drawing.Graphics Methods for Raster Drawing
Drawing Support for Vector Output
Table 15.4 summarizes the seven methods in the Graphics class that draw vector Graphics objects in the .NET Compact Framework. There are substantially fewer supported vector methods than in the desktop .NET Framework. The vector methods whose names start with Draw draw lines. The vector methods whose names start with Fill fill areas. | http://www.informit.com/articles/article.aspx?p=349039&seqNum=2 | CC-MAIN-2017-09 | refinedweb | 3,953 | 57.27 |
Difference between revisions of "Data Validation (Code Review)"
Latest revision as of 07:28, 2 January 2007OWASP Code Review Guide Table of Contents
Contact author: Eoin Keary
One key area in web application security is the validation of data inputted from an external source. Many application exploits a derived from weak input validation on behalf of the application. Weak data validation gives the attacked the opportunity to make the application perform some functionality which it is not meant to do.
Canonicalization of input.
Input can be encoded to a format that can still be interpreted correctly by the application but may not be an obvious avenue of attack.
The encoding of ASCII to Unicode is another method of bypassing input validation. Applications rarely test for Unicode exploits and hence provides the attacker a route of attack.
The issue to remember here is that the application is safe if Unicode representation or other malformed representation is input. The application responds correctly and recognises all possible representations of invalid characters.
Example:
The ASCII: <script>
(If we simply block “<” and “>” characters the other representations below shall pass data validation and execute).
URL encoded: %3C%73%63%72%69%70%74%3E
Unicode Encoded: <script>
The OWASP Guide 2.1 delves much more into this subject.
Data validation strategy
A general rule is to accept only “Known Good” characters, i.e. the characters that are to be expected. If this cannot be done the next strongest strategy is “Known bad”, where we reject all known bad characters. The issue with this is that today’s known bad list may expand tomorrow as new technologies are added to the enterprise infrastructure.
There are a number of models to think about when designing a data validation strategy, which are listed from the strongest to the weakest as follows.
- Exact Match (Constrain)
- Known Good (Accept)
- Reject Known bad (Reject)
- Encode Known bad (Sanitise)
In addition there must be a check for maximum length of any input received from an external source, such as a downstream service/computer or a user at a web browser.
Rejected Data must not be persisted to the data store unless it is sanitised. This is a common mistake to log erroneous data but that may be what the attacker wishes your application to do.
- Exact Match: (preferred method) Only accept values from a finite list of known values.
E.g.: A Radio button component on a Web page has 3 settings (A, B, C). Only one of those three settings must be accepted (A or B or C). Any other value must be rejected.
- Known Good: If we do not have a finite list of all the possible values that can be entered into the system we uses known good approach.
E.g.: an email address, we know it shall contain one and only one @. It may also have one or more full stops “.”. The rest of the information can be anything from [a-z] or [A-Z] or [0-9] and some other characters such as “_ “or “–“, so we let these ranges in and define a maximum length for the address.
- Reject Known bad: We have a list of known bad values we do not wish to be entered into the system. This occurs on free form text areas and areas where a user may write a note. The weakness of this model is that today known bad may not be sufficient for tomorrow.
- Encode Known Bad: This is the weakest approach. This approach accepts all input but HTML encodes any characters within a certain character range. HTML encoding is done so if the input needs to be redisplayed the browser shall not interpret the text as script, but the text looks the same as what the user originally typed.
HTML-encoding and URL-encoding user input when writing back to the client. In this case, the assumption is that no input is treated as HTML and all output is written back in a protected form. This is sanitisation in action.
Good Patterns for Data validation
Data Validation examples
A good example of a pattern for data validation to prevent OS injection in PHP applications would be as follows:
$string = preg_replace("/[^a-zA-Z0-9]/", "", $string);
This code above would replace any non alphanumeric characters with “”. preg_grep() could also be used for a True or False result. This would enable us to let “only known good” characters into the application.
Using regular expressions is a common method of restricting input character types. A common mistake in the development of regular expressions is not escaping characters, which are interpreted as control characters, or not validating all avenues of input.
Examples of regular expression are as follows:
^[a-zA-Z]$ Alpha characters only, a to z and A to Z (RegEx is case sensitive). ^[0-9]$ Numeric only (0 to 9). [abcde] Matches any single character specified in set [^abcde] Matches any single character not specified in set
Framework Example:(Struts 1.2)
In the J2EE world the struts framework (1.1) contains a utility called the commons validator. This enables us to do two things.
- Enables us to have a central area for data validation.
- Provides us with a data validation framework.
What to look for when examining struts is as follows:
The struts-config.xml file must contain the following:
<plug-in <set-property </plug-in>
This tells the framework to load the validator plug-in. It also loads the property files defined by the comma-separated list. By default a developer would add regular expressions for the defined fields in the validation.xml file.
Next we look at the form beans for the application. In struts, form beans are on the server side and encapsulate the information sent to the application via a HTTP form. We can have concrete form beans (built in code by developers) or dynamic form beans. Here is a concrete bean below:
package com.pcs.necronomicon import org.apache.struts.validator.ValidatorForm; public class LogonForm extends ValidatorForm { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
Note the LoginForm extends the ValidatorForm, this is a must as the parent class (ValidatorForm) has a validate method which is called automatically and calls the rules defined in validation.xml
Now to be assured that this form bean is being called we look at the struts-config.xml file: It should have something like the following:
<form-beans> <form-bean </form-beans>
Next we look at the validation.xml file. It should contain something similar to the following:
<form-validation> <formset> <form name="logonForm"> <field property="username" depends="required"> <arg0 key="prompt.username"/> </field> </form> </formset> </form-validation>
Note the same name in the validation.xml, the struts-config.xml, this is an important relationship and is case sensitive.
The field “username” is also case sensitive and refers to the String username in the LoginForm class.
The “depends” directive dictates that the parameter is required. If this is blank the error defined in Application.properties. This configuration file contains error messages among other things. It is also a good place to look for information leakage issues:
- Error messages for Validator framework validations
errors.required={0} is required. errors.minlength={0} cannot be less than {1} characters. errors.maxlength={0} cannot be greater than {2} characters. errors.invalid={0} is invalid. errors.byte={0} must be a byte. errors.short={0} must be a short. errors.integer={0} must be an integer. errors.long={0} must be a long.0. errors.float={0} must be a float. errors.double={0} must be a double. errors.date={0} is not a date. errors.range={0} is not in the range {1} through {2}. errors.creditcard={0} is not a valid credit card number. errors.email={0} is an invalid e-mail address. prompt.username = User Name is required.
The error defined by arg0, prompt.username is displayed as an alert box by the struts framework to the user. The developer would need to take this a step further by validating the input via regular expression:
<field property="username" depends="required,mask"> <arg0 key="prompt.username"/> <var-name>mask ^[0-9a-zA-Z]*$ </var> </field> </form> </formset> </form-validation>
Here we have added the Mask directive, this specifies a variable . and a regular expression. Any input into the username field which has anything other than A to Z, a to z or 0 to 9 shall cause an error to be thrown. The most common issue with this type of development is either the developer forgetting to validate all fields or a complete form. The other thing to look for is incorrect regular expressions, so learn those RegEx’s kids!!!
We also need to check if the jsp pages have been linked up to the validation.xml finctionaltiy. This is done by <html:javascript> custom tag being included in the JSP as follows:
<html:javascript
Framework example:(.NET)
The ASP .NET framework contains a validator framework, which has made input validation easier and less error prone than in the past. The validation solution for .NET also has client and server side functionalty akin to Struts (J2EE). What is a validator? According to the Miscosoft .
The following is an example web page (.aspx) containing validation:
<html> <head> <title>Validate me baby!</title> </head> <body> <asp:ValidationSummary runat=server <form runat=server>
Please enter your User Id
<tr> <td> <asp:RequiredFieldValidator runat=server ControlToValidate=Name * </asp:RequiredFieldValidator> </td> <td>User ID:</td> <td><input type=text runat=server id=Name></td> <asp:RegularExpressionValidator runat=server display=dynamic </tr> <input type=submit runat=server id=SubmitMe value=Submit> </form> </body> </html>
Remember to check to regular expressions so they are sufficient to protect the application. The “runat” directive means this code is executed at the server prior to being sent to client. When this is displayed to a users browser the code is simply HTML.
Length Checking
Another issue to consider is input length validation. If the input is limited by length this reduces the size of the script that can be injected into the web app.
Many web applications use operating system features and external programs to perform their functions. When a web application passes information from an HTTP request through as part of an external request, it must be carefully data validated for content and min/max length. Without data validation the attacker can inject Meta characters, malicious commands, or command modifiers, masquerading, as legitimate information and the web application will blindly pass these on to the external system for execution.
Checking for minimum and maximum length is of paramount importance, even if the code base is not vulnerable to buffer overflow attacks.
If a logging mechanism is employed to log all data used in a particular transaction we need to ensure that the payload received is not so big that it may affect the logging mechanism. If the log file is sent a very large payload it may crash or if it is sent a very large payload repeatedly the hard disk of the app server may fill causing a denial of service. This type of attack can be used to recycle to log file, hence removing the audit trail. If string parsing is performed on the payload received by the application and an extremely large string is sent repeatedly to the application the CPU cycles used by the application to parse the payload may cause service degradation or even denial of service.. Remember: Data validation must be always done on the server side. A code review focuses on server side code. Any client side security code is not and cannot be considered security.
Data validation of parameter names:
When data is passed to a method of a web application via HTTP the payload is passed in a “key-value” pair such as UserId =3o1nk395y password=letMeIn123
Previously we talked about input validation of the payload (parameter value) being passed to the application. But we also may need to check that the parameter name (UserId,password from above) have not been tampered with. Invalid parameter names may cause the application to crash or act in an unexpected way. The best approach is “Exact Match” as mentioned previously.
Web services data validation
The recommended input validation technique for web services is to use a schema. A schema is a “map” of all the allowable values that each parameter can take for a given web service method. When a SOAP message is received by the web services handler the schema pertaining to the method being called is “run over” the message to validate the content of the soap message. There are two types of web service communication methods; XML-IN/XML-OUT and REST (Representational State Transfer). XML-IN/XML-OUT means that the request is in the form of a SOAP message and the reply is also SOAP. REST web services accept a URI request (Non XML) but return a XML reply. REST only supports a point-to-point solution wherein SOAP chain of communication may have multiple nodes prior to the final destination of the request. Validating REST web services input it the same as validating a GET request. Validating an XML request is best done with a schema.
<?xml version="1.0"?> <xsd:schema xmlns: <xsd:complexType <xsd:sequence> <xsd:element <xsd:element <xsd:element <xsd:element <xsd:element </xsd:sequence> </xsd:complexType> <xsd:simpleType <xsd:restriction <xsd:minLength <xsd:maxLength <xsd:pattern </xsd:restriction> </xsd:simpleType> <xsd:simpleType <xsd:restriction <xsd:minLength <xsd:maxLength <xsd:pattern </xsd:restriction> </xsd:simpleType> </xsd:schema>
Here we have a schema for an object called AddressIn. Each of the elements have restrictions applied to them and the restrictions (in red) define what valid characters can be inputted into each of the elements. What we need to look for is that each of the elements have a restriction applied to the as opposed to the simple type definition such as xsd:string. This schema also has the <xsd:sequence> tag applied to enforce the sequence of the data that is to be received. | https://www.owasp.org/index.php?title=Data_Validation_(Code_Review)&diff=14811&oldid=3789 | CC-MAIN-2014-10 | refinedweb | 2,372 | 55.44 |
Can this be done at all? I'm making a pseudo terminal and would like some highlighting on specific words if possible. I'm happy to apply a material to certain strings and add them to the text area rather than insert an entire string. Because of the complexities of doing this I only use one text area. I'd think multiple text areas would be out of the option.
Answer by brain56
·
Nov 15, 2013 at 09:02 AM
No, that is not possible with the default text rendering facilities Unity 3D currently provides.
What you can do is use different text objects to render each part of the string with a different material. But I'd also recommend you take a look at third party Unity plug-ins for text. I would recommend *Toolkit 2D* and *NGUI*.
I'm looking for a free option preferably as I'll not be making revenue with this. Can I append text objects and strings into the same text area? If so ill likely be able to make that work.
Answer by MrVerdoux
·
Nov 15, 2013 at 09:30 AM
I can only think of doing it by extending GUI methods to add a "sequential" GUI option or something like that, but in my opinion that is not a very good solution, only that I can´t think of anything else.
using UnityEngine;
using System;
using System.Drawing;
using System.Collections;
using System.Collections.Generic;
using System.Windows.Forms;
public static class GUIExtension{
public static void SequentialLabel(this GUI gui, Rect rect, List<StyledString> styledStrings){
float recorredWidth = 0;
for (int i=0; i<styledStrings.Count; i++){
Size stringSize = TextRenderer.MeasureText(styledStrings[i].text, styledStrings[i].style.Font.size);
GUI.Box(new Rect(rect.x + recorredWidth, rect.y, rect.width, rect.height),
styledStrings[i].text, styledStrings[i].style);
recorredWidth += stringSize.width;
}
}
}
public class StyledString{
public string text {get; private set;}
public GUIStyle style {get; private set;}
public StyledString(string text, GUIStyle style){
this.text = text;
this.style = style;
}
}
Note: I have a problem with autocompletion right now so probably the code needs fixing. Oh, and that is only for "one line" label, if you want more lines you will have to do a line end check.
Thanks I was unaware I could apply styles like that I'll see what I can come up with and post back. I'm not overly concerned about optimization or anything given the nature of the code.
The way to call it would be:
GUI.SequentialLabel(new Rect(left,top,width,height),myStringList);
But again, I´m not very sure this would work...
Are you able to confirm what package Size is in? I've added the Windows.Forms dll to my project but I'm still getting a namespace Error for Size. EDIT: It's in drawing....
It is in System.Drawing
EDIT: I didn´t see you edit, hah.
Get height of TextArea when wordwrap is enabled?
1
Answer
Accents work on windows but not in mac
1
Answer
Unity3d C# select statement for GUI.TextArea
1
Answer
Saving textarea to textfile on Android
0
Answers
How can I fix EditorGUILayout.TextArea not having word wrap?
1
Answer | https://answers.unity.com/questions/576064/apply-style-to-specific-string-in-text-area.html | CC-MAIN-2020-45 | refinedweb | 533 | 67.65 |
Red Hat Bugzilla – Bug 190962
/etc/mtab needs to be a symlink to /proc/mounts
Last modified: 2015-03-04 20:16:56 EST
Description of problem:
Use of the pam_namespace.so module can result in significant differences
between the /etc/mtab file reports and the state of the name-space posessed by
a user's session. If the administrator mounts or umounts a file system after
a user has logged in then /etc/mtab will be immediately updated but the actual
mount list that applies to the user will not change. This means that "df"
will produce incorrect and misleading answers.
If /etc/mtab is made a symlink to /proc/mounts then the "df" command (and
other programs that use /etc/mtab) will get the correct data that refers to
the session in question.
Also please note that pam_namespace.so provides greater benefits to non-SE
Linux users than it does to SE Linux users.
/etc/mtab and /proc/mounts don't contain identical data and different apps
work with them, so I don't think we can just merge them.
regards,
Florian La Roche | https://bugzilla.redhat.com/show_bug.cgi?id=190962 | CC-MAIN-2016-22 | refinedweb | 186 | 69.72 |
So here is my Generic Build Server System Tray Notifier. After unpacking the zip you have to create a startup script or link executing the jar that looks like
<path to java 6>\bin\javaw.exe -jar BuildServerSystemTray.jar <path to config>(Source is included in the zip.)
Configuration
The notifier is generic and needs a properties file. The zip contains sample configurations for Anthill OS 1.7, Cruise Control 2.3 and Hudson 1.2. You will have to customise the configuration. At least the build server URL (
server.url) has to be set accordingly. It should be easy to create configurations for other build servers, just set the proper value for the
status.patternproperty. This property defines a regular expression matching the whole information about a build containing the project name, success or failure and build time. The regex grouping values
status.name.group, status.value.groupand
status.date.groupmust be set accordingly.
Q: I was checking out the source, why is the package
at.kugelused as top level namespace instead of
org.codecop? A: Kugel was my coder pseudonym in the 80ties when I started coding for Commodore 64. I'm using it from time to time when I'm feeling retro. Kugel is German for ball or sphere. The name was coined by my first coding buddy because I was quite overweight.
3 comments:
There is a new version 1.3 of the notifier available. It contains configuration templates for Jenkins as well as support for HTTPS and basic authentication (as needed for CloudBees). Download it from Bitbucket.
Bitbucket changed their URLs, the link above might not work any more. The current download page is here.
Bitbucket shut down my Mercurial repositories :-( The current download page is here. | https://blog.code-cop.org/2009/01/build-server-tray.html?showComment=1579863531950 | CC-MAIN-2021-39 | refinedweb | 292 | 61.63 |
I have used this pogo pin
but it's not in stock any more.
Type: Posts; User: stephanschulz
I have used this pogo pin
but it's not in stock any more.
The Websocket library looks very promising.
I does mention it does not support "Sec-Websocket-Key".
Do you know if it is possible to add this option? I want to use an existing Websocket sever on...
Thanks Matthew for your advice via private message.
I think I got it working. I had to use SPI_MODE0 to make it work with teensy LC
//Teensy LC
//EMS22A encoder
#include <Arduino.h>...
Thanks for sharing.
I will try this with the AMT233A-V 12 bit encoder.
So far I have used tis code but have a feeling your might be more stable.
...
An update.
The AMT233A-V did not work with the mentioned code.
But since the AMT233A-V use SSI for communication I was able to use this example to get good reading:...
Thanks again for your input.
I will try a 2.0 teensy too.
Interesting to learn you used the AMT233 which uses SSI communication while the AMT203 used SPI. Aren't they different things?
I think...
yes I am using the Vin from the teensy to feed the encoder. Vin is 5 volts since it gets it from the USB power.
I am using the standard SPI pins
MISO 12
MOSI 11
CS 10
SCK 13
it's very...
Thanks for sharing. It's very much appreciated.
Sorry to ask more question, but it's not yet working for me.
Don't you have to do the 0xA5 and 0x10 stuff to query the sensor?
I only get this...
Hey ChrisBaron.
Do you mind posting your working code. I am working with the same encoder on a teensy 3.2 and have not had any luck.
Thank you.
it looks like I am able to make this board:
work with this library:...
Hello @MechanicalLumber
I am also hoping to use the MAXREFDES117 to read heart rates.
Did you by any chance Finnish your project and can share code on how to convert the data to BPMs?
I...
Thank you both for your valuable input.
For now I will unplug the touch sensor and see if the teensy still overheats at points.
But even went not doing touchRead() did it heat up to the point of...
I finally have physical access to the problem teensy / PCB setup.
To re-cap.
I am using PIN A8 as a capacity touch sensor. I have a 1.5 meter cable running to a 3D printed part that is covered in...
thanks pictographer.
I thought I already took care of most clamping via the constrain() function.
But I will look it over again.
In addition if move the touch code to processing to look for...
Thanks Paul for the quick reply.
I certainly agree that posting code help.
Right now I only have the full project which has too much meat around the edges....
I learned that the max touchRead value returned is 65535.
I am still not sure if it might also output -1 during an error; similar to the capacity touch library on the teensy site.
I did apply...
Hello
I have a few teensy 3.2 running in an exhibition and am using the touchRead to see if people are touching a pad.
The touch pad is connected to pin A8 and it's readings are send out over...
I am using attachInterrupt on a teensy 3.2.
Inside my interrupt function I need to know if the CHANGE was due to a pin going HIGH or LOW. Because inside the function then measure the time difference...
seems like this example works.
right now I am just shifting out the same 8 bit pattern to all 32 LED.
next test is to see how to...
I am on a teensy 3.2 and want to use the open drain function of the HV5523 (by Microchip) shift register.
The ShiftPWM library is for 8 bit data.
But the HV5523 has 32 output pins which means...
could it be as simple as not picking 96 MHz but rather 72 MHz for the CPU speed?
Hi.
I made a PCB layout with 12 daisy chained TLC5940 but all my different tests show that only 6 in a row work. As soon as i connect the other 6 i get random LED.
I added the 0.1uF and a 2.2K...
for OSC we pretty much followed these instructions:
the teensy reads the hall sensors directly via out custom BLDC driver. the driver has the 6...
Hello Gerrit.
My communication will be with the teensy over OSC via the wiz ethernet shield.
I can alter the speed but was hoping for constant control that allows for smooth - non-stutter motion....
Hello everyone.
I just started reading about PID control.
I am using a linear actuator with brushless DC motor that has 3 internal hall sensors through which i can count steps and ultimately...
this works perfectly. thanks
thanks a lot for this advice.
i will try it tomorrow morning.
i wonder if this has to do with the problem of usb disconnect described here:
I am running a simple USB keyboard example connected to a Mac computer with a teensy LC
The sketch works fine and characters are being typed.
But when i put the computer to sleep and try to use...
thank you for your efforts. it's much appreciated.
i followed your advice and connected an oscilloscope to one of the 3 AC outputs which are controlled by the WS2811.
the AC curve looks find to me, considering that i am not monitoring the zero...
My design already has LEDs on the AC side of the optocouplers and TRIAC. See LED7.
These LEDs do come on reliably and do not display the delay i see with the AC devices, even though they both get...
Thanks for your input.
I just tried adding a 0.1uF between the GND and VDD pins of the WS2811 IC but i still see the same delay.
Here is a short video of two "RGB pixels" being turned on one...
Hi Forum.
I am using the OctoWs2811 library on a teensy 3.1 with the Octo Adaptor to control 8 line of each 36 x WS2811 RGB drivers. I do not have LED strips but rather use the RGB-Driver IC.
I...
i see.
so if i follow this post for the teensy 3.0
Pin2 = D2 -> PortD
...
thanks for the reply.
I saw the NVIC_SET_PRIORITY but i did not know how to set it from within my sketch and how to set it for the right pin. in my case pin 2.
right now i am doing this:
...
it would be great if we could set the attachInterrupt priority.
As mentioned here my DMX signal on the RX pin is sometimes preventing an attachInterrupt read on Pin2.
A solution would be much...
I am using DmxReceiver successfully for a 20 channel DMX dimmer.
The same Teensy 3.1 is used to do AC Light Dimming but i see flicker once i a while in the lights.
There is no flicker if i command...
i too would be very interested in knowing if this can be made to work reliably.
i was planning on using the new teensy LC with the LIDAR Lite sensor.
i hope one of you finds a solution.
good...
here the LC is not yet listed:
i want to make sure i can use the LC, since it can not supply or handle 5v signals.
should i supply the cc3000...
we finished the project and these are my final design files:-
thanks to everyone for helping out.
finally had some more time to work on this.
i am now able to dim 22 channels.
but since i am using just one timer that gets called every...
this looks very interesting chris.
do you think you could also upload an example sketch to github for dmx send, receive and RDM?
thanks.
this happened many time to me too (broken teensy 3.1 + super hot), without being able to track down the exact problem source.
in my setup i provide 5v to the VIN pin via this OKAMI dc/dc...
ok.
just downloaded this newer version and it seems to have removed the flicker.
s.
Hi.
I my code has been successfully running using the great DmxReceiver.h library.
I supplied a DMX signal with the Enttec USB PRO interface. The dmx controlled LEDs faded nice and steady.
Now...
here is the code:
which is used for this artwork:
if anyone wants to take it to the next...
true. budget is spent. everything does work well, on my first proto PCB. but the next version (smaller) seemed to have introduced some noise on the data line and one of the screens sometimes has an...
i have 13 SPI device in total, one of which is an SD card, the others are these LCD buttons:
i wanted to see if a fast SPI bus...
i see. thanks for taking the time. | https://forum.pjrc.com/search.php?s=84ecf9aa8e822633be7f3698455d2e43&searchid=5176419 | CC-MAIN-2020-05 | refinedweb | 1,526 | 84.98 |
No. 30
FINANCING DEVELOPMENT
IN ISLAM
The Islamic Research and Training Institute was established by the Board of Executive Directors of
the Islamic Development Bank (IDB) in 1401H (1981). The Executive Directors thus implemented
Resolution NO.BG/14-99 which the Board of Governors of IDB adopted at its Third Annual Meeting held
on 10 Rabi Thani 1399H (14 March 1979). The Institute became operational in 1403H (1983).
Purpose
The purpose of the Institute is to undertake research for enabling the economic, financial and
banking activities in Muslim countries to conform to shari'ah, and to extend training facilities to
personnel engaged in economic development activities in the Bank's member countries.
Functions
(A) To organize and coordinate basic and applied research with a view to developing models and
methods for the application of Shari'ah in the field of economics, finance and banking;
(B) To provide for the training and development of professional personnel in Islamic Economics to
meet the needs of research and shari'ah-observing agencies;
(C) To train personnel engaged in development activities in the Bank's member countries;
(D) To establish an information center to collect, systematize and disseminate information in fields
related to its activities; and
(E) To undertake any other activities which may advance its purpose.
Organization
The President of the IDB is also the President of the Institute. The IDB's Board of Executive
Directors acts as its supreme policy- making body.
The Institute is headed by a Director responsible for its overall management and is selected by the
IDB President in consultation with the Board of Executive Directors. The Institute consists of three
technical divisions (Research, Training, Information) and one division of Administrative and Financial
Services.
Location
Address
Telephone: 6361400
Telex: 601407 - 601137
Cable: BANKISLAMI - JEDDAH
P.O. Box 9201
Jeddah 21413
Saudi Arabia
ISLAMIC RESEARCH AND TRAINING INSTITUTE
ISLAMIC DEVELOPMENT BANK
JEDDAH, SAUDI ARABIA
FINANCING DEVELOPMENT
IN ISLAM
Edited by
M. A. MANNAN
The views expressed in this book are not necessarily those of the Islamic
Research and Training Institute nor of the Islamic Development Bank.
References and citations are allowed but must be properly
acknowledged.
First Edition
1416H (19%)
Published by:
Foreword 9
Introduction 11
M. A. Mannan
5
Page
6
Page
Appendixes 415
7
FOREWORD
M. A. MANNAN'
* Senior Economist and former Head,. Special Assignment Unit of Islamic Research and
Training Institute (IRTI), Islamic Development Bank (IDB).
11
Towards Islamic Finance in Small Manufacturing Business in Saudi
Arabia, d) Some Considerations on the Size of the Public Sector in The
Islamic Republic of Iran, e) Efficiency of the Islamic Approach to
External Debt-Management in North Africa and Middle-East, 6) The
Survival and Development Strategies of the Minority of Nairobian
Muslims in Nairobi. The last section dealing with Financing
Development from Historical Perspectives consists of following four
papers : a) The Role of Finance in Development: The Ottoman
Experience, b) Public Borrowing in Early Islamic History: A Review of
the Records, c) Provision of Public Goods: Role of Voluntary Sector
(Waqf) in Islamic History and d) Relevance of the Ottoman Cash Waqfs
(Awqaf Al-Nuqud) For the Modern Islamic Economics.
12
between the surplus and deficit countries. In this context, the paper
discussed the role of the Islamic states and other relevant issues relating
to mobilization of domestic as well as external resources.
13
need for activating the rural Waqf and community services for financing
education, health etc.
14
tried to explore the role of Musharaka (participatory) finance and
Mudaraba finance. They tried to demonstrate that these two modes of
finance may not be fully adequate to finance small manufacturing
business in Saudi Arabia. While advocating for exploring other modes
of finance it is argued that these two modes of Islamic financing can
make significant contribution to small business finance. There is a
need to create an awareness among the existing investment agencies.
15
and made an attempt to derive its contemporary implications for
financing development. It is argued that Ottoman economy
discouraged credit and encouraged participatory financing and
financing social security services through patronage of private
foundations. It is argued that Ottoman administration followed
essentially export oriented policy.
16
dominant mode of endowment. The paper argued that cash waqf was
instrumental in transferring the savings of the well-to-do to those who
needed cash for financing various socio-economic activities. The author
argued that by combining the cash waqf with long term capital finance,
the problem of cash-waqf's perpetuity can be solved. It can also promote
participatory finance, free of interest.
17
imperative to meet the government deficit out of conventional tax and
non-tax revenues. In the process of creating secondary securities
markets for Islamic financial instruments, the central banks of the
Muslim countries can play a significant role. It is gratifying to note that
there is a growing recognition of Islamic modes of participatory
financing both in Muslim and Western countries. The historic decline of
rate of interest in almost all western countries such as USA, UK for
stimulating investment and growth (i.e., where bank interest rates, in
1993 is within the range of 3.5% to 4.5% in USA and UK, the lowest in
the last 20 years) provides further justifications for Islamic participatory
and custom-tailored financing program for alleviation of poverty in the
informal sector and economic progress in the Muslim countries. In this
context, the importance for reactivating the voluntary sector can hardly
be over-estimated.
18
Section I
ISLAMIC STRATEGIES
FOR FINANCING DEVELOPMENT
* Professor, Center for Research in Islamic Economics, King Abdulaziz University, Jeddah,
Saudi Arabia.
21
liquidation, debtors such as bondholders are paid first, followed by
preference shareholders who are paid the nominal value of their
shares. Ordinary shareholders receive what remains.
22
From the issuing company's point of view the advantage of financing
itself by preference shares is that they are a hybrid between bonds and
ordinary stocks.
23
3. ISLAMIC PREFERENCE SHARES: A PROPOSED FORMULA
24
In case of losses, Muslim jurists are unanimous that they must be
shared "normally", i.e., in strict proportion to each partner's capital.
There can be no preferential treatment in this case.
25
5. A NUMERICAL EXAMPLE
To illustrate, if profits in a given year were only $3.0 i.e., less than
the critical $5.0; then:
26
and ordinary shareholders would have got $12.0 (= 1.5+10.5 = 30
per cent of 5 + 70 per cent of 15).
TABLE
1 17 7.1 9.9
2 8 5.9 2.1
3 (-5) (-2.5) (-2.5)
4 9 6.2 2.8
5 22 10.1 11.9
6 21 9.8 11.2
7 (-10) (-5) (-5)
8 (-2) (-1) (-1)
9 18 8.9 9.1
10 14 7.7 6.3
11 10 6.5 3.5
12 (-4) (-2) (-2)
Arithmetic Mean (m) 8.17 4.3 3.86
Standard Deviation (s) 10.5 5.13 5.55
Coefficient of 1.29 1.19 1.44
Variation (s/m)
27
In the table, column (1) gives the earnings of the company for . a 12
year period. I assume that when earnings are positive, they are fully
distributed as dividends to all shareholders according to the ratios
mentioned earlier. Column (2) and (3) must add up to column (1)
(total profits), of course.
Let us compare the risk and return of total earnings for the full 12-
year period in column 1 of the table to the dividend streams of
preferred and ordinary shareholders in columns 2 and 3. Annual
earnings of the company averaged $8.17, out of which $4.3 or about
53 per cent were distributed as preferred dividends, and $3.86 or 47
per cent as ordinary dividends.
28
One cannot of course generalize from numerical examples.
Analytical treatment is needed to explore the general conditions under
which our suggested formula can achieve its objectives.
Why are preference shares much less popular than stocks or bonds in
Western countries? This can be explained by one fundamental reason.
It is that preference shares are a mix (hybrid) between stocks and
bonds; hence their main characteristic can be matched by a suitable
portfolio containing both stocks and bonds. The existence of preference
shares probably owes more to institutional or tax system peculiarities
than to basic functions not achievable without preference shares. This
leads me to believe that preference shares can play a useful role in an
Islamic interest-free economy where interest bearing bonds are
prohibited. In such a setting, Islamic preference shares can provide, for
any particular company, a financial instrument which is less risky than
its ordinary shares. It may thus appeal to those investors who would
like to sacrifice some return to achieve lower risk.
29
The proposed formula of Islamic preference shares would permit a
company to partially change its risk/return profile for a sub-group of
potential investors by offering them suitably designed Islamic
preference shares. It would add flexibility and desirable diversity to
other shari'ah approved modes of financing.
The two previous functions discussed in 6.1 and 6.2 are those usually
ascribed to conventional preference shares. Restating them is meant to
underscore the fact that proposed Islamic preference shares can
maintain these functions to a degree that is compatible with shari'ah.
30
7. CONTROLLING RISK IN. ISLAMIC PREFERENCE SHARES
7.1 Introduction
This suggested formula for Islamic preference shares changes the risk
measure of preference shareholders because it involves a variable
profit-sharing ratio.
31
view, as it treats "missed" dividends much like a debt on ordinary
shareholders.
32
Appendix
Answer to Question 11
This is the case where the term fixing a given sum of money is
expected to result in one of the parties being deprived of sharing the
profits; but if fixing the sum is not expected to result in such
deprivation, fixing the profits may be permissible. For example, if one
of the parties agrees to give the other LS.1000 over and above his share
in the profits, if the profits realized amount to LS.5,000, then the
remaining portion is to be divided equally between the two partners.
This is the rule as stated in the book called "El Bahr El Zakkar" as
follows: "If one of the parties asks for ten (pounds) if the profits exceed
that, then the stipulation is correct and binding and there is no reason to
consider it as voidable.."
33
profits is to be given to the bank's partner if the profits exceed a given
sum will not result in negating the fact that both parties will have a
common share in the profits. This is so because the partner will not
deserve the fixed sum except after sharing fifty-fifty with the bank out
of the fixed profits agreed.
REFERENCES
ENDNOTES
3. For more fiqh details see: Al-Khayyat, Vol. 2, pp. 222-24, and Al
Marzooqi, pp. 358-61.
34
6. Risk is often measured by the standard deviation (s) of an income
stream, and as such would be in the same units as the stream.
Relative risk is often measured by the coefficient of variation (s/m)
or the Standard Deviation divided by the arithmetic mean (m).
This measure of relative risk is adopted here because it is a pure
number that is directly comparable for different streams regardless
of units or time span.
35
2
FINANCING ECONOMIC DEVELOPMENT FROM
AN ISLAMIC PERSPECTIVE
HATEM EL-KARANSHAWY*
1. INTRODUCTION
37
In this working paper, we shall try to present a framework for a
mechanism that may enable the mobilization of the surplus available
in some Islamic countries which is currently utilized in international
capital markets in order to deal with some of the needs of deficit
countries on shari'ah based principles. Such a mechanism should
ensure the efficiency of utilization in these countries. Before going
into the basic principals of this mechanism, it is important, from our
view point to discuss three points which represent the framework
through which one can determine the finance gap and as such we can
work out ways and means to face how such a gap can be worked out.
The very concept of development itself represents the first point in
such a frame while the second point is the role of the state and its
responsibilities in Islamic jurisdiction. The third point discusses the
relation between the proper concepts and institutional framework in
Islam and the mobilization of domestic as well as external resources.
38
ensuring the power of the state in providing domestic as well as
external security in a general way i.e. economically, politically,
militarily and socially. Development in this way has a dynamic content
which means that it has to continue all the way through so mankind will
achieve increasing degrees of control over available resources.
Rationalization of resources utilization, as well as the fair distribution
of output, are the other commitments necessary to achieve ever
increasing levels of income and economic possibilities which keep
Islamic society in its proper place domestically and internationally as a
model and leading society. Needless to say, the achievement of the
development of such frames will require a set of mechanisms and
methods, some of which are linked directly to the question of financing
development. Others deal with the issues of production and distribution.
With respect to the question of finance, we would like to point out the
following:
2.2 The basic concept in the relation between man and the process of
full utilization of resources is the responsibility of both individual and
the state, whether these resources be capital, natural resource or even
the labor power of man himself as a factor of production. As a result of
this commitment, the gap between the available and utilized;the
attainable and actual, in all areas, including financial is substantially
reduced.
39
3. THE ROLE OF THE STATE AND ITS RESPONSIBILITIES IN
ISLAM
40
In the meantime, the government has to secure the proper
environment for the producer, investor and the consumer. Such an
environment would require prohibition of all types of illegitimate
activities, such as production of illegitimate goods and services,
prohibited monopolies, riba in all forms, quality control of all goods
and services, adherence to announced specifications. Pricing in such
cases might be needed and accepted by the jurists. This will also
extend to the commitment of the government to undertake direct
investment in areas where individuals is not able or willing to step in or
to run what is agreed upon to be part of the public domain. With these
concepts for the role of the state, the market plays an essential
function in the mobilization of resources, its allocation and distribution
of the production on the various factors of production according to
each factor and contribution in the production process. The word
market, in this case, covers factor markets, goods and services markets
as well as capital markets which are all controlled by the same
principals. The government, through its various organs, would accept
the responsibility of monitoring and control. Price and quality control
would be borne by Al Mohtasib; the monetary policy by the central
bank etc. These organs would step in when necessary to harmonize
action within these markets and between them.
41
finance on all transactions. As such, it gives implicit agreement to
borrowing with interest, since interest payment is treated as a cost
element. As such the effective cost of borrowing is reduced with as a
result of tax relief while the. return on profit sharing or risk sharing is
treated as part of profit. As such, it is taxed which increases its
effective cost on the institution at the business level. At the same time
this reduces the return to the financier. Needless to say, it is the
principal of Islamic countries to encourage Islamic financial concepts
that result from Islamic financial formats. The zakat system represents
what might be called the perfect tie balance for the economic
transaction cycle in Islam, not only because of its redistribution effects,
but also because of the effect on the production process and its effect
on the increase of supply of capital and its effects on the cost of finance
used as a base in investment decision making. All this directly affects
both the availability of finance and type of investment.
42
imports and exports of these developing countries. In our view, the
adoption of Islamic development concepts, the utilization of Islamic
forms and tools and the adherence to Islamic Market principles are
going to lead not only to reduction of the absolute size of the finance
gap but also to the structural uprooting of the discrepancies between the
estimation of the absorptive capacity and the misuse of available
finance domestically and external finance. Funds are more often than
not allocated to projects that do not produce direct or indirect returns
sufficient to carry the burden or cost of that finance.
43
system as to guarantee investors capital and returns in the project
itself rather than the government or the Central Bank commitment to
pay back the loan with' the due interest.
In short, it could be said that the size of the finance gap, ways to
face it deal with and the efficiency of utilization and the distribution of
the burden of such finance would differ substantially if Islamic
countries were to adopt development models and financing techniques
directly linked to proper Islamic concepts rather than the present
utilization of imported development models, methods and tools of
finance.
44
activities, the condition of diversification and attractivity would be
satisfied if these tools carried the following characteristics:,
b) It should vary in its nominal or face value and its maturity date as
such it would be capable of addressing various types of investors.
45
5.1 Direct Foreign Investment
46
imagine that in short or medium run, the private foreign investor would
be permitted to offer it for sale or close it down if its return is not
coping with the opportunity cost of the investment and so on. Such
infrastructure projects as well as other activities are badly needed in the
host countries and as a matter of fact considered as a pre-condition for
enhancing investment opportunities to attract local as well as foreign
investment. On the other hand, there are a number of advanced and
developing countries which enforce some limits on direct foreign
investments and control ownership or property rights in some
activities. This is linked to economic or political calculations and
balances that are difficult to change. All of the above recommendations
indicate the need for other forms of external flows together with direct
foreign investment. The following are some recommendations that
would, in our view, facilitate the flow of direct foreign investment to
the host countries. These recommendations could be divided between
measures to be taken at the level of host countries and others to be
taken on the multilateral or international level.
5.1.1 Measures to be taken at Host Countries Level
47
d) Legal restructuring of present laws - if needed - so as to recognize
the various formats of contracts that is proposed according to
shari'ah and determination of the legal position for parties to these
contracts.
5.1.2 Measures to be taken on Multilateral Level
48
examine its legitimacy even if it has some interest as a measure for
helping Moslems to avoid sinful dealing with interest.
As for common stocks, the subject has been studied in the number
of papers and conferences and the general agreement is that dealing
49
in them is legitimate whether buying or selling at market value as long
as the project concerned is adhering to shari'ah rules. What is needed to
encourage people to deal with this the establishment the proper
institutions, a subject that will be considered shortly.
As for the participation bonds that have a set maturity date a few
points may be raised:
50
spite of the actual contribution made with his money in achieving
these results. One exception that can be made is the special
reserves which may be directed to the enforcement of low expected
profits during the period of the bond and in this case it is be the
right of the bond holder to get his share in the reserve at maturity
but not before that. Second, the bond will be redeemed at a certain
value based on net worth of the activity at time of maturity. In this
case, the basis for calculating the periodic return will be net profit
i.e. after deducting various reserves. Of course this has to be done
after adjusting taxation laws so as to allow the return on bond to be
treated as a cost of finance on the borrowing company. The bond
holder is going to get his share in the increase or decrease in the
value of the bond. As a capital gains (or losses) at maturity date.
c) The bond might be a convertible one which means that it can turn
into equity right in the firm. In this case, the value of the bond
could be linked to a certain number of stocks based on their par
value. Alternatively, numbers of shares that can be acquired by the
bond could be determined on basis of market value of bonds and
shares at the time of taking the decision of conversions.
51
accounts. Returns over and above the guaranteed par value in local
currency may not mean much for external inventors in the light of
prevailing inflation and instable exchange rate in many Islamic
countries.
52
developmental projects - including public utilities - to income
generating activities where development bonds could be used to
generate at least part of the required finance.
On the other hand it is proposed that part - if not all - the surplus
that may be realized from the mutual insurance fund operations (to be
discussed shortly) should be channeled to the most needy Islamic
countries to finance development activities that will not generate
enough income to induce private inventors. The zakat fund, due on
investment profits in host countries, could also be directed for the
same proposed subject to the control of Islamic Organizations. zakat
funds however should be used to finance those projects and their
property right could be transferred to eligible poor and needy - in
accordance with what is agreed upon by shari'ah Jurists - These
include housing projects and small scale industries.
53
On the multilateral or international level specialized companies (S.C.)
preferably attached to the International Islamic Development Bank in
the beginning will undertake the marketing and promotional tasks for
various issues, check the studies and review the availability of domestic
finance if needed. These companies-will also undertake follow up,
auditing and ensure host countries and their companies adherence to
disclosure requirements. Such requirements should be designed in a
way that enable investors or their agents to carry out accurate, regular
economic valuations of the financed companies.
The S.C.'s can also play the role of the secondary markets until there
are sufficient and capable stock markets in Islamic countries. This role
will include the regular publication of information about prices,
dealings, supply and demand trends, etc. of listed securities.
54
Shari'ah control over the processes of issues, flotations, dealings, etc.
should be performed by an international independent authority with
appointed representatives in host countries. The authority would have
the right to review, examine and access to all documents deemed
necessary for performing its obligations. This body's expenses would
be financed from flotation or marketing commissions. As for the
collection of the zakat on investments and profits generated, it should
be collected either by independent Islamic organizations or Islamic
banks in the host countries previously mentioned.
6. MARKET REGULATIONS
Capital markets, like all other markets, are subject to the general
rules that characterize Islamic markets for goods, services or factors of
production. The application of these well known general rules in the
case of stock markets leads to a number of points that may be worth
emphasizing:
Stocks should not be sold for more that its par value before
invested money is transferred to productive assets.
Disclosure roles should secure enough flow of information to
establish the link between the financial asset value and real assets
productivity.
Margin trading should be prohibited.
55
special ledgers might be kept for that purpose pending final transfer of
title in the issuing companies. Dealers could also be permitted to
manage private portfolios with no need to disclose owner
identification.
SELECTED BIBLIOGRAPHY
56
6. Eiteman, D. Stonehill, A, Multinational Business Finance, 3rd ed.,
Addision-Wesley Publishing Company, Massachusetts, 1985.
7. OECD, Financial Market Trends, Paris, May, 1990.
8. Millard, B. J., Stocks and Shares Simplified, 2nd ed. John Willey and
Sons Ltd. Chichester, 1987.
57
3
THE ROLE OF EQUITY PARTICIPATION IN
FINANCING ECONOMIC DEVELOPMENT
RODNEY WILSON*
1. INTRODUCTION
Equity finance raises a- number of moral and ethical issues, which are
usually neglected by western finance specialists. As with other branches
of economics, it can be instructive to take account of such issues, rather
than merely rely on a positive approach. Equity financing can be
conducted in a very moral manner, and the principles of risk sharing and
cooperation through participation is certainly preferable to the conflict
of interest which often exists between borrower and lender in a debt
financing situation. Unfortunately, however, there are also negative and
morally objectionable factors. Equity markets. are renowned for
speculation and other undesirable behavior, especially in the thin and
volatile markets which are often found in the Third World countries.
Whether equity markets function in a just or unjust manner will clearly
depend on the motives and
59
behavior of the participants. It is to these behavioral issues that we must
now turn.
60
the question of responsibility over resources which are, most people
believe, ultimately provided on trust and not subject to absolute
individual ownership rights.4
Each of these forms of business organization has its merits, but the
most appropriate form will depend on the size and nature of the business
and the financial and economic environment in which it operates.
Partnerships are especially appropriate where businesses are small but
where is a need to bring in external risk capital. This may be due to the
limited resources of the concern itself, but where the owner wants to
avoid excessive reliance on debt finance. If a partnership is created then
trust will be needed on all sides. It usually involves a large commitment
for the participants, even for the so called "sleeping partners", whose
prime function is to provide finance rather than management.
Partnerships are difficult to terminate, and
61
there is limited flexibility in terms of bringing in new partners or
changing partners. Such developments involve the complete legal and
financial restructuring of the business.
Ordinary share issues are of course in many respects the best way
of raising risk capital, and the preferred option for large businesses
which can afford the expenses associated with going to market. The
main attraction is being able to tap a large capital market and raise
funds on much more favorable terms than is possible with bank
borrowing or private placements. Investors are satisfied with
62
anticipated dividends well below market rates of interest on loanable
funds, as their concern is at least as much in possible capital gains as
with the income yield.
63
Width and depth are therefore essential features for market maturity,
width referring to the range of companies quoted, and depth to the pool
of potential investors. In many developing countries banks and
investment companies are the main quoted shares on the stock
exchange, most industrial concerns either being within the state sector
or private family businesses. This limits the scope of the stock market,
and means that its use is very restricted as a vehicle for risk capital
financing.
It is far from easy task to get ordinary members of the general public
interested in stock market transactions rather than merely a rich elite.
One way of attracting interest may be through a privatization program,
be selling off previously state owned industries. Such sell-offs have
become increasingly popular in recent years, both as a means of raising
government revenue and freeing industry from the constraints of state
control. Ideologically it has been a way of encouraging "popular
capitalism".
64
safeguards; fixed interest bank deposits cannot give adequate protection
in real terms in the long run.7
There are three distinct categories of unit trust, capital growth funds,
income funds and balanced funds. Capital growth funds, as their name
implies, are designed to maximize the appreciation of the unit holders'
capital value over time, but are not primarily concerned with the return
on capital. Recovery funds are one example of a capital growth oriented
trust. Unit holders' funds are put into companies that are experiencing
financial difficulties, but are believed to have good future prospects
once they are rescued. This is of course a high risk strategy, as many of
the companies will not survive even after the capital injection. Those
that do recover often perform extremely well however, which can mean
a rapid rise in the value of these assets. It is this that brings the growth
in the value of the units,
65
despite the losses. The ability of unit trusts to have a wide spread of
assets means that losses are not catastrophic. Some failures are
inevitable, but portfolio diversification ensures a favorable outcome
overall.8
At first sight income unit trusts are much less attractive than time or
savings deposits with banks or building societies as the returns are
significantly lower. Investors usually contrast the initial income on the
units with the interest on bank deposits, and it is rare for the former to
be more than fifty per cent of the latter. With unit trusts it is always
necessary to take a long term view. The return in the first year
underestimates the long term benefits, especially as even with income
unit trusts the initial return will seldom cover the difference between
the buying and selling price, which makes the. units unattractive as
short term investments.
The scope for unit trusts is of course much greater in the context of
the developed stock markets found in the world's major financial
centers. Unit managers have a huge variety of quoted stock to select
from when making their portfolio choices, and there are no worries
about the tractability of stock. Responsibility for a particular trust's
66
performance rests with the unit manager and he or she cannot blame
imperfections in the market. The financial pores compile league tables
of the best and worst performing unit trusts in each category, and
these are published and avoided read by the investing public when
making their choices. Hitherto many investors used stock brokers
even when buying and selling unit trusts, and relied heavily on the
advice of these specialists. Increasingly the investing public has
become better educated and informed, and make their own purchases
directly, often by clipping press advertisements. By purchasing direct
discounts of the purchase price can be obtained, and there is no need to
pay brokerage fees.
67
groups offer Far Eastern funds, North American funds and even units
geared to particular markets such as Hong Kong or Singapore. Such
choices cannot be offered where there are foreign exchange controls that
impede the free mobility of capital internationally.
68
rewards can be considerable if a "winner" is backed. The risks are
almost like those in gambling, but the motivation is worthy, and it is not
merely unproductive wagering on the basis of chance.9
69
across a number of countries and sector to reduce risk. The trust would
hold a portion of its assets in liquid form both to provide security and
to ensure that funds were available to take advantage of favorable
opportunities as and when they arose. The liquid holdings would be
government securities rather than cash, so that returns could be earned
on all assets to increase the attractiveness of the trust to investors.
70
most interest to potential investors, assuming the company is easonably
regarded.
The main worry about equity finance for management is the fear of a
loss of business control. This could involve a take-over by a hostile
predator or a buy-out unfriendly interests that might ultimately plan to
install new management. The workforce might fear that their company
might be acquired by an asset stripper, interested only in the salable
value of the property and not the business itself. Such unwelcome
developments are a common occurrence in the stock markets of mature
industrial countries, indeed there are financiers who have made their
fortunes through such activity, to some extent at the expense of others.
71
In developing countries the financial markets have not usually reached
the stage of maturity where such actions would bring rewards. Asset
strippers are more likely to find easy pickings in the property market,
where their activities can be less easily identified, than in the higher
profile financial markets. There are few with the resources to mount
hostile take-overs, and interventionist governments, conscious of their
political constituencies, are less likely to sanction such activity.
Industrialists and company workers are likely to be part of a strong
urban political lobby, which governments see it in their interests to
protect. De-regulation does not mean a completely hands-off approach.
For this reason companies have less to fear from equity market
developments.
72
In practice business will always wish to strike a balance between
debt and equity financing, and this is where the concept of gearing is
important. Debt financing is appropriate for short term working capital
and trade finance. It oils the wheelless of any business undertaking.
For longer term finance of investment and capital expenditure, equity
financing is more appropriate. Such activity is sometimes financed by
taking short term loans and rolling them over so that they become
virtually indefinite lines of credit. Such an approach is not advisable, as
it is this that results in growing debt burdens. There may be times
when it is necessary to reschedule borrowing due to unforeseen
developments, but this should not be the intention at the outset when
the loan is contracted. Participatory finance, based on risk sharing, is
much more preferable for long term ventures, given the inevitable
uncertainties as the time period increases. Fixed commitments to loan
repayments on commercial terms over long periods are never
advisable, even at the international level, as the Third World debt
problems dramatically illustrated.10
10. CONCLUSIONS
There is a strong case for equity finance as s source for long term
investment funding on the practical level rather than reliance on bank
borrowing. Such finance, being participatory in nature, is also more
equitable, as risks are shared, rather than placing the entire burden on
the enterprise being financed.
73
units could be based on quoted stock, or on more direct participation
which would not necessarily involve securitization.
REFERENCES
74
4. Munawar Iqbal, Distributive Justice and Need Fulfillment in an
Islamic Economy, The Islamic Foundation, Leicester, 1986, p.12 if.
10. Rodney Wilson, "Third World Debt", in Adrian Darnell and Lynne
Evans, Contemporary Economics: A Teachers Update, Philip Allen,
Oxford, 1988, pp. 178-191.
75
Section II
M. FAHIM KHAN*
1. INTRODUCTION
* Head, Research Division, Islamic Research and Training Institute (IRTI) of Islamic
Development Bank (IDB), Jeddah, Kingdom of Saudi Arabia. The views expressed are not
necessarily those of IRTI/IDB.
79
have a macro model where growth and development can be
manipulated through supply side.
2. THE MODEL
80
H= E+L
Where H is stock of economically active human resources,
E is that part of human resource that is active as
entrepreneurs 3 , i.e. working for (uncertain) profits,
L includes all those who are either working for someone
else for wages in a modern sector or are disguised
unemployed in the subsistence sector.
L has two types of labor (a) those employed in the modern sector (call
this labor as L1 and (b) those employed in subsistence or traditional
sector (call this labor as L2 ). Bulk of L2 is disguised unemployed in
the sense that their removal form the traditional sector is possible
without affecting the output of the traditional sector.
81
Since W is assured in the subsistence sector to all the population, the
human resources will take up entrepreneurial work only if it ensures a
certain minimum expected profit (P) for them. The reservation for
expected profits is a function of W.
P = F (W) (2)
82
The curve implies diminishing marginal output on investments as
more and .more funds are used by the same entrepreneur.
83
The entrepreneurial sector competes with the wage paid sector and
an equilibrium is simultaneously achieved in the wage paid labor
market and in the entrepreneurial labor market.
g
) Entrepreneurial sector serves a catalytic role. When it moves it
makes the other sector (the wage paid sector move) and hence the
entrepreneurial sector plays a catalytic role for growth in the
economy.
3: INVESTMENT DEMAND
84
The profits that the supplier of funds will expect to receive on his
investment may increase at a constant rate implying a constant expected
rate of return on his funds or it may increase at an increasing rate
because the risk may increase for the supplier of funds as he supplies
more and more funds to the same entrepreneur. There may be a limit
beyond which the supplier of funds may not be willing to supply the
funds irrespective of the expected profits. This limit may depend on
various factors including the human capital of the entrepreneur seeking
the funds.'
The expectations about the profits for the entrepreneur, as well as for
the supplier of funds from the investment in a potential enterprise, can
be shown together in the following diagram:
Ievel
Fig (2)
85
The entrepreneur will effectively demand that amount of investment
funds which leaves him the maximum expected profit after paying the
share of the supplier of funds. In the above diagram the effective
demand would be Io . At this level of investment, the enterprise is
expected to make a total profit Po out of which supplier of funds
expects to claim Q.. The ratio of Qo to Ro at Io os a o . This is an
optimum point for both the parties and becomes a basis for entering
into a mutual contract. The contract between the parties will then be
made to include the following:
The 'a' - value is agreed upon ex-ante and determines the planned
level of investment. The changes in `a' will affect the effective demand
of investment funds from the entrepreneur. The changes in `a' may
occur as a result of shifts in A or B or both.
86
Curve B may shift up and down depending on various factors such as
availability of more investible funds with the owners of funds,
improved credibility of the users of funds, reduced risks due to an
improved political and economic climate etc.
When `a' = 0 implies that the owner of funds supplies his funds to
the entrepreneur with no share in profit. This also implies that he will
also not share or bear any losses and the entrepreneur is obliged to
return the full amount at sometime in future. The possibility that the
owner of funds may supply their funds at a = 0 may occur due to
several reasons:
87
a) Expected profits are too low and risk of loss is considered too high
to be compensated by the share in the expected profits.
88
We assume large number of entrepreneurs and large number of
suppliers of funds. An entrepreneur chooses a supplier whose return-
risk preferences (Curve B) enable him to agree upon an optimum value
of 'a' yielding him maximum expected profit (P).
On the other hand, the available investment funds look for more
productive entrepreneurs so that they are able to claim more profit.
The most productive entrepreneur believed to be generating the highest
return (R) at all levels of investment would be chosen first. At this
stage, we may not distinguish between entrepreneur and enterprise. In
the presence of surplus stock of human resources, we assume that each
entrepreneur represents a single enterprise. Hence, we need not
distinguish between profitability of an enterprise and productivity of
an entrepreneur. Competitive conditions can be assumed to ensure that
profitability of enterprises is equalized over all
89
enterprises in the economy. The investment funds market, thus, will
determine three things:
90
Equation (7) shows a negative relationship between `a' and Y. This
is an IS curve in our framework with positive slope.
6. MONEY DEMAND
Demand for real money balances will depend on the level of real
income and the expected return on financial assets.
L = bY (8A)
91
motivated by altruistic considerations in fact, will be a function of both
income (Y) and rate of return (0). While it will be positively related to
Y, it will be negatively related to Q. This part of the demand for
money for some cash for altruistic purposes can be written as:
A =a2Y-hQ (8B)
92
Hence, the demand for real money balances increases with the level of
real income and decreases with the expected rate of return on
financial assets. We can write demand for money function as:
LA = kY - haR
or LA =kY - h'a (9)
where h' = hR
Assuming a fixed money supply (M) and a constant price level (P)
implying fixed real money balances F we write money market
equilibrium as:
93
demand for liquidity that is motivated by profit-cum-altruistic
considerations.
The answer depends on whether 'h' can be zero i.e. whether demand
for money can be insensitive to changes in 'a'. (Equation for money
demand being M = kY - h'a). 'a' may cease to have any effect on
demand for money when Q (the expected rate of return for the owners
of the financial assets) is very low. At very low Q, the owners of
financial assets may not prefer to invest at positive 'a' as a matter
94
of risk aversion. Positive `a' means also the responsibility to bear the
losses. The low Q may not tempt the financial assets owner to bear the
responsibility of loss implied in this Q. On the other hand there is a cost
in holding money. The holders pay 1 on the amount held. In such a
situation where holders of money do not like to invest on a profit/loss
sharing basis and also want to avoid the penalty Z, they may prefer to
lend the money to those who need it. Money lent, in our framework,
does not share any profit and is liable to be returned in full at some
future date. This may also be referred to as investment with a = 0 (i.e.
neither earning any profits nor bearing any losses).
95
money as they can afford to pay Z on their money balances out of the Q
earned on the finances already invested. Hence the bulk of any
addition to the money supply at this stage may simply add up to the
money demand. The horizontal section of LAM curve is possible at
very high (close to unity) level of `a' values. Such a horizontal section
may not occur at a very low level of R may mean P to be less than P m
( a thousand point of entrepreneurial human resources to remain in
entrepreneurial jobs).
Y = Ao A1 a (12)
Or a = A A'Y (13)
96
b = Marginal propensity to consume
t = Rate of income tax
i = Responsiveness of effective demand of investment funds to the
profit ratio
97
iii) Any additional supply of financial assets in this situation does not
have to offer a lower Q to get themselves deployed with an
entrepreneur.
98
0
Fig. (5)
99
This is turn implies that there can be a horizontal section in the IS
curve in the initial stages of development when there is surplus stock
of human resources and return on investment in quite low.
LAM has been shown to be vertical for having a steep slope when 'a'
is very low and rates of return (Q and P) are also lower. In such
100
cases, fiscal policy will be ineffective whereas monetary policy will have
full impact on GNP. When returns (Q and P) are higher and `a' is also
closer to unity, the LAM curve has been shown to be flatter. The
monetary policy, in this case, will cease to be very effective and
government spending (preferably to help improve the productivity of
human resources) will produce more effective results on growth and
employment.
101
New entrepreneurs with new investment opportunities -are generated,
implying some absorption of the surplus labor from the subsistence
sector. The output and employment in the modern sector increases
without affecting the output of traditional sector because of the
presence of surplus labor.
The aggregate demand and hence output increases by the full effect
of the new investment. As more and more money is injected not does
only employment and output increase but the entrepreneurial
productivity improves through learning by doing and through the
competition that newly entered entrepreneurs pose to the existing
entrepreneurs. In the process R improves. This is in turn raises Q as
well as P. This means demand for money goes down. The IS curve
becomes horizontal at a higher level of `a'. The above process
continues with IS curve shifting in horizontal jumps till all surplus
labor is absorbed. Now R is at a higher level than that from we started
and there is no surplus so that `a' has to be reduced to attract human
resources to employ additional supply of investible resources. But
reduced `a' will also affect money demand. A choice has to be made
between monetary policy and fiscal policy depending on which of the
two will be more powerful given various parameters. R keeps on
improving till we reach a stage where IS curve becomes vertical.
Monetary policy loses its significance. Fiscal policy becomes
important. Now it is time for government to take up big development
projects of its own. This will further increase R forcing `a' to come
down and once again, we are on a downward sloping IS and an upward
sloping LAM. The process continues till a stage comes where the
government's role ends up in the economy and self sustaining growth
may take place.
102
limited due to illiteracy or due to extremely bad infrastructure (absence
of roads etc) or extreme political instability etc.
ENDNOTES
REFERENCES
103
4. Ausaf Ahmad, Income Determination in an Islamic Economy,
Scientific Publishing Center, King Abdulaziz University, Jeddah,
1987.
Appendix
Y = F (K,L) (1)
Since labor and capital are sharing the income of the project and
hence do not impose fixed costs, this production function also
represents net income function for the project.
104
Assuming that the entrepreneur is the only labor in the project and
hence the labor component is faked we can write the production
function as:
Y = F (K) (2)
Fig. (1)
. On the other hand the provider of capital expects to receive 'a certain
return on his capital. The expected return, of course, will be directly
related with the total amount he invests. In the very simplest form, this
relationship can be linear relationship of the type:
C = rK (3)
105
of capital cannot demand Y. It can only fix a share in the income or
profit of the project.
Let this share be called 'a'. Since income, i. e. 'y' is not fixed and
varies at different levels, of K, therefore, the profit-sharing ratio
becomes a function of the amount of capital.
This equation shows, that profit-sharing ratio will vary as more and
more capital is invested because C is increasing at a constant rate and
Y is increasing at a declining rate.
Y,C
Fig. (2)
106
Two things are clear from Fig (2).
Hence, the assertion* September 11, 1931 that under the profit-
sharing system there will be infinite demand for capital is not valid per
se.
* Several scholars make the assertion that profit-sharing system would mean infinitely elastic
demand for investment.
107
spread his investment among different. enterprises unless an
entrepreneur is willing to offer a higher than 'r' return - higher enough
to compensate the risk of putting more capital in one enterprise.
C=g(K) (4)
R=Y -C
R =F(K)-g(K)
F'(K)=g'(K)
Y,C
Ko
Fig. (3)
108
5
CAUSES OF FISCAL PROBLEMS IN MUSLIM
COUNTRIES AND SOME SUGGESTIONS FOR REFORM
MUNAWAR IQBAL*
1. INTRODUCTION
* Islamic Research and Training Institute (IRTI) of the Islamic Development Bank (IDB),
Jeddah, Kingdom of Saudi Arabia.
109
a result, many Muslim countries. are on the verge of bankruptcy and
are constrained to tow their "donors" line both in economic and
political policies.
What is even more disturbing is the fact that in spite of huge public
sector allocations financed through borrowing, most of these countries
have not been able to build viable physical and human infrastructures. It
is painful to note that a majority of the population in these countries is
living in slums or undeveloped rural areas without even. safe drinking
water, not to speak of electricity, sewerage or other civic facilities. The
rates of literacy are extremely low; health facilities are severely
deficient; housing problems are very serious and transport facilities are
extremely limited. Even after decades of high spending, most of these
countries have not been able to develop good railroad facilities, good
roads, good schools, adequate health care, sufficient energy for
industrial and domestic requirements, adequate irrigation facilities and
similar economic and social infrastructure. Where has all that money
gone? What went wrong? How serious is the problem? These are some
of the questions that will be addressed in this paper. In section two, we
present the long run trends on the state of public finance in Pakistan as
a case study. We have tried to highlight the aspects which may be
similar to those found in other Muslim countries. In section three an
attempt has been made to identify the reasons that have led to present
fiscal problems. In section four we present some reform proposals with
the hope that these will provide a basis for discussion and dialogue
which may lead to the formulation of some guidelines for a viable
strategy for fiscal reform in Muslim countries in the light of Islamic
teachings. Section five summarizes the main findings of the paper and
presents the main conclusions.
110
TABLE 1
111
2. ANALYSIS OF THE TRENDS OF PUBLIC FINANCE IN
PAKISTAN.
112
On the revenue side of the government budget, we notice that the
tax revenues have stagnated at around 13 per cent of GDP. Within the
total tax revenue, indirect taxes account for 87 per cent while the share
of direct taxes is only 13 per cent. Since, the incidence of indirect
taxes on the poor is relatively higher as compared to direct taxes, this
feature renders the tax structure inequitable. Moreover, both in direct
and indirect taxes, the base is very small and the tax rates are rather
high. For example, in a population of 113 million, the number of people
assessed for tax is only about 1.5 million and among them also the
upper 5 percent pay 96 percent of total income tax collected.
Similarly, in the case of customs duties, more than 50 percent of
imports are exempted while rest of imports are taxed at very high rates.
In case of excise duties, narrowness of the base is even
TABLE 2
(Rupees in Millions)
1979-80 1983-84 1984-85 1985-86 1986-87 1987-88 1988-89 1989-90
(P.A.) (R-E-)
Current Expenditure' 32,324 71,945 83,769 94,686 116,242 133,645 153,066 163,733
Defence 12,655 26,798 31,866 35,606 41,335 47,015 51,053 57,926
Interest 5,070 14,128 16,529 16,734 23,955 33,238 38,132 45,291
Current Subsidies 3,821 4,668 5,368 5,368 5,809 7,950 13,277 11,037
Gen. Administration 3,011 5,955 6,560 7,379 10,393 8,542 10,192 10,277
Social Services 3,979 9,815 10,485 12,375 15,452 17,325 19,304 19,657
All Others 4,288 10,581 12,969 13,886 19,298 19,575 21,108 19,545
Development Expenditure 21,805 28,057 33,050 39,777 36,160 46,728 48,110 55,000
Total Expenditure 54,629 100,002 116,819 134,463 152,402 180,373 201,176 218,733
As percent of Total
Expenditure
113
1979-80 1983- 1984- 1985-86 1986- 1987-88 1988-89 1989-90
84 85 87 (P.A.) (R.E.)
Current Expenditure 60.1 72.0 71.7 70.1 76.4 74.1 76.1 74.9
Defence 23.2 26.3 27.3 26.5 27.1 26.1 25.4 26.5
114
total public debt, the domestic debt has increased at a much faster rate
than foreign debt with the result that its share in total public debt has
increased from-42 percent in 1980/81 to 55 percent in 1988/89.
TABLE 3
Besides the high rate of growth, domestic borrowing has also become
increasingly costly. This has resulted in rising interest payments on
domestic debt. The government is offering increasingly higher rates to
attract domestic savings. It should also be pointed out here that the
higher rates of return on government schemes have not led to additional
resource mobilization. They have only displaced
115
private sector deposits. This can be easily verified by the ratio of
private savings to GNP which has not shown any upward trend. It has
hovered around an average of 10 percent.
The reasons that led many Muslim countries into serious fiscal
problems may vary from one country to another. However, there are
some factors which may be common to many countries. Identification
of the exact causes of the problems is essential before any reform is
contemplated. In this section we discuss some of the more common
reasons for fiscal deficits. Though we are guided by the experience of
116
Pakistan, many of these reasons may be present in other Muslim
countries as well.
The period starting from early 1940's and stretching well into 1970' s
was in general dominated by big government philosophy all over the
world. Previously the only rationale for the involvement of public
finance authorities in the production of goods and services had been the
provision of public goods such as defense, law and order, justice etc.
These goods and services have certain technical characteristics
(indivisibility, jointness of production etc.) which make their provision
by the private sector undesirable or unprofitable. Since the society
needs these goods, they had to be produced by the public sector. In late
1930's John Maynard Keynes popularized the idea that government
could play a more active role in stabilization and growth through
management of aggregate demand. Under the Keynesian influence these
two functions i.e. stabilization and growth also became necessary
components of public sector objectives. Around the same period,
governments started realizing that market forces left to themselves, may
not produce the distribution of income desired by the society. Partly due
to rising levels of unemployment and income inequalities and partly as a
reaction to communist philosophy, governments started taking upon
themselves the responsibility of supporting the unemployed, the
disabled, the old and the very young.
117
theories were based did not prevail in their economies. (The recent
theoretical developments have shown that they do not prevail even in
the developed countries).
118
TABLE 4
119
The reason that public debt has led to fiscal problems is that almost
all of this debt is on fixed interest basis. While borrowing this money,
there has been little consideration of the rates of return on these funds.
A general, obvious and simple rule which is easily forgotten is that no
public spending financed by borrowing should be carried out unless
the expected rate . of return on it at least equals, and is preferably
higher than, the cost of obtaining the resources. This is' one of the evils
of interest-based borrowing. The costs of servicing the borrowed
capital have been higher than the rate of return on investments carried
out with those funds. And even that is on the generous assumption that
these loans were used for investment. In fact, a good part of these
loans was used to finance extravagant government consumption. This
again is due to the fact that under interest based financing, the financier
has little interest in the way the funds are utilized as long as the
borrower does not default. These inherent problems of interest-based
borrowing are now widely recognized and a number of reform
proposals are being discussed.
The third major reason for fiscal deficit in Muslim countries has
been huge expenditure on defense. In Pakistan, it is the largest item of
government expenditure and constitutes more than 30% of total
government expenditure. There are a number of other Muslim
countries where defense has taken 25% or more of total government
expenditure. Since defense expenditure does not lead to a
corresponding physical output, it creates a huge burden on government
exchequer. Because of its crucial importance, however, it cannot be
ignored by any government. Many countries find themselves in
extremely sensitive circumstances which call for sizable defense
outlays. Unfortunately, most governments have neither been able to
execute the defense policies efficiently which could have saved a
120
considerable amount of money, nor have been able to motivate their
populations to render necessary sacrifice that their situation demand.
121
significant margin. (See Table 6). Inelasticity of tax revenue is a result of
narrow tax bases.
122
TABLE 5
Burkina Exp 13.8 15.99 1624 15.4 17.5 13.8 166 13.4 15.4 1.7 NA
Faso Rev 14.5 13.5 15.6 14.1 15.1 14.1 14.1 15.1 15.7 17.6 NA
Egypt Exp 4242 443 NA 46.0 55.5 45.1 46.7 43.7 45.9 41.1 NA
Rev 3&4 37.0 NA 47.1 46.5 44.2 43.2 4&0 40.1 2&1 NA
Indonesia Exp 19.4 20.6 223 24.1 20.8 21.2 1&9 21.9 24.7 NA NA
Rev 17.5 19.9 21.4 23.2 19.6 20.1 20.0 21.4 20.2 NA NA
Jordan gap 4&8 59.8 49.6 469 47.8 46.1 40.5 44.1 421 468 NA
Rcv 23.6 23.4 21.8 25.1 261 265 262 25.7 2&7 27.4 NA
Malaysia Exp 25.2 222 28.5 3&4 361 31.1 27.6 NA 34.4 29.0 NA
Rev 23.2 225 264 27.5 266 26.6 25.8 269 27.7 227 23.8
Mali Exp 1&0 17.4 244 228 27.9 30.7 30.7 349 27.8 27.8 NA
Rev 15.2 126 125 11.5 128 12.9 14.1 16.8 15.7 15.7 NA
Morocco Exp 34.4 34.9 349 40.3 3&6 33.9 3.9 33.0 333 30.3 NA
Rev 242 255 24.9 266 27.1 25.9 25.5 25.3 24.5 25.4 NA
Pakistan 17.5 1&6 17.5 19.2 17.2 19.4 19.6 19.4 21.9 21.0 20.7
Rev 14.3 15.1 163 164 15.7 15.9 169 15.8 16.4 16.3 17.1
Tunisia Ep 34.0 33.8 31.8 32.5 37.8 39.0 39.1 32.0 38.8 35.2 NA
Rev 31.4 320 31.6 31.9 343 33.6 365 33.7 34.5 31.5 NA
Turkey Exp 23.1 24.1 23.9 226 NA 242 24.9 25.0 21.11 21.9 213
Rev 20.5 19.7 20.l 21.3 NA 20.0 14.9 17.6 1&0 17.9 17.5
123
TABLE 6
Source: Computed from data given in World Development Report 1990 and
Government Finance Yearbook 1989.
124
3.5 Tax Evasion
The problems of tax evasion are also common knowledge. These are
not easy to quantify, but their magnitude is generally believed to be
substantial. In the case of Pakistan, it was estimated that the tax evaded
was more than three times the amount of tax collected.* The major
reasons for tax evasion are multiplicity of exemptions on the one hand
and high tax rates on the other. Moreover, lack of clearly identifiable
and easily assessable tax bases has made tax evasion quite easy.
Any reform proposal must start with defining the proper role of
public sector. From a purely economic point of view, the experience of
three decades following World War II, which were characterized by
125
large public sector outlays, has shown that the big-government
philosophy has serious flaws. The growth of public spending was
justified on grounds that the government must promote economic
growth, sustain economic activity and bring about a better income
distribution. Yet the experience of many developed countries shows
that economies have not become more stable because of governmental
intervention; income distribution has not improved and the rate of
growth has not accelerated because of the larger government
involvement: Economic historians also state that the period between
1870 and 1913 was one of the most dynamic periods for the economies
of the modern world. The rate of growth was normally very high, and
must modern infrastructure such as railroads, roads and schools was
built. Yet the level of public spending was remarkably low. For
example, in France it was only about 10 percent of national income.
Similar percentages are found for the other countries (Tani, 1990).
These percentages raise doubts about the necessity for high levels of
public expenditure in promoting economic growth. In view of these
facts and the recent theoretical developments in the field of public
policy, more and more governments are now encouraging the private
sector, privatizing public enterprises and reducing regulations which
limit private sector activities.
126
4.2 Creating Earmarked Heads of Public Expenditure
127
be pointed out here that if applied properly, zakah should generate
between 2-3 percent of GNP [Zarqa, Anas, 1986].
1 We are not recommending imposition of all these taxes. These are some of the possibilities. Each of these taxes has its
merits and demerits. Detailed analysis of individual taxes is not possible in the paper.
2
See Zarqa (1986) for an excellent description of these schemes.
128
very different. Some of the changes which necessitate a fresh look on
the issue are the following:
129
pointed out here that while ensuring proper defense for the country, the
government should normally seek from the people whatever level of
sacrifice their defense requires.
After the proper size of standing and reserve forces has been worked
out and all possible measures to reduce expenditure without
compromise on having battle-ready forces have been taken, then
whatever expenditure seems necessary may be raised from the public
through taxation and voluntary contributions. It is against this
background that we are suggesting that a separate head of expenditure
for defense should be created. Under the joint pool system, while the
defense may get the necessary funds, other heads of expenditure
130
usually suffer. It is one at the cost of other. Ignoring other necessary
functions, especially the needs of the people, creates internal instability,
social tensions and public antipathy. In such circumstances, the very
objective of a defense build-up ensuring national and territorial
integrity, is jeopardized by "excessive" defense spending [Chapra, M.
U., 1988].
131
d) The share of "in the path of Allah" in zakah collections can also
be spent under this head, whenever needed.
132
provision by the government, i.e., public interest, was sacrificed. A
radically different approach for a number of items of expenditure under
this head need to be adopted. Some suggestion in this regard are given
below:
a) First and foremost, the role of the private and voluntary sectors,
especially the latter, has to be strengthened. Awqaf have historically
played a very important role in the provision of public goods in
Islamic societies. This role has to be rejuvenated.
133
4.5.1 Two "Unconventional" Sources for Financing" Public Goods
While we do not rule out any form of taxation that meets the
principles of justice, equity and ability to pay, we would like to draw
attention to two possible sources of financing for the provision of public
goods. Public goods we remember are goods and services from which
the community at large benefits. Interestingly, in a modern economy the
community as a whole also generates resources by using paper and
credit money as a medium of exchange. This is known as seigniorage.
This arises because of a joint-action by the community at large i.e.
accepting paper/credit money in settlement of mutual claims. Since the
community at large generates this, it seems most appropriate to use this
for the provision of goods and services for that community.
134
expenditure. In Muslim countries, this is most unfortunate. In addition
to the economic problems that this public debt is creating for these
countries, they are in violation of Islamic shari'ah. As a matter of fact a
number of their economic problems are a result of ignoring the
unequivocal prohibition of borrowing when interest is charged.
135
We would like to re-emphasize that there are a number of ways for the
government to fulfil national requirements and that for genuine needs
government can levy additional taxes also. If the circumstances of a nation
require additional sacrifice, people should be convinced of that and then
made to offer that sacrifice. It must be remembered that borrowing does
not eliminate the need for sacrifice. It only postpones it and increases its
magnitude.
136
sources and then meeting current expenditure out of the available
resources and transferring the residual to the development budget is
not correct. In our view, the two kinds of expenditure need to be
mobilized through distinctly separate approaches. For determining the
development needs the possibilities of a more active participation by
the private sector should be considered. Many public projects can be
undertaken on the basis of islamic Financing Techniques.
137
REFERENCES
70mn1 :a
138
6
IS EQUITY FINANCED BUDGET DEFICIT STABLE IN
AN INTEREST FREE ECONOMY?
M. AYNUL HASAN*
AND
AHMAD NA'EEM SIDDIQUI*
1. INTRODUCTION
Over the past decade, there has been a growing literature on Islamic
economics involving theoretical macroeconomic models [e.g., Al-Jarhi
(1983), Haque and Mirakhor (1987), Kahf (1985), A. Khan (1982), M.
Khan (1986), M. Khan and Mirakhor (1989), Mirakhor and Zaidi (1988),
Naqvi (1982) and Zarqa (1983)]. Indeed, most of these studies have
provided a better conceptual and analytical understanding of how a
banking system may operate in an Islamic economy. For instance, the
study by M. Khan (1986) has shown that the Islamic Banking Model,
based on equity participation,' may be dynamically more stable than the
traditional banking model with fixed interest rates. In particular, M.
Khan (1986, p.19) noted that the Islamic Banking Model may be 'better
suited to adjusting to shocks that result
139
in banking crises' because in such a model the shocks are 'immediately
absorbed by changes in the values of shares (deposits) held by the public
in the bank'. In another paper, M. Khan and A. Mirakhor (1989)
developed an IS-LM model of closed Islamic economy wherein they
have shown that monetary policy, using Mudaraba financing, may have a
positive impact on the growth rate of output of the economy. Their
results were reinforced by A. Mirakhor and I. Zaidi (1988) in an open-
economy version of that model.
140
non-interest bearing money. Government, however, can finance its
deficit through money creation or equity finance.
141
minimum standard of living for all citizens, and (g)
prevention of gross inequalities in income and wealth.
Having outlined the basic role of the state and the objectives of fiscal
policy in an Islamic society, the important question is how the state is
going to achieve these objectives. More specifically, how is the
government budget going to be financed or if the budget is not balanced,
then is deficit-financing permissible in an Islamic state? All these issues
will have important implications in constructing the government budget
constraint in the next section. Ziauddin Ahmad (1989: 15-16) has best
explained and clarified these questions. He writes:
142
on a PLS basis also and choose how much of the
government's equity to monetize through the usual kinds of
open market operations, with the only difference being the
nature of the securities being traded.
143
where the variables are defined as follows:
144
Equation (1) simply shows that the value of shares is equal to the
capitalized value of profits of the banks. As no capital gains and that
banks are not holding any reserves and additional net worth, equation
(1) can be thought of as bank's balance sheet with (aY/7r) as assets and
S as liabilities..
145
As mentioned earlier, the total government expenditure as
represented by equation (6) is divided into a welfare allocation and a
general allocation.6 Equation (7) shows the transfer payments or
welfare expenditures which are made from funds received through
zakah levy. It may, however, be noted that the welfare expenditure
[equation (7)] is exactly matched by the zakah collection. This is in
contrast with Ziauddin Ahmad's (1989) exposition of dual budget, who
has not ruled out the possibility of deficit in the welfare budget. The
allowance of financing such deficit from the general allocation may
diminish the important distinction between the welfare budget and the
general budget.' The term inside the bracket of-equation (7) represents
the total savings (the difference between disposable income and private
consumption). The total value of zakah fund is simply a fraction
(roughly 2.5%) of the total savings.8
146
Equation (11a) is obtained by substituting S from equation (1) into (8)
and then setting M equal to zero. On the other hand, by setting 1l equal
to zero in equation (8), we obtain the second dynamic budget constraint
[equation (11b)]. Thus the compact dynamic system in the case of equity
financing consists of equations (9), (10) and (11a) while for money
financing the dynamic model includes equations (9), (10) and (11b).
Before a meaningful investigation of the stationary (or long run)
multipliers of the system can be done, it is necessary to analyze the
dynamic stability of the model.
147
where
148
This 3x3 system has three roots . Thus the
necessary and sufficient conditions for stability require that both the
determinant (n) and trace should be negative while the sum of the
principle minors be positive. However,if one of these conditions is
violated unambiguously then the system would be necessarily unstable.
Analyzing these stability conditions in the context of our model, we get
149
these conditions carefully one may observe that the influence of terms
A , and A2 are crucial for stability and in both these terms the wealth
effect on consumption (C A> 0) is important. This leads us to make the
following proposition.
150
Figure 1
And when the prayer is ended, then disperse in the land and see
of Allah's bounty, and remember Allah much, that ye may be
successful. (62:10).
151
And when the prayer is ended, then disperse in the land and
see of Allah's bounty, and remember Allah much, that ye may
be successful. (62:10).
152
where all variables and parameters are as defined earlier. Since our
interest in this paper is on the expenditure multipliers, we have ignored
the other exogenous terms in equation (13). The long-run expenditure
multiplier with respect to income M is given below:
153
Given the parametric assumptions of the model, it is evident that
the dynamic system under money financing is necessarily stable. Our
results for an Islamic Economy, in this case, are consistent with the
traditional Keynesian type of macroeconomic model.
5. CONCLUSIONS
154
whether or not an equity (or shares) financed deficit is stable for an
Islamic economy. Most of the earlier studies based on fixed interest rate
system concluded that the bond financed budget deficit is necessarily
unstable. The implications of such a finding could be crucial, from the
policy point of view for the economies which use bond as an instrument
to finance the deficit. It has been argued that the policy makers in many
Western economies 'still hope that bond financed fiscal policy can be
used for growth and employment targets, with only transitory effects on
the national debt.' Scarth's (1979) research, however, found no strong
support for this hope.
Our study, based on a macro model broadly consistent with the tenets
of Islam, however, found that the equity financed deficit is not necessarily
unstable and fiscal policy measures may have positive effect on the
growth rate of the economy, provided there are strong wealth effects on
private consumption.
ENDNOTES
155
4. Zakah is a special tax on the individual ' s savings and wealth
which is then distributed to the poor citizens of the state. The
zakah rate varies between 2.5% and 20% depending upon the
type of assets held by the individual.
9. One can interpret the term (yS) as equity financing for the
following reason: y indicates the growth rate of the 93
proportion of shares held by the private individuals and when
this term is increased (because of legal authorization of the
central bank), it increases the share holdings of the private
individuals and reduces the share holdings of the government.
By virtue of this operation, the government is being able to
generate funds to finance its deficits. This operation can be
viewed as an open market operation in the traditional sense but
with one important difference being that unlike the bond, the
instrument- used in this operation does not have a fixed return.
156
REFERENCES
Al-Jarhi, Mabid Ali (1983): "A Monetary and Financial Structure for
an Interest-Free Economy", in Ziauddin Ahmad, Munawar Iqbal,
and M. Fahim Khan (ed.), Money and Banking in Islam, Islamabad:
Institute of Policy Studies, 69-87.'
Christ, Carl (1979): "On Fiscal and Monetary Policies and the
Government Budget Restraint, American Economic Review, Vol.69,
526-38.
157
Khan, M. Akram (1982): "Inflation and the Islamic Economy: A
Closed Economy Model", in Muhammad Ariff (ed.), Monetary and
Fiscal Economics of Islam, Jeddah: International Center for Research
in Islamic Economics.
Scarth, William (1979): 'Bond Financed Fiscal Policy and the Problem
of Instrument Instability,: Journal of Macroeconomics, Vol.1, 107-17.
158
Zarqa, Mohammad Anas (1983): "Stability in an Interest-Free
Islamic Economy: A Note", Pakistan Journal of Applied Economics,
Vol. 2, 181-88.
70=144-:a.88
159
Section III
161
7
THE BASIC NEEDS FULFILLMENT GUARANTEE IN
ISLAM AND A MEASURE OF ITS FINANCIAL
DIMENSION IN SELECTED MUSLIM COUNTRIES
ZUBAIR HASSAN*
AND
MOHAMMAD ARIF**
1. INTRODUCTION
163
linked, but which may also not infrequently be concurrent. To integrate
them together in a unified development program may be difficult and
challenging. Their net result, or individual impact, may not always or
entirely be welcome to the entrenched status quo ante interests. As a
consequence, political expediency may often feel hesitant to implement
a BNF program despite an initial enthusiasm to implement such a
program.
The scheme of this paper is as follows; section two deals with the
conceptual aspect of a BNF program from an Islamic viewpoint. Here we
shall give reasons for our reservations about an absolute concept
concerning basic needs5 , and shall argue that a relative measure is more
logical and helpful both for inter-temporal and inter-nation
comparisons. Such a measure is also more realistic and convenient for
analyzing the financial dimension of the program in various Muslim
countries.
164
selection is purposive and well spread across the globe. The countries
included have very diverse historical backgrounds, -natural resources,
population sizes and political systems, and are at' quite different
milestones on the road to economic development. Taken together, their
population is more than half a billion. This constitutes over 50% of all
Muslims in the world, and around 70% of those living in the Muslim
majority countries where, given the will, an Islamic version of a BNF
program can be put into operation.
The idea that the basic needs of all should be satisfied before the less
essential needs of a few are met has its origin in religious scriptures
including those of Islam.' The principle has won a very wide acceptance
(Streeten p. 8). However, the religious import of the idea which we shall
explain using the Islamic case as illustration, seems much different from
the restricted, somewhat technical, meaning it has assumed in the current
discussions on poverty, income distribution, and levels of living in the
area of development economics.8
From the viewpoint of Islam, and other religions too, the issue of the
spiritual poverty of the believers at present may not be less important
than the problem of the material deprivation which afflicts their vast
majority.9 Still, one can presumably separate the two for analytical
treatment with advantage, more so because the shari'ah sees an intimate
link between them. Promotion of the material well-being of the poor
through the BNF is expected to improve not only their
165
ethical performance but, depending on the content and range of the
program, of the rich as well.10
166
shari'ah fence around his notion of needs which he then terms as `basic'
to everyone in the society. In that, he tends to break the link - so
common in the secular literature - between the `basic needs' and the
concept of `poverty' marked on an income scale. Naturally, Siddiqui's
list becomes too broad and its focus shifts from the 'basic needs' to
unquantifiable Islamic living in oblivion of resource availability at the
micro or macro level.
Even though both Siddiqui and Ahmad mention explicitly the stage
of economic development and income level as factors affecting the
Islamic need fulfillment guarantee, the overall argument - its content,
drift and thrust - tends to lessen the relevance of these constraints in
each case.
167
have to be periodically spelled out in accordance with the level of
economic development reached (Hasan p. 40). This being so, one must
avoid the overdrawing of the `basic needs' list ignoring the operational
constraints, specially the financial ones, that delimit it.
168
The contents of the basket varied according to the dictates of the
local requirements, but the `needs' it was meant to fulfil were virtually
the same in each case. A money equivalent of the basket was then
defined as the `poverty line' and those having incomes below this
minimal were identified as the `poor' . 19 Inflation being a perpetual
feature of all modern economies, the money value of the basket can be
raised periodically to obtain its current equivalent.
169
"as this type of subjective poverty may increase one's unhappiness and
greed with an associated urge for exploitation of the less fortunate
people." (Mannan, p.308).2'
170
To begin with, take the case of food requirements. Recent literature
on the subject is full of controversies as to what constitutes malnutrition
or more importantly how to ascertain the 'relative' degrees of under-
nourishment. The empirical research conducted by individuals,
institutions and international organizations on the issue poses
perplexing interpretive problems.22 For, "we do not know how many
calories are needed for people to live their daily lives". 23 It is also not
settled if protein deficiency is a distinct problem from inadequacy of
calories in a diet, or if the removal of the latter would mitigate the
former as well, except in some exceptional situations.24 Nor is one sure
if calories requirement in the diet would be the same for people engaged
in different kinds of activities requiring relatively more (or less)
energy.25 It is not only the difficulties of definition, the non-availability
of the relevant data complicates the problem further.
Since all stomachs are of almost the same size the difference in the
diet intakes of the rich and the poor is expected to be of a limited
nature,28 and one may probably stretch for an `absolute' view of the
requirement. But that cannot clearly be the case with the other basic
needs. For example, the size and quality of a shelter, and the range and
level of the accompanying services relating to water, electricity,
sewerage, transportation etc; can only be thought of meaningfully in
`relative' terms. Provision of education and medical services - their
quantum, type and standard - is all the more difficult to conceive of on an
absolute basis. In any case, when we aggregate all the basic needs,
171
as we must, using a money measure, we are but transported to the
realm of poverty indicated on an income scale. And poverty in this
sense cannot be divided, as argued, into `relative' and `absolute'
components.
Third and the last, the relative view, of course, defines poverty in
such a way that it can never be eliminated, however much the absolute
levels of income rise .30 But what is alarming about that? Which
society, and at what point in time has been, or presently is, without its
poor or free of a perception of poverty? Not even the most affluent
ones can claim to be entirely devoid of the malady. And why should
not an electric hare be used to spur on the greyhounds of public
concern if that would make them run on road to social welfare towards
an ever distancing destination? Islamic economics with a special focus
on distributive equity would presumably welcome such a built-in spur.
(Compare Streeten P.20).
3. FINANCIAL DIMENSION
The merit of the basic needs concept is that it takes us from the
general to the specific and focuses attention directly on the sore point of
destitution in society. But the decomposition of the underlying
172
poverty notion into the `absolute' and `relative' parts is entirely
capricious. There rarely is a way of defining the appropriate standards
of nutrition, shelter, clothing, health or education without a reference
base. Furthermore, this reference base cannot be the same in the
U.S.A. and Pakistan. Nor can it remain unchanged over time in either
country.
The time when the objective of BNF (absolute) will have been
attained and also the criteria to judge it, may both be fairly clear. But
that alone can hardly help. Required for policy formulation and result
appraisal is the firmness and clarity of relationships between the
needed inputs and the desired outputs. Unfortunately, there is no
production function which spells out these relationships. Precisely
what financial, fiscal or human resources would achieve the desired
results is rarely known. The situation in the developing countries is
characterized with a multiplicity of forces which interact in a complex
and intractable manner.
Of course the average basic needs basket shall not be the same in
content and quality for all the seven countries under study. Still, it is
considered fairly realistic to assess the magnitude of deprivation in
each case by its own, and make comparisons on that basis. The
173
method avoids the difficulties of standardizing the basket as also the
problem of currency conversions to a common base.
To fix ideas, let us suppose that in a given country, for any period t,
Xyt is the mean national income, Xbt is the average expenditure on
specified basic needs, and on them Xbpt is the minimum desired
expenditure for the poor identified as those whose average income Xpt
is less than Xbpt.. Clearly, therefore:
174
3.1 Measurement: Two Indices
In this study we measure these two indices for the selected seven
Muslim countries. We start with the percentage GNP share of the
target group in 1987. This share (col. 9, appendix I) is estimated as a
weighted average for the period 1975-2000, using the group's
population at the two time points as weights. 35
The BNGI rests on the extent of short fall in the target group's
income from the national average expenditure on the specified basic
needs. The gap is expressed as a ratio of the letter to obtain the
required index. Symbolically:
175
BNGI [abY - PpY]abY (1)
where:
Table 1 below shows our findings in terms of BNGI for the seven
selected Muslim countries for the year 1987. We have arrived at these
findings using the World Bank data for 1987 (World Development
Report, 1989).
176
TABLE 1
The above table shows that there are significant income disparities
in the countries under study as indicated by the Pp which measures the
per head income of the poorest 40% (col. 11, appendix I) as a
proportion of the average GNP (col. 2, appendix I). In Turkey the
value of Pp is the lowest at (0.239). Consequently, the BNGI in that
country stands at (0.586) which is the highest in the group. With a per
capita income of U.S. $ 1210, Turkey ranks among the lower middle
income group countries but a highly skewed income distribution puts
her poorest 40% population much below the national average.
Although Bangladesh is the poorest country in the group, her BNGI
(0.478) is lower than Turkey's (0.586). This indicates relatively less
unequal income distribution in the former case. On the other hand,
Malaysia with a U.S. $ 1810 per capita income, is also a lower middle
income country like Turkey, but its track record in combating poverty is
the best in the entire group as indicated by its BNGI being the lowest
at (0.086). This performance of the Malaysian economy is neither
accidental nor is it the sole outcome of the trickled down
177
effects of growth. Rather, the Malaysian economy owes this better
distribution (and hence a lower BNGI) to the New Economic Policy
(NEP) which was introduced in the early 1970s with the specific goal of
improvement in income distribution.
TABLE 2
178
The above estimates show that in order to bridge the 1987 BN gap, in
Bangladesh we need an increase of 133% in her budget for that year.
Pakistan ranks second in terms of additional budget requirement of 81%
while Turkey, needing a budgetary increase of 64%, ranks third in the
group. Malaysia, on the other hand, needs the least additional budget
(0.04%) to bridge the BN Gap. It is interesting to note that there is a
high positive correlation (r = + 0.8) between BNG expressed as a ratio
of GNP, and the BEI. This clearly shows that the higher the basic needs
gap relative to income, the greater will be the effort required to
mobilize resources for the improvement of the condition of the poor in
a `roll up' scheme.
4. CONCLUSION
179
its own context and the cure is prescribed within its own resource
capacity. The technique of estimation presented in this study is neither
claimed to be perfect nor final. Rather, it marks the beginning of a serious
discussion on the estimation of resource requirement and the relevant
strategies to reduce significantly the poverty in the Muslim world (or
elsewhere). Here the BEI estimates the resource requirement to bridge
the entire BN gap in just one year. Obviously, this gap cannot be bridged
in such a short period, and the resource requirement will have to be
estimated on an annual basis with reference to the desired time frame. At
the same time there will be need to discuss the strategies for resource
mobilization for the purpose. Hopefully, further research in the area will
explore relevant issues involved in the process.
180
APPENDIX I
1 2 3 4 5=(3-4) 6
Bangladesh 8 90 2 11 -9 -4
Egypt 14 77 8 19 -11 -4
Indonesia 10 61 29 26 3 0
Malaysia 16 47 37 23 14 4
Morocco 18 68 14 19 -5 1
Pakistan 13 77 11 17 -6 -8
Turkey 12 67 23 26 -3 -1
Source: World Development Report, 1989, Table No. 9, Structure of Demand, pp.
180-81
Appendix III
Source: World Development Report, 1989. Table No. 10, pp. 182-83
182
ENDNOTES
183
inevitably require an improvement in the rate of economic growth (Kumar,
Abs.).
7. Not only Islam but all other major religions of the world insist on the
fulfillment of basic human needs. An interesting elaboration available in
recent times is that of the Talmud, a codification of the Jewish religious law
spanning almost eight centuries. '"The Talmud attempted to raise the poor
to well-defined objective minimum living standards, while considering
individual subjective needs." For details see Shapiro pp. 54-59.
8. For this restricted view see Streeten pp. 109-110 and also H.W. Singer.
184
the spiritual poverty but fails to suggest its specific objective
dimensions or concrete policy measures to reduce it, save for a
vague, general remark.
11. See Hifz-ur-Rehman pp. 40-48 supported by the Holy Qur'an e.g.
15:20; 41:10.
12. Indeed, the point had been conceded both in Libya and Iran, for
example, much earlier than Siddiqui made it in 1983.
13. The paper gives the impression of a hurried effort. The argument is
at places repetitive and shifty and marked with digressions. The
verses quoted do not always bear out the points they are meant to
support.
185
paper as the bench mark, may be regarded as decent for purposes of
measurement. We owe this suggestion to Mr. Zakariya Man,
presently Deputy Dean, Kulliyyah of Economics and Management,
International Islamic University, Malaysia.
186
18. For a detailed discussion of these reasons see M.P. Todaro Ch. 1.
See also Srinivasan.
19. Such a concept was adopted in some Indian studies in the late
sixties. See, for example, Dandekar V.M. and Nilakantha Rath:
Poverty in India, New Delhi, Ford Foundation, 1970. For the basic
needs related concept of the absolute poverty line see Meier G.
(p.43) and for the standardization of the line to facilitate
international comparisons see Todaro, M.P. (pp.32).
20. For this (pp. 20) and other arguments against a 'relative' concept of
poverty see Streeten pp. 17-21.
187
against the rich or compel the state to take corrective measures?
Will shari'ah bar this second course of action? The flow in Mannan
is obvious.
22. "It is not all certain just how many people in the world are
malnourished. In the late 1960s and early 1970s (for example) the
FAO estimated that approximately 1.5 billion people were
undernourished - but in 1974 the FAO estimated that around 1970
less than half a billion people were suffering from inadequate diets
... Unfortunately, the greatly reduced estimate of the number does
not reflect improved diets - merely changed definitions. In 1977,
the FAO once again estimated the number of undernourished in the
LDCs at * somewhere over 400. million people... The calculations
were based on a more conservative estimate of nutritional
requirements than in 1974 (Murdoch, pp. 95-96 see footnotes also
on p. 96).
188
26. Such an estimate can be made by examining medical surveys in
the developing countries. These surveys estimate directly the
number of people showing clinical symptoms of malnutrition. The
WHO has based some of its estimates on these surveys (Murdoch,
pp. 97-98).
27. See Streeten p. 125, also Murdoch pp. 98-99.
29. "By necessities I understand not only the commodities which are
indispensably necessary for the support of life, but whatever the
custom of the country renders it indecent for creditable people,
even of the lowest order, to be without" (Adam Smith, The Wealth
of Nations bk. 5 ch. 2 p. 2, quoted in Streeten p. 19). .
30. It is not K.A: Naqvi alone who raised this objection, as quoted in
the text, to a relative concept of poverty, see also the discussion on
the point in Streeten pp. 18-21.
32. In the case of a notion of relative poverty the reference base may
be a matter of one's predilections. It may be the mean national
income, the bottom of the top 80 percent of population on the
scale, the mean of the top 40 percent or any thing else for any
given percentage of people at the bottom.
189
33. Even in secular economics it is now well recognized that the BHN
(Basic Human Needs) strategy must be implemented in a flexible
way and must go beyond health, nutrition, education, sanitation,
water, and housing to include infrastructure and indigenous, small
enterprise products that will make it easier for domestic production
to meet basic human needs as and when the growing economy so
permits (For details see Curry).
34. The 'Roll Up' approach would insist that as Xbt expands with
growth in the GNP, the ratio of Xpt to Xbt is at least maintained at
the old level and the effort is made to raise it with the passage time.
This would require more pro-poor measures to raise their
productivity, disposable income and availability at reasonable
prices of goods and services included in the expanding basic needs
basket. The process should eventually tend to raise the ratio of Xpt
and Xyt making for a more equitable distribution of incomes (and
wealth) in accordance with the Islamic norms.
35. The calculations here are based on the data given in Todaro (pp.
152-53, 1985).
BIBLIOGRAPHY
190
Burki, Shahid Javed. "Sectoral Priorities for Meeting Basic Needs",
Finance & Development, Vol. 17, No. 1 (March 1980), pp. 18-22.
Curry, Robert L., Jr. "The Basic Needs Strategy, the Congressional
Mandate, and U.S. Foreign Aid Policy." Journal of Economics Issues,
Vol. 23, No.4, Dec. 1984, pp. 1085-1096.
Hosni, Djehane A. and Al-Qudsi, Sulayman, S., "Basic Needs and the
Manpower Dilemma of Kuwait". International Journal of Manpower,
Vol. 6, No. 4, 1986, pp. 13-17.
191
Haque, Mehboobul, "Employment and Income Distribution in the 1970s:
A New Perspective". Development Digest, October, 1971, pp. 6-7.
192
Misiolek, Walter S. and Elder, Harold W. "Cost-Effective
Redistribution: Implications of a Basic Needs Approach to Public
Assistance". Public Finance Quarterly, Vol. 15, No. 1, 1987, pp. 76-97.
Panda, Manoj Kumar, "Fixing Income and Price Targets for the Poor in
India". Journal of Development Economics, March 1986, pp. 287-297.
193
---------------------------, 'Ethical Issues in Income Distribution: National
and International'. Paper presented to the symposium on the Past and
Prospects of the Economic World Order, Saltsjobaden, Sweden, August
1978.
194
Srinivasan, T.N, "Development, Poverty, and Basic Human Needs:
Some Issues". Food Research Institute Studies Vol. 16, No. 2 (1977).
pp. 11-28.
Streeten, Paul, and Shahid Javed Burki, "Basic Needs: Some Issues".
World Development, vol. 6, no. 3 March 1978), pp. 411-21.
195
8
LONG TERM FINANCE IN ISLAMIC COUNTRIES :
CASE STUDY OF PAKISTAN
INTRODUCTION
The paper consists of five parts besides the Introduction. The first
part of the paper briefly surveys the existing financial instruments and
points out the extent to which these instruments adhere to the Islamic
framework. The second part suggests possible changes in these
practices to bring the financial instruments nearer to Islamic standards.
The third part proposes such institutional arrangements as would be
necessary to support the changes suggested in part two of the paper.
Although the main thrust of the paper is on long term finance, the
structural changes proposed in the paper will give rise to some related
questions about short term finance and overall economic management
of the economy. Therefore, part four discusses the related questions of
the proposals made in part two of the paper. The last part consists of
concluding remarks.
197
The main conclusions of the paper are as follows. First, the Islamization
of banking in Pakistan has not met with a success. Most of the finance is
being provided by the savers and the bankers on interest although different
terms are being used to camouflage this. Second, the early days of
Islamization in Pakistan did see some genuine but inadequate efforts to
eliminate interest from the economy but in a period of less than five years
most of these efforts have either been reversed or, at least, further progress
on them has been halted. Third, a genuine attempt to eliminate interest
from the economy would require the restriction of all opportunities for
interest-bearing finance. So long as avenues for interest-bearing
investment are open, the possibility of a successful transition to an Islamic
system of finance is well-nigh impossible. Four, a true Islamic system of
finance would require the savers desirous of earning a return on their
savings to assume risk as well. The shari'ah principle of no risk-no-return
would have to be strictly enforced. This would mean a structural change in
the role of financial institutions. Five, the macro-economic management of
the economy would also have to be in conformity with the Islamic
principles to make Islamic financing a successful experiment.
(1) Long term deposits with commercial banks and development finance
institutions (DFIs)
(2) Saving schemes of the government
(3) Long term bonds floated by the government or public enterprises (like
National Bonds, WAPDA bonds etc.)
(4) Foreign loans from such institutions as Asian Development Bank
(ADB), World Bank, IMF, and Islamic Development Bank, etc. (5)
National Investment (Unit) Trust (NIT)
(6) Mutual funds floated by the Investment Corporation of Pakistan (ICP)
198
(7) Profit-Loss Sharing Investment scheme of ICP
199
Participatory Term Certificates
The Participatory Term Certificates (PTCs) were designed to replace
interest-bearing redeemable finance. The PTCs were an innovation of
the Islamic finance movement. It introduced the concept of redeemable
long-term finance on the basis of profit-loss sharing. The concept
operated in the following manner. An enterprise which desired to get
long-term finance was required to float redeemable PTCs. The
financiers (mostly banks and DFIs) would accept the PTCs for the
finance provided by them. The enterprise would share profit or loss with
the PTCs-holders on the basis of a pre-determined rate. The profit of
loss was determined on a pro-rated basis for the equity capital and long-
term finance obtained through PTCs. The mechanism of obtaining
finance through PTCs has recently been discontinued as the financial
institutions have not found it profitable. Moreover, they involved some
risk for the financial institutions which the latter were unwilling to
assume.
The TFCs are, financial instruments which have replaced the PTCs.
The" TFCs. are i s s u e d by the client enterprises to obtain. finance from
DFIs a n d banks on a mark up of 22% which is calculated by using the
200
compound interest formula. However, the client gets a rebate of 6%-7%
if it pays back the principal sum with the mark-up on the due date.
Introduction of FCs in lieu of PTCs is a step in the reverse direction, so
far as Islamic financing is concerned. There is no difference between
this type of finance and debenture-finance on interest, except that it
does not involve compounding of interest beyond the due date. In that
sense, however, it is a less "efficient" mode of finance than debentures.
The lessee does not have the option to refuse the article or to return
it before the lease term. In this way, the lessor does not assume the
"business risk" which a lessor of operating leases (such as houses etc)
would assume. The lessor in the case of finance-lease extends finance
for a specified period and takes it back with a pre-determined increment
without assuming business or trade risk. In brief, the finance-lease it
nothing but another form of financing on interest. However, some
companies are also in the operating-lease business. In this case the
lessor assumes all the risks which an owner of an asset has to bear in
the normal course of leasing business. This type of lease is not very
popular, however. Data are not available on the exact proportion of the
types of leasing business but interviews
201
with the executives of some of these companies revealed that they are
doing mostly finance-leasing.
Housing Finance
202
Reasons for Going Back to Interest-Bearing System
The bankers are extremely worried about the safety of the depositors
funds. They feel that at the prevailing standards of ethics and honesty,
it is highly risky to extend finance on profit-sharing basis. They are
afraid that their clients will depict losses or at least will suppress true
profits in their accounts and as bankers they will not be able to
effectively check this tendency. The confidence in the banks will
erode and the whole financial structure will collapse. Therefore, they
have adopted the safer course of providing finance on the basis of
mark-up which is a disguised form of interest.
The banks do not have any experience of operating in the public sector
which requires different types of skills. They do not want to risk the
depositors' funds by operating in a field they do not know. They are
conscious that they are in the position of financial intermediary and
they want to remain restricted to that without assuming additional
risk.
The cost of finance for the financial institutions is higher than the
return they can get from the investors or if they have to arrange
finance on interest they cannot give it on a profit-sharing basis. For
example, HBFC gets finance on a flat mark-up of 9% from the State
Bank of Pakistan. It could not afford to provide it to individuals on
rent-sharing bases, when the average rate of return was less than 5%.
Similarly, Pakistan Industrial Credit and Investment Corporation
(PICIC) obtained funds from ADB, IBRD etc. on fixed interest. It
could not risk its deployment on profit-sharing basis where the return
was uncertain.
203
The above account of the reasons for a reversal towards interest-
bearing finance points toward the direction of the proposal we are
going to make in part two of the paper. In brief, there are two
compulsions: first, the banks are financial intermediaries. They cannot
get into real sector. This, by itself is not objectionable from the Islamic
point of view. The Islamic position is that, in this case, the banks
should also not expect a return of the finance provided by them. They
should remain restricted to getting a fee for being financial
intermediaries, which is a service. From the Islamic point of view, if
the banks want to earn a profit they should have to assume the business
risk, also. Since at that present moment of history they are unwilling to
assume the risk of loss, for whatever reason, they, should limit their role
to being agents of investors and savers for a fee or service charge and
quit the role of lenders on interest. In fact, this is going to be one of
our major proposals.
204
PART TWO : ISLAMIC INSTRUMENTS OF LONG TERM
FINANCE
205
The PTCs should be made tradeable on the stock exchange. The idea
is to develop a secondary market for these instruments. This will
obviate the need for discounting and re-discounting of the PTCs.
206
leasing to the first lessee if it is so required by him. The banks will
also arrange to dispose of the assets once they are returned by the
lessees after their natural life. In brief, the banks will act as agents of
the savers who will be the lessors.
As lessors, the leasing certificate holders will assume all the risks
which any lessor has to accept in this business.
Since the banks will not be assuming any risk they will also not be
entitled to any profit. All profit or loss will be passed on to the
leasing certificate holders after the banks have deducted their agency
commission. This commission will be a fixed sum to be paid once for
each service. However, to keep the interest of the banks it can be
stipulated that the banks will share in profit if it is over and above a
certain threshold.
The consumers need credit to purchase durable goods like motor cars,
motor cycles, refrigerators, air-conditioners, and houses. Since the
consumer items do not generate any profit or loss their financing poses
a challenge. The following proposal is likely to present a solution to
this problem.*
* For a short-comment on economic implication of this proposal, see part four of the paper
(below).
207
These products will be offered for sale on instalment at the same
price as cash. This is essential to forestall the re-entry of interest in
the economic system in a disguised form. At present, the difference
in the cash price and the credit price of products sold on installments
is mainly due to the interest charges on the capital involved.
Most likely, it will have the effect of inducing everyone to try to
obtain the asset on credit, if possible.
The manufacturers will get a refinance facility from the central bank on
profit-loss sharing basis. The customers will repay their installments
to the sellers who will return the finance to the central bank along
with profit or loss. Since it may be possible that the central bank
cannot, possibly, deal directly with so many manufacturers, the
banks can act as agents of the manufacturers. They will charge their
agency commission for their services'.
Since the refinance will be available on a profit-less sharing basis, it
is possible that some saving societies(*) choose to provide finance to
the manufacturers or developers of the housing estates on a profit-
loss basis.
Gradually, the manufacturers and developers of houses can resort to
issuing of Instalment Sales Certificates which can be bought by the
consumers' saving societies or commercial banks, if they have funds,
or through a central bank.
These certificates will be traded on the stock exchange. In the
beginning, the central bank wall take the initiative to provide the re-
finance.
The Instalment Sales Certificates shall be redeemable by the
manufacturers and developers of the houses after a stated period.
208
deposits from the savers in the form of special or general purpose
mutual funds. These funds can be instituted to provide finance to
specialized sectors or for general purpose financing through PTCs,
MCs, LCs or ISCs. Since the former saving schemes, saving bank
accounts, fixed earning bonds and certificates will be banned, these
mutual funds will be a great attraction for the savers. The money
collected in these funds will be invested on the basis of equity or for
leasing or for mudharabah. The mutual fund certificates will be traded
on the stock exchange.
7. Investment Trusts
209
The limit of Rs. 30,000 should be relaxed and people should be
allowed to make investment to any limit. However, the profit-loss
sharing can be made proportionate to respective capitals.
Similarly, the counterpart funds can be made available in equal
proportion.
There is no reason why the profit loss sharing investment scheme
funds should be restricted to the purchase of joint stock shares.
These funds should also be made available for investment through
other financial instruments.
The ICP also accepts funds for investment in equity stock without
providing counterpart funds. This arrangement can continue.
PREREQUISITES
210
working in financial institutions in the concept and practice of Islamic
finance should be given a priority at the national level.
INSTITUTIONS
The commercial banks will also have a changed role. They will
accept deposits on current account for safe custody only. They may be
allowed to charge a fee for providing this service. They will not accept
savings for investment and lending except in those cases where the
depositors agree to make them their agents or trustees for investing on
their behalf.
211
brokerage, etc which they are doing at present and which do not involve
any interest related activities.
2. Investment Banks
The investment banks will replace the present day saving schemes,
saving bank accounts, postal saving accounts, fixed return certificates
and bonds issued by a large number of DFIs. The investment banks will
collect household and corporate savings and act as agents or trustees to
place those funds in the real sector. These banks, again, will be doing
this business on behalf of the savers and would receive agency charges
for various services they perform. At present the ICP and the NIT are
examples of investment banks. A large number of such banks will have
to be established in the public and private sector. Their number will
have to be large because they will be mainly responsible for attracting
household and corporate savings.
3. Mudharabah
4. Stock Exchanges
212
basis is so overwhelmingly large and. the equity capital market is much
smaller. As a result, the activity and the stock exchanges is also very
limited. If necessary, more stock exchanges may have to be opened.
5. Saving Societies
213
There will be an urgent need to establish an independent Islamic Audit
Foundation (IAF) responsible for issuing accounting and auditing
standards which are in conformity with the Islamic law. The IAF should
also appoint auditors on behalf of the savers and investors to carry on
audits independently. The IAF will pay the audit fees for these audits
which it will recover from the companies registered with it. The
incentive for getting a registration of the IAF would be entitlement to
finance from various specified sources. We have discussed this question
in more detail elsewhere3.
8. Al-Hisbah
In this part we shall discuss some broader issues which have a deep
impact on the success of the proposal made above.
214
1. Economic Implication of Consumer Durable Finance Proposal
215
It can be argued that the scheme can be misused. The answer is that
the legal framework, monitoring and auditing controls will have to be
strengthened to forestall its misuse. The possibility of misuse is not
specific to the proposal. It is general to all arrangements.
Another question is: since the cash price and credit price will be the
same, it will stabilize at a level, where the manufacturers of consumer
durables are able to earn a profit and give a share of this profit to the
financial institutions providing finance. This level would, in all
probability be higher than the cash price level. As a result, there may be
a general price-hike in the economy. This fear is not realistic. The cash
price in a system where finance is available on interest. contains an
element of interest which bids up the sale price. In a situation, where the
price does not have an element of interest, the increase in price due to
the manufacturers' expectation for a higher profit would compensate for
the reduction in price due to absence of interest as an element of cost of
production. In practice, the price in the proposed arrangement could be
more or less than the effect of interest on price.
216
But then, we cannot make a firm comment at this stage of our
knowledge.
* This is his personal opinion and does not necessarily reflect the views of IRTI/IDB.
217
instruments can be issued in installments according to the paying
capacity of the government.
A related question is the inflation that has eroded the value of the
money originally lent by a person to the government. It is highly
injudicious, it can be argued, to return the principal sum after so many
years. But this objection could have some validity if the loan had been an
interest-free loan. The lenders had been receiving interest on their loans
which, more or less, was equal or more than the inflation rate. In fact,
such lenders are not losing anything.
Foreign Debt
218
domestic rate of savings is low, the need for foreign capital may remain.
Moreover, it may not be possible to change the course of the economy
in a sudden manner. Therefore the first effort should be to try to get
venture capital on a profit-loss sharing basis.
219
3. Public Financial Management
4. Macroeconomic Management
220
5. Credit Rationing
6. Accountability Mechanism
221
PART FIVE : CONCLUDING REMARKS
The paper has briefly discussed the existing pattern of long term
finance in Pakistan. It has been argued that by and large long term
finance is still being made available on an interest basis. Conceptually,
long term finance is one area where the concept of profit-loss sharing is
most suitably applicable. But this has not happened in Pakistan despite
all the lip service paid to Islamization. The reasons are, mainly, lack of
political will, existence of an interest-bearing economy which had the
effect of Gresham's law, nonavailability of interest-free finance from
other countries, internal resistance from the banking community which
is extremely skeptical of the whole concept of interest-free finance, and
inadequate legal support. The proposal made in this paper seeks to
establish the whole financial structure on a profit-loss sharing basis. It
visualizes a new role for banks and financial institutions. They should
restrict themselves to agency and other services for which they may get
a fixed fee. The savers in the economy, who like to earn a return on
their savings, should assume the risk as well. To facilitate this concept
a number of financial instruments have been proposed. At the same
time there is a need to establish such institutions which support the new
system. Not only this, a host of policy measures and structural changes
would be needed to effectively abolish interest within unIslamic
community.
ENDNOTES
1 In fact, this is being done even now. The State Bank of Pakistan
provides re-finance @60% for Locally Manufactured Machinery credit.
Our proposal only transforms the fixed interest into profit-loss sharing.
222
4 For a detailed treatment, see the present writers' "al-Hisba and the
Islamic Economy" in Ibn Taimiya, Public Duties in Islam, Leicester: The
Islamic Foundation, 1982.
6 In fact, the ICP already has a State Enterprises Mutual Fund (SEMF).
This fund can be enlarged to include all government investments in state
enterprises. The holders of domestic debts may be issued SEMF
certificates, where profit and loss from all state enterprises will be
pooled. This will also allow a uniform rate of dividend to holders of
these certificates. The certificates can be made tradeable on the stock
exchange.
BIBLIOGRAPHY
3 Ghifari, N.M. & M. Muzaffar Ijara and Its Modern Applications. Paper
presented in the Seminar on Islamic Financing Techniques, Islamabad,
December, 1984.
223
7 al-Kaff, S.H.A.R., al-Murabaha in Theory and Practice, Karachi: Islamic
Research Academy.
8 Kakakhel, M.S.S., Bai Muajjal and Bai' Murabaha (U). Paper presented to
the Seminar on Islamic Financing Techniques, Islamabad, December.
11 Khan Aftab A., The Role of Banks and Financial Intermediaries in The
Development of Capital Market IBP, Karachi, August 1990. -
224
18 Qureshi, D.M., Mudaraba and its Modern Applications. Paper presented
to the Seminar on Islamic Financing Techniques, Islamabad,
December, 1984.
21 Rehman, G., Bai' Muajjal and Bai' Murabaha (U). Paper presented in
The Seminar on Islamic Financing Techniques, Islamabad, (December
1984).
70=145-:a.88
225
9
FINANCING ECONOMIC DEVELOPMENT IN ISLAMIC
ECONOMICS: ATTITUDE TOWARDS ISLAMIC
FINANCE IN SMALL MANUFACTURING BUSINESSES
IN SAUDI ARABIA
BANDAR AL HAJJAR*
AND
JOHN PRESLEY**
INTRODUCTION
227
managerial and entrepreneurial skills. Again profits are shared according
to a proportion agreed in advance. Losses, if incurred, are the liability of
the provider of capital; the mudhareb (entrepreneur) merely loses his
expected share of profits and his efforts are foregone without
remuneration.
228
other non-financial incentives) and factories and workshops regulated
by the municipalities, having no access to financial and non-financial
incentives.
229
mainly at the domestic market. These included food, beverages, dairy,
chemical, metallic and non-metallic products. Government incentives
included the provision of medium and long-term interest free loans of up
to 50 per cent of the total cost of the project with a repayment holiday of
between one and two years, exemption from custom duties on raw
material and machinery used in production, preference of national
products on government contracts, distribution of land in various
industrial cities at nominal rent, subsidized prices for electricity and water
and the imposition of tariffs on similar foreign products: the latter was
possible given the ability of national factories to provide at least 70 per
cent of the market demand.'
The response of the private sector to these incentives is- shown in the
number of factories and the contribution of the manufacturing sector to
total GDP and to non-oil GDP. Table 1 indicates that the number of
factories operating -in the Kingdom up to 1987, reached 2,016, covering
all economic activities. Of these 31 per cent were small according to the
definition adopted in this study (employing between 10 and 30 persons
and their invested capital ranged between one and five million riyals).
Despite the industrial development which has taken place since the
mid-1970's, small factories and workshops continue to play a dominant role
in some industries. The census of private establishments conducted in
1976 and again in 1981 indicated that 92.8 per cent and 91.2 per cent
respectively of industrial concerns employed less than 10 people.
230
TABLE 1
Leather Products - - - 4 4
Industry
Source: Ministry of Industry and Electricity, The List of National Factories Licensed Under the
Statute of Protection and Encouragement of National Industries and Foreign
Investment Code up to 1987.
1 . . These factories are licensed under the Statute of Protection and Encouragement of
National Industries and the Foreign Capital Investment Code.
2. Small factories are those whose invested capital ranges between one and five million riyal, and
employ between 10 and 30 persons.
3 Medium and large-scale factories are those whose invested capital is more than five million
and employ more than 30 persons.
4. With Saudi and foreign capital invested in company.
231
TABLE 2
After 1982, the growth rate of the value added of the manufacturing
sector started to decline. Indeed, until recent years its growth rate has
been negative. This was due partly to the decline in government
spending, completion of most infrastructure projects and the departure
from Saudi Arabia of many foreigners, especially construction sector
workers.
METHODOLOGY
233
and therefore definitions are often adopted within the constraints set by
data availability. (Burn & Dewhurst 1986; Neck & Nelson 1977).
234
approach to the conduct of interviews and also the most suitable ways
of distributing and collecting questionnaires. As far as the authors are
aware, this is the first survey undertaken of small businesses in Saudi
Arabia.
i) It was apparent that lack of finance was only one factor limiting
the development of small businesses.
iii) The pilot survey revealed that accounts were not readily available
in small businesses in Saudi Arabia. It was therefore impossible
to conduct the kind of case study approach adopted in other
developing countries, based upon accounting ratios. (Osaze 1981;
Ahmed 1987). A more general approach was adopted based upon
distributing a large number of questionnaires, accompanied by
follow-up interviews.
235
The major investigation of the questionnaire which followed the pilot
study consisted of a questionnaire survey of 412 small firms within the
manufacturing sector: of these 222, or 53.9 per cent were completed,
collected and analyzed. The breakdown of these by product group is
contained in Table 3.
236
TABLE 3
5 79 52 65.8 23.4
6 41 29 70.7 13.1
412 222 53.9 100.0
Where:
237
owner of the business to remain anonymous. All businesses should
operate under Saudi ownership, but the questionnaire revealed that in
many cases must be collected a "kafil" arrangement exists where a Saudi
national has the appearance of being the owner in order to disguise the
true identity of the real owner who is non-Saudi. Any musharakah
arrangement would bring with it the fear of exposing the illegality of the
business. Interviews also revealed that were aware of the need to supply
financial and non-financial information in order to gain Islamic
financing. Most indicated that they were not in a position to be able to
do this.
TABLE 4.
COUNT
ROW Building Aluminum Wooden Chemical Iron Others Row
PCT Materials Products Products Products Products Total
COL 1 2 3 4 5 6
PCT
TOT
PCT
Prepared to 9.0 5.0 4.0 20 10.0 5.0 35.0
accept 25.7 14.3 11.4 5.7 28.6 14.3 16.6
Musharakah 15.0 19.2 12.5 10.0 20.0 17.2
arrangement 4.3 24 1.9 0.9 4.7 24
Not 51.0 21.0 28.0 120 40.0 24.0 176.0
prepared to 29.0 11.9 15.9 6.8 227 13.6 83.4
accept 85.0 80.8 87.5 85.7 80.0 82.8
Musharakah 24.2 10.0 13.3 5.7 19.0 11.4
arrangement
Column 60.0 26.0 320 14.0 50.0 29.0 211.0
Total 28.4 123 15.3 6.6 23.7 13.7 100.0
238
TABLE 5
0 94 42-3 Missing
222 100-0 100.0
Where:
TABLE 6
COUNT '
ROW PCT Building Aluminum Wooden Chemical Iron Others Row
COL PCT Materials Products Products Products Products Total
T0T PCT 1 2 3 4 5 6
239
Of the respondents (128), 36 per cent more preferred to share
business ownership with a friend or relative than with a financial
institution or national company. Interviews confirmed that this was due
to the simplicity and informality which might attach to such a financier
compared to the requirements, for example, of bank borrowing where
financial records and/or business plans might be required before share
capital is provided. In contrasts only 13 per cent would prefer to share
ownership with a commercial bank. Interviews concluded that this was
primarily because such banks were seen to be charging interest on
other accounts and therefore for religious reasons should be avoided.
Despite this response however it is noticeable that Islamic banks were
not overwhelmingly popular 'as financial sources, only 26 per cent
preferred than as first choice financiers.
240
CONCLUSION
FOOTNOTES
241
5. For more details about the inconsistency in international statistics
about small firms, see Burns P & Dewhurst J. (eds.) Small Business in
Europe (1986). Macmillan Educational Ltd: Also see Enterprise
Development: Policies and Programs, International Labor
Organization (1977). For more details about the economic and
statistical definition of small businesses, also see Bolton Report:
Report of the Committee of Inquiry on Small Firms, Cmnd 4811,
London HMSO 1971. For more details about the statistical definition
of small businesses in some developing countries, see Stalev E &
Morse R. Moders Small Industry for Developing Countries, McGraw-
Hill, New York, 1965.
BIBLIOGRAPHY
242
Appendix I
The information included in the list only partially serves the purpose
of this study since the list does not contain data on financial
measures such as annual turnover, sales and profits and, secondly, it
only covers those factories whose invested capital exceeded one
million Saudi riyal.
243
despite their fully . computerized system, the Commercial
Registration Department have, to date, not produced such a list or
directory. The Department considers that the task of organizing and
classifying this information is the responsibility of the Ministry of
Industry and Local Municipalities since these concerns are involved
in industrial rather than commercial activities.
The CDS published a summary of the results of the 1971, 1976 and
1981 censuses. However, information, including names and
addresses of concerns which participated in these surveys are
considered to be confidential by the CDS and are not available to
this study.
244
6. The Domestic Economy Department at the Ministry of Finance and
National Economy has produced a very valuable list which is part of
a survey study of the national factories in production up to 1985. The
list contains the following information:
The main reasons for adopting two samples is to stress the extent to
which the smaller concern has access to external sources of finance in
contrast to the slightly larger business. Members of the second sample
are entitled to obtain an industrial license from the Ministry of Industry
and Electricity, which enables them to obtain long and medium interest
free loans up to 50 per cent of the total cost of the
245
project from the Saudi Industrial Development Fund (SIDF). This, in
turn, paves the way for them to obtain financial facilities from
commercial banks and other external sources of finance. Members of
the first sample are not subject to industrial license regulations and this
deprives them of access to the financial facilities provided by SIDF.
Hence it is more difficult for them to secure loans or other financial
facilities from commercial banks.
The first sample was drawn from the lists prepared by the Ministry of
Finance and National Economy, and that. of the Chambers of
Commerce. The second sample was drawn mainly from the list of
licensed factories in production issued under the National Protection
and Encouragement Law and Foreign Capital Investment Law up to
1987 and the list prepared by the Ministry of Finance.
246
10
SOME CONSIDERATION ON THE SIZE OF THE
PUBLIC SECTOR IN THE ISLAMIC REPUBLIC
OF IRAN
IRAJ TOUTOUNCHIAN*
INTRODUCTION
The paper addresses itself to the above question and seeks answer to
see whether this past trend will persistently show up in the future or if
there are reasons to believe that past growth was temporary and
transitory?
Less than two years after the Islamic revolution in Iran, the country
engaged in an unwanted war with Iraq. Quite expectedly the government
in response to the expectation of the general public for protection
against resulting shortages and rising prices, intervened in some areas of
economic activity. This intervention went beyond the scope outlined in
the constitution.
247
to escalating economic problems such as unemployment and inflation to
limit its involvement in economic affairs.
SIZE OF GOVERNMENT
248
Economists, in general, have come to the conclusion that any measure
of the size of the government is arbitrary.
TABLE 1
ALTERNATIVE MEASURES'
Each one of the above-mentioned measures has its own merits and
demerits. Not all measures have the same sensitivity with regard to the
factor. chosen. For example, the errors in estimating capital
consumption, in using "national ' income" measures are . likely to be
greater than .the errors in -the measurement of " gross product' so that
variations in the ratio will be sensitive to the- precise method used to
calculate capital consumption. The same argument . applies to the
choice between market price and factor cost measures. Variations'in
the ratio will be sensitive to- variations in the mix of direct taxes,
indirect taxes and subsidies. This means that if ratio (2) is to be used
249
to show changes in the relative size of the public sector over time to
compare the sizes of the' public sectors in different countries, the
conclusions that can be drawn are clouded because the ratio will. not
only be an indicator of the relative size of the public sector, it will also
reflect. variations in the structure of public sector revenues. The
following example illustrates the point:
For example; Two countries A and B each spend 100 units on public
expenditure. Each of these two countries have gross domestic products,
measured at factor cost, equal to 200 units. Country A finances its
public expenditure from the following mix of taxes: 10 units from direct
taxes and 90 units from indirect taxes. Country B finances its public
expenditure from the following mix of taxes:, 90 units from direct taxes
and 10 units from indirect taxes. Subsides in country A=20 units and in
country 13=30 units.For country A, GDP (market price) = GDP (factor
cost) + indirect taxes - subsidies = 200+90 - 20 = 270, for country B;
GDP (market prices) = 200 + 10 - 30 = 180.
TABLE 2
250
One should note that the conclusion derived from this example
depends on the degree of shifting the tax incidence. In other words, the
underlying assumption here is that both indirect taxes and subsidies will
be 100% shifted upward, which is of course a strong assumption.
251
PART ONE : THE SIZE OF THE IRANIAN GOVERNMENT
BEFORE AND AFTER REVOLUTION
TABLE 3
With respect to the years selected and the time period chosen in this
paper some caveats are in order: 1) The year 1977 (corresponding to
1356 of the Iranian calendar) has been used as the base year with which
other ratios for the corresponding year can be compared. The
252
reason 1977 has been selected as the base year is that during that year
three major economic activities (namely, Agriculture Ministries and
Mines, and Services) had been operating at almost full capacity.4 2)
Although the revolution happened on 11th February 1979 the data for
the two preceding years have not been, due to the turbulent state of
affairs in the economy, reliable. 3) Unavailability of a uniform data to
make comparisons easy did not allow me to present them here.
(1) The range of numbers starts from 20 per cent and goes to the
highest value of 32 in all years covered, which is a mild increase in
the size of Government. However, the highest ratio was observed
in 1981 which not only does not keep its time trend in the
following years but also declines to its minimum value in the last
year of coverage, i.e. 1986.
(2) The maximum and the minimum values of all four ratios occur,
without exception, in 1981 and 1986, respectively. Emphatically,
all four ratios in 1986 are below the corresponding ratios in the
base year. Having accepted the four measures as being
appropriate and sound measures, this result might be used as an
evidence of a relative decline in the size of the government of the
IRI during the ten years under consideration.
253
(3) Heavy dependency of the economy of the IRI on oil revenues
shows itself in 1983 and 1986. Full fluctuations in oil revenues
are reflected in the size of government expenditure in these tow
years. In 1983 the economy enjoyed the highest oil revenue ever
since the revolution. In that year, the first two values remain
constant, relative to those in the base year. But the last two
measures show slight increases in comparison with the
corresponding figures in 1977. In 1986, a sharp decline in oil
revenues, caused a corresponding decline in government
expenditure to such an extent that almost all figures reach their
minimum values in this year.
254
TABLE 4
GOVERNMENT REVENUES
Unit: Billion Riyals
Year 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990
Source of Revenue
1- Export of oil and gas 889 1056 1690 1779 1373 1189 417 766 668 763 1090
2. Other than oil and gas 543 868 1012 1217 1620 1780 1159 1748 1832 2619 3427
3- Taxes 340 554 614 797 899 1034 1025 1030 986 1031 1930
4- Non-taxes 202 314 398 420 721 846 575 718 846 1588 1797
Total 1431 1924 2701 2996 2993 2969 2016 2514 2500 3382 4517
A) Public Revenues
. In this section four other tables have been provided. The first two
tables show the sources of government revenues and the remaining two
tables show the government expenditures. Table 4 shows four different
sources of revenues from 1980 to 1990. Although a mild decline in total
revenues was observed in 1984 and 1985 relative to those in the
preceding years, the decline in 1986 was quite sharp, i.e. over 30 per
cent.
Revenues from the export of oil and gas show a relatively small
decline in 1984 and 1985 compared to those in the preceding years.But a
drastic decline of 65 per cent occurred in 1986. As noted earlier, the
evidence of heavy dependency on one revenue source is shown in the
first six years where, oil and gas revenues accounted for 54 per cent of
the total revenues. It should be noted that the formal exchange rate is
$1=Riyals 70 i.e., all revenues earned from the export of oil and gas are
multiplied by 70. But inflation has ceased to allow the formal exchange
rate to play its role. If government should decide to devalue the local
currency, the degree of reliance on one revenue source will increase.
For example, in. 1987, oil and gas revenues amounted to over 10 billion
U.S. dollars. If effective exchange rate should be $ 1= Riyals 500 (in the
current year the black market rate has been over Riyals 1300) then,
ceteris paribus, total revenues would increase to 2719 billion riyals.
Consequently, the ratio-of oil and gas revenues calculated at the new
exchange rate (which would amount to 5471 Billion Riyals) to total
revenue of 7219 billion, Riyals -would go up to 75 per cent compared
to the actual r a t e o f 30 per cent.
Tax revenues exhibit an increase in all years covered except for two
years of 1986 and 1988. Tax collections has almost doubled in size
compared to 1981. There are. three reasons for such an increase. Firstly,
considerable ware expenditures forced the government to put strict
controls over the foreign exchange revenues and hence investment
expenditures declined drastically. Therefore, capital stocks
256
were allowed to depreciate to their minimum level. The book values of
the already existing stocks had been quite low, consequently
depreciation expenses were minimal. However, due to high inflation
rates, the replacement costs of capital stocks compared to their book
values was quite high. Secondly, inflation caused revenues to increase.
Granted that, during inflation, the rate of increase in other expenses
such as wages and salaries, customarily, lag behind the rate of inflation,
the two factors were partially responsible for the rise in profits and
hence an increase in tax revenues collected from corporate profits.
Thirdly, on equity grounds, government tried to collect more taxes from
occupational incomes on the belief that they had enjoyed windfall
profits during the inflationary period.
Table 4 shows that tax revenues did not exceed more than 50 per
cent of the government's revenues during the period of coverage. The
highest ratio occurred in 1986 which accounted for 50 per cent of total
revenue and the lowest ratio is identified in 1982. Although, since the
revolution, the greatest fall in oil and gas revenues bills in 1986, tax
revenues partially compensated the fall. Again, during the period under
consideration the IRI had the highest revenues, from the export of oil
and gas, in 1983. It reached the highest ratio of 59 per cent relative to
the total government revenues. But, in this year the ratio of income
taxes to total government revenues was the lowest at 27 per cent
relative to total revenues. Putting these facts together we can conclude
that tax revenues are the most reliable source of the revenue to the IRI.
Revenues received from the export of oil and gas are liable to external
shocks and drastic fluctuations in price and hence represent an
unreliable source of revenue.
257
TABLE 5
Year 1977 1988 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988
Source and Ratio
Direct Taxes 231 270 229 129 327 296 331 405 528 579 612 646
Indirect Taxes* 213 197 140 211 227 318 464 503 505 446 418 340
Total Taxes 444 467 369 340 554 614 795 908 1033 1025 1030 989
Source: High Council of Taxation; Ministry of Economic Affairs and Finance (1989)
* Close to 100 per cent of indirect taxes is composed of import taxes- Other indirect taxes are negligible.
To embark on the policy implication of the point made above, we
need further information. Table 5 is provided to furnish us with the
necessary information about direct and indirect taxes for the period
1977-88 inclusive. The growth of indirect taxes, quite expectedly,
parallels oil and gas revenues because of higher incentive led to
increased imports. As a result one can see the maximum value of oil and
gas revenues in 1983 (Table 4) which coincides with the highest ratio of
indirect taxes to total tax revenues of 58 per cent.
B) GOVERNMENT EXPENDITURES
259
if possible, welfare. As mentioned earlier the overall welfare of an
average Iranian- citizen has considerably declined.
260
TABLE 6
COMPOSITION OF GOVERNMENT EXPENDITURES
Unit: Billion Riyal
Year 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990*
Expenditures
Total Expenditures 2404 2861 3367 3895 3632 3616 3466 3983 4625 4528 1602
1. Current Expenditures 1730 2032 2253 2524 2476 2548 2410 2911 3394 3203 3965
2 Capital Expenditures 568 675 915 1149 878 765 746 729 816 900 1631
(24) (23) (27) (29) (24) (21) (21) (18) (17) (20) (26)
3. Other Expenditure 105 154 199 223 278 303 309 342 415 725 507
Sources: National Income Accounting Department: Central Bank of Iran - and Ministry of Economic Affairs and Finance - various
publications-
* All figures are forecasts not actual.
Note: All figures are at current prices- Figures in parentheses are ratios of the respective figures to total- For further information: budget
deficits have traditionally been financed through borrowing from the Central Bank-
TABLE 7
AMOUNT OF SUBSIDIES
Unit Billion Riyals
1977 1981 1982 1983 1984 1985 1986 1987 1988* 1989*
65.8 81.3 109.7 106-1 120-2 207.1 127-3 104-6 155-0 206.0
Source: The Organization for Protection of Consumer and Producers (various pamphlets)-
* Receipts not payments.
Subsidies being mainly financed through overcharges o n imported
goods, it is seen from the table. that in 1 9 8 6 during which we experienced
the highest decline in oil and gas revenues, we witnessed a somewhat
corresponding decline of 60 per cent in subsidies. However, when the
country had the highest oil and gas revenues in 1 9 8 3 the amount of
subsides not only failed to rise but decreased slightly relative to 1982.
*Adopted from C.V. Brown and P.M. Jackson (1982), pp.157-160. 262
262
about last year's budget and the one the year before that and so on. A
decision to build a highway or a public health care centre is not a
commitment to allocate resources to these activities for the next year
only. Instead, these resources are committed until a decision is taken to
change the level of quality of service provision. thus, last year's budget
determines this year's budget because of the large commitment of
resources that is carried forward into the present from the past.
263
(1) Agency's . decision rule:
X it =bi Y it-1 +e it
where: X it = the requested budget by Agency i in period t.
Y i t 1 = The actual budget granted to agency i in the previous
_
year.
b i = a parameter> 1
eit= a randomly distributed variable with mean equal to zero.
An agency current year budget equals the previous year budget plus
certain mark-up. If, for example, b=i=1.12 then this year's budget is 12
per cent greater than the previous year.
This rule shows that the actual budget granted by the committee is
equal to some proportion (less than one) of the actual amount
requested. (The model needs some refinement. That is, after this
process has been continuously in use, then both the agency and the
committee know the rules of the game. Then each side can predict the
game that the other will play. Thus, the applying agency will always
overstate the amount requested with the belief that the committee will
try to reduce it. Consequently, as the committee has learned from past
experience that the agency often overestimates the needed budget . it
has the rationale to cut it. In other words, overstatement of , budgets
and. slashing them become an established rule. My experience as a
deputy minster, in the past, and as an adviser, at present, allows me to
claim that this has been the rule p racticed for long time in the IRI).
264
It means that this year's budget is a function of last year's budget;
which is, the decision rule of incrementalism. The error terms in each
decision rule reminds us that these are statistical decision rules. In other
words, the actual outcome is dependent upon the actual amount granted
plus random events that occur during the year such as unforeseen
floods, earthquakes and other natural calamities.
Real world markets are far away from being perfectly competitive.
There are some impediments that may prevent free markets from
generating allocative efficiency. Hence, government finds it to the
benefit of the pubic to intervene. The number of impediments to perfect
competition is practically infinite.Where possible, however,
265
these can be classified into three categories that include most of the cases
in the real world. They are namely: imperfect competition, externalities,
and public goods. In order to be able to carry forward the results of this
part of the paper to the next I will try to discuss each on of these
categories very briefly.
A) Imperfect Competition
266
B) Externality
267
divergence between-private and social cost (utility). In cases where
production of a commodity entails pollution the social rate of product
transformation will exceed the private rate of product transformation of the
same commodity with no pollution. Since the price system reflects only the
private costs therefore, the social and private rates of transformation differ.
The result would be that the private market will tend to produce too much
of the commodity when production entails pollution, relative to other
commodity.
C) Public Goods
I believe that the scope of public goods goes beyond the examples
conventionally given such as national defence, inoculations against
268
infectious diseases, criminal justice, pest control and the like. Another
important public good, whose importance cannot be exaggerated, is
"money" with all externalities attached to it. In my paper entitled:,
"Money in an Islamic Economy" I have prescribed that, due to the
peculiar characteristics of money such as not being allowed to hoard,
speculate or used on interest - based contracts, the government, not the
private sector, shall manage it.
269
a correct and just economic system in accordance with Islamic criteria is to
be one of the "goals" of the Government of the Islamic Republic".
At first glance, it seems that the private sector has been assigned a
residual and relatively minor role in the economy. However, the above
description of the cooperative sector does not assume, implicitly or
explicitly, that this sector is to be totally within the public sector domain.
Rather, the provision for the establishment of the cooperative sector
indicates an attempt to implement and foster the spirit of the principle of
cooperation in economic activities observed by the Qur'an and Sunnah.
This sector can be wholly within the private sector domain, that is, the
firms and units comprising this sector can be private, but "cooperatively",
owned just like a corporation whose shares are owned by a large number
of stockholders, as opposed to single proprietorships or (small)
partnerships. This idea is reinforced by Clause (b) of Article 43 which
designates cooperatives as means by which" conditions and possibilities of
employment" can be "assured for everyone, with a view towards attaining
full employment "by" placing
270
the means of production at the disposal of anyone who is able to work
but lacks the means. "The same clause specifies the granting of interest
free loans as a vehicle for securing the "means of production" for those
who are able to engage in productive activities but lack the financial
resources to do so. Clearly, the constitutional intent is to prevent
concentration of economic power in the hands of the few.
271
property is to "be restored to its legitimate owner, and if no such owner
can be identified, it must be placed in the public treasure". Economic
activities declared as illegitimate sources of property rights are precisely
those listed in traditional Islamic sources. However, Article 50 of the
Constitution expands the traditional list to include those economic
activities" that tend consistently to pollute the environment or inflict
irreparable damage on it".
The right to work is endorsed for everyone, and the Government has
been made responsible for providing "every citizen with the opportunity
to work," as well as with the duty of creating "equal conditions for
obtaining it" (Article 28). In carrying out these duties, however, the
Government itself must not become "a major or dominant employer"
(Article 43).
272
recovered from usurpers". Additionally, the National Consultative
Assembly (the parliament) is empowered to imposed taxes, "in
accordance with the law" (Article 51). The Government is to prepare
annual budges, "in a manner specified by law" and submit them "to the
national consultative assembly for discussion and approval" (Article 52).
Government revenues are to be placed" in accounts at the central
treasury, and all disbursements shall be within the allocations approved
in accordance with law" (Article 54). An auditing agency, under the
supervision of the parliament, is provided for in the Constitution as a
check on fiscal operations of the Government, its agencies, and its
contractors (Article 54 and 55).
To ensure that all laws passed by the parliament are compatible with
the shari'ah, the Constitution stipulates for a Council of Guardians
composed of twelve members-six Islamic scholars and "six jurists,
specializing in different areas of law". A majority vote of the Council
membership is required to declare legislation passed by the National
Consultative Assembly as compatible with the shari'ah, as well as the
Constitution.
The fundamental changes that took place in the IRI after the
revolution led to the creation of many organizations and foundations.
The most important of these organizations are: (1) the Foundation for
the Oppressed; (2) the Reconstruction Crusade; (3) the Islamic
Revolution Housing Foundation; (4) the Foundation for the Affairs of
the Refugees of the Imposed War; (5) the Foundation for the Martyr of
the Islamic Revolution (the Martyr Foundation); and (6) National
Iranian Industrial Organization.
* Bank Markazi Jomhouri Islami Iran, Post-Revolution Economic changes, 1983/84, pp.
165-69, and 268-78.
273
1. The Foundation for the Oppressed
This organization was founded on June 16, 1976 with the aim of
improving living conditions for the rural population residing in much
neglected 60,000 or more villages and tribal centers in the country. Its
responsibilities include: (a) activities related to improvement in
production of farming and animal husbandry, (b) construction and
maintenance of public buildings, serving villages and tribal centers; (c)
construction and maintenance of roads in rural and tribal areas; (d)
provision and maintenance of water resources in rural areas; (e) health
service assistance, and (f) provision of cultural services and activities in
ural areas. The Reconstruction Crusade has been very effective in
providing the above services to rural and tribal areas and was formally
brought into the governmental structure as a full-fledged ministry in
1986. Before that time its financial resources were supplied through: (a)
special line-item in the government budget; (b) surplus budgets of
provincial governments; (c) revenues from its own projects; and (d)
financial contributions from urban and rural areas.
274
3. The Housing Foundation
275
and its people; and (d) help for reconstruction of the war-spoiled areas
after the war and the return of the refugees to their homes. Financial
resources for the foundation are provided by: (a) government budgets;
(b) gifts and other cash and in-kind contributions from the people as
well as agencies; and (c) income received from the foundation' s
investments in various projects.
(i) . In addition to oil, gas, railroads, utilities, and fisheries which had
already been nationalized, certain other industries such as
automobile manufacturing, metals, production, shipbuilding, and
276
airplane industries were also declared nationalized. The private
shareholders and owners of these industries were compensated
the net worth of their shares.
(ii) Large industries and mines, the owners of which had accumulated
great fortunes via their illegal relationships with the previous
regime, and many of whom had already abandoned their shares,
came under the possession of the government. The claims of these
owners were to be settled through legal channels.
(iii). The government also took possession of industrial units for which
the liabilities to the Government and to the banking system
exceeded their assets.
(iv) All other industries which did not fall into categories (ii) and (iii)
remained in the private sector.
The Foundation for the Oppressed has its own revenues and budgets
independent of the annual budget. The budget and the annual report is,
in fact, approved by the Muslim Leader. The Foundation's budget is not
only a burden to the Government budget but also due to its surplus
generating feature it does indirectly constitute to the well-being of some
economic classes of the country.
277
The Reconstruction Crusade of the early years after the revolution
has been. transformed, as noted earlier, to a full-fledged ministry.
Therefore, its expenditures show up in the annual budget which due to
common low efficiency of the public sector is a great burden.
However, it has been quite successful in some aspects of its
responsibilities.
Last but not the least the factor contributing to the growth of the
size of the government, was that the Majlis decided, for several years,
to treat the foreign exchange budget, in the same way as the regular
(Rial) budget. In order to properly use the controlled foreign exchange
278
revenues, it was claimed that the benefit to the public could best be
served through the establishment of centers to supply and distribute
commodities. To this end 10 different large centers were created by the
Ministry of Commerce in order to import and distribute various types
of commodities. Not only did these centers control the importation of
many items but also other items intended for import to the country
required the appropriate center's approval. Obviously, each center has
its own personnel and budget included in the said ministry ' s budget.
The end of the war and the removal of the internal as well as
external pressures from the economy has given a chance to the
authorities to give some thought to the problems created during the
war period. In order to understand the current state of the economy,
studies have been undertaken in various areas, all of which are in the
process of compilation; therefore specific decisions have rarely been
announced. However, information released through newspapers and
279
magazines and also official interviews are evidences of some new
developments. The most important of them crudely put include the
following, irrespective of priorities:
(a) To bring about one single rate for foreign exchange in order to
eliminate a great many distortions in different markets. Presently,
there ' are four major rates for foreign exchange, namely: official,
preferential, competitive, and black market rate. To give an
indication of the scale of distortion introduced by having multiple
rate of exchange it should be mentioned that the black market rate
is over 20 times higher than the official rate.
280
necessary to have this subsidy eliminated in a near future. Other
subsidies on necessities have also been kept in tact.
ENDNOTES
1. The table and the following example has been adopted form pp.
130-131 of C.V., Brown & P.M. Jackson (1982).
3. Op.cit.pp.145-6.
281
4. Following dates might be of some assistance if there should arise
confusion: Revolution happened on 11th February 1979; War began
on 21st Sept. 1980; the Iranian fiscal year starts on March 21.
5. Fourth measure will be that chosen by those who wish to argue that
the public sector is too large.
BIBLIOGRAPHY
282
Harcourt, G. C., "The Quantitative Effect of Basing Company Taxation
on Replacement Costs", The Social Science Imperialists (Selected
Essays); Routledge & Kegan Paul; London (1982).
70mn210-: a
283
11
EFFICIENCY OF THE ISLAMIC APPROACH TO
EXTERNAL DEBT MANAGEMENT IN NORTH AFRICA
AND THE MIDDLE EAST
I. O. TAIWO*
INTRODUCTION
Most less developed countries (LDCs) have been battling with the
debt crisis which emerged in 1982 following an announcement by
Mexico, a major debtor country, that she would not be able to service
her external debts. This crisis cuts across ideological leanings, various
religions and geographic groups. Table 1 shows the magnitude of the
external debt problem facing LDCs in general and North Africa and the
Middle East in particular. As at 1982, when the debt crisis erupted, all
LDCs were indebted to the tune of about $752.00 billion; their debt-
export ratio was 160.3 per cent; and their debt service ratio was 15.4
per cent. As for North Africa and the Middle East, the external debt
stock was about $68.00 billion, while the debt-export ratio and the debt
service ratio were 140.6 per cent and 18.3 per cent respectively.
The debt crisis has become worse since 1982. As at 1988, the latest
year for which reliable information is available, LDC external debt
stock amounted to about $1,121.00 billion; and their debt-export ratio
and debt service ratio had risen to 201.2 per cent and 26.7 per cent
respectively. A similar fate befell North Africa and the Middle East, as
their external debt stock had increased to about $119.00 billion, and their
debt-export ratio and debt service ratio had risen to 296.0 per cent and
38.4 per cent respectively.
285
North Africa and the Middle East is not the most indebted
geographic group,' but from Table 1 it is clear that this group's debt-
export and debt service ratios are above average, implying that the debt
crisis faced by North Africa and the Middle East is sufficiently serious.
However, this is not a sufficient reason for focusing on this geographic
group. Our focus on the group is based mainly on the fact that this
paper is about an evaluation of the Islamic approach to the debt crisis;
and North Africa and the Middle East is comprised of a great number,
and in fact the largest concentration of Islamic countries, where policy
measures based on the Islamic doctrine can be more readily put into
practice.
The main purpose of this paper is to assess the role and viability of the
Islamic approach to the debt crisis. This is done by first tracing the
causes of the debt crisis, with the aid of an econometric model; and then
assessing the extent to which the Islamic approach, if adopted, can
influence the major causes of the debt crisis, for the better.
286
TABLE 1
Source: The World Bank, World Debt Tables, 1988-89 Edition, various volumes; and 1989-90 Edition, First Supplement.
There are ten countries in North Africa and the Middle East which are
listed by the World Bank as having a debt problem and which have
reported data on their debt situation. In this paper, we consider all of
these countries, except one, namely Lebanon. The reason for excluding
Lebanon is that not all the data needed for the estimation of our model
are available for this country. The remaining nine. countries that
constitute our sample are Algeria, Egypt, Jordan , Morocco, Oman,
Syria, Tunisia, Yemen Arab Republic, and Yemen Peoples Democratic
Republic.
287
2. THE MODEL
288
gradually proceed from the periphery to the center of the world
economic system, and the relationship between economic development
and debt crisis would be a negative one. Secondly, we have the case in
which development is financed by debt and the system is riddled with
leakages such that we end up with a positive association between debt
and development. Lastly, we have the case in which development is
intended to be financed by debt, but the receipts are diverted to non-
developmental issues. In this case, we end up with a negative
relationship between debt and development.
The domestic price level plays at least two important roles. First, the
different between the domestic price level and export, prices serves as a
measure of export competitiveness which affects the supply of exports.6.
The, higher. this. differential the lower the supply of exports.
289
Secondly, the differential , between the domestic price level and the
foreign price level affects the demand for imports and exports. The
higher this differential the greater the demand for imports and the
lower the demand for exports. Because export prices are already
incorporated into the terms of trade dealt with in the preceding
subsection, the latter differential is emphasized here.
Another reason that has been proffered for the debt crisis facing
LDCs is the increase in the cost of borrowing in the international debt
market.7 Up to the mid 1970s, most of these countries borrowed at
concessionary rates from official creditors, and interest rates were low.
Thereafter, most LDCs were compelled to borrow largely from private
creditors and at market rates. Consequently, the nominal interest rate
increased, especially up to 1981. Between 1970 and 1981, the ratio of
concessionary loans to total outstanding debt decreased from 55.8 per
cent to 26.3 per cent, and nominal interest rate increased from 5.3 per
cent to 11.1 per cent.8 However, other considerations influencing
market forces have tended to push down the nominal interest rate since
1981. In this paper, we shall focus on the real cost of borrowing which
is the nominal rate minus the rate of inflation. We expect that an
increase in interest rate will, ceteris paribus, reduce the demand for debt
but increase the difficulty with which contracted debt can be managed,
and vice versa. The overall effect can go either way.
290
of debt maturities, and defective investment incentives leading to an
industrial sector that is highly dependent on foreign inputs. Not all of
these lapses are measurable, and we do not have adequate time series
data for others. We then limit ourselves to two measures for which
reliable information is available, namely the average debt maturity and
the degree of openness of the economy, measured by the ratio of
imports of the GNP.
EDT
EGS = f(LED, TOT, PR, INT, MAT, DOP, u) (1)
291
PR = Relative price level, measured by the ratio of the domestic price
index Pd, suitably adjusted to the exchange rate (e), to the
foreign price index (Pf);
3. METHODOLOGY A)
Estimation Method
292
and low capacity utilization; and the more likely is import restriction.
The other variables are not so influenced.
In view of the above, we adopted the two stage least squares (2SLS)
method in preference to the ordinary least squares (OLS) method. In
the first stage, we regressed the stochastic regressors on their lagged
values as well as the exogenous variables of the model. The second
stage is comprised of a regression of the dependent variable in equation
(1) on the predicted values of the stochastic regressors as well as the
exogenous variables of the equation. We corrected for autocorrelation,
where present, using the Cochrane-Orcutt method.13
B) Evaluation Methods
C) The Data
We used time series data for the period 1970-87 to estimate the
regression equations. 1970 is the earliest year, while 1987 is the most
recent year, . for which a comprehensive debt and other data are
available. Our data were obtained from two principal sources, namely
(i) The World Bank; World Debt Tables, 1988-89 and 1989-90
Editions, various volumes; and (ii) IMF; International Financial
Statistics,, various issues.
293
expressed in decimals. All price indices have a base year of 1985 = 100,
and average debt maturity is in years.
4. EMPIRICAL RESULTS
The terms of trade also have a positive impact on the debt crisis in
six of the countries sampled, and a negative impact in the others. Two of
the positive impacts (those of Oman and Syria) and three of the
negative impacts (those of Algeria, Morocco and Tunisia) are
significant, so that the majority of the countries sampled are
significantly affected by their terms of trade. Like the case of the level of
economic development, however, the direction of the impact of the terms
of trade on debt burden is not unique.
Both the relative price level (i.e. the ratio of the domestic price level
vis-a-vis the foreign price . level) and cost of borrowing exert a positive
impact on the debt crisis, implying that both domestic inflation and
294
high interest rate are bad from the viewpoint of the debt crisis. The
relatives price level and the cost of borrowing have a significant impact
in eight (the exception being Yemen P.D.R) and five (the exceptions
being Jordan, Morocco, Tunisia and Yemen Arab Republic) of the
countries sampled, respectively.
The average debt maturity has a positive impact in only two of the
countries sampled. Consequently, for most of these countries, a longer
debt maturity eases the debt burden, which conforms to our a priori
expectation. However, only one of the positive impacts (that of Egypt)
and one of the negative impacts (that of Morocco) are significant,
implying that for most of the countries sampled, the maturity structure
of the debts is not a major factor in the debt crisis.
295
TABLE 2
EMPIRICAL RESULTS
Explanatory variables
Country LED TOT PR INT MAT DOP R2 (in %)
d and F
Algeria 1176.57 -3.04 40.95* 9.77 -11.73 577.38 R'=95.0
(237) (-299) (230) (228) (-1.77) (3.25) d =214
F=34-8
Egypt -219228 0.39* 308.27 6.17 7.59 -121.39 R'=98.7
(-1.57) (0.62) (4.71) (222) (4-1) (-1.28) d =1.89
F =143-1
Jordan 660.51 0.48* 416.92* 223 0.65 -15224 R2=97.3
- (1.62) (1.16) (226) (0.94) (0.52), (-275) d =1.92
F =66.4
Morocco 5087.22 -0.71 25.57 1.27* -5.05 23-9 R'=98.5
(4.72) (-3.53) (5.2) (0.36) (-3-91) (0.13) d =202
F =216.2
Oman -11214 0.51* 228.85 247* -1.40 -50.48 R=98.5
(4.98) (3.79) (7.85) (5.24) (-207) (4.01) d =1.91.
F =348.9
Syria 54286 1.52* 5.91 5-52* -3.73 16231 R'=95.4
(236) (3.02) (277) (246) (-1.47) (-1.03) d =21
F =37.6
Tunisia 260.01 -1.76 _ 199.23* 1.42* -1.94 383.04. R=98.9
(0.36) (-261) (4.43) (0.68) (-1.88) (3.91) d =2.12
F =163.4
Yemen 584.26 0.43 21.36 1.20* -0.008 -148.5 R'=98.0
Arab (1.02) (0.63) (8.37) (0.31) (-0.007) (-224) d =2.07
Rep. F =65.7
Yemen -0334.81 0.81 580.16* 30.51* -1.91 915.84 R=81.9
P.D.R. (-1.06) (0.43) (1.26) (239) (-0.43) (1.79) d =2.12
F =8.3
296
By and large in the majority of the countries sampled, domestic
inflation vis-a-vis inflation abroad, and the high cost of borrowing are
major causes of the debt crisis. In some, but not most, of these
countries, the debt crisis has been fuelled by the level and/or style of
economic development, a deterioration in the terms of trade, debt
maturity structure and import liberalization.
297
of partnership in which the rights of the partners, are not necessarily
equal in terms of, e.g. share ownership and profit sharing. The
institution of involves the provision of capital by one or more partners,
and the work done by the other(s). Profit will be shared according to an
agreed ratio, but in the event of a loss, partners lose in proportion of
their capital share in the total investment. Islamic banking is then
modelled in a tripartite relationship consisting of two tiers. The first tier
involves depositors and the banks, while the second involves the bank
and investors.
298
Secondly, we have the zakat and other taxes which act as in-built
mechanisms for redistributing income and wealth, and for controlling
spending. Last, but no least, we have those measures which are aimed at
combating cost-push inflation such as linking of wages with productivity,
subsidies on certain inputs and direct control method.
299
Secondly, Islam abhors all riba on sales, whether at the domestic or
international levels. This has a lot of implication on the relative price
level turning to Table 2, we find that a reduction in the. domestic price
level would alleviate the debt burden of all the countries sampled; and
the relief is significant for all of these countries except Yemen P.D.R.
For instance, a one percentage point reduction in the relative price
level would reduce Jordan's debt-export ratio by 4.2 percentage points,
and that of Oman by 2.3 points.
The abolition of riba on sales can also affect the terms of trade
depending on whether riba on imports departs from that on exports, or
not. If riba on imports exceeds riba on exports, and -all riba is
abolished, then the terms of trade would improve, which in turn affects
the debt burden. Table 2 shows that an improvement in the terms of
trade would significantly alleviate the debt burden of Algeria, Morocco
and Tunisia; and it would worsen it in the remaining countries, the
impact being significant in only Oman and Syria. For instance, a one
percentage point improvement in the terms of trade would reduce
Algeria's debt-export ratio by about 3.04 percentage points, and worsen
Oman's by about 0.51 points. It can therefore be concluded that there
are wide cross-country differences in the role which the Islamic
approach can play to alleviate the debt crisis through the terms of
trade.
By and large, the Islamic approach can be used to check the debt
crisis facing North Africa and the Middle East if the emphasis is on
300
price and interest rate reduction. But if the emphasis shifts to other
variables such as import control and the terms of trade, the evidence will
be divided; some countries would be worse off, while others may gain.
For example, import compression and an improvement in the terms of
trade would alleviate Algeria's debt burden, but worsen Oman's. Even in
countries where the Islamic approach is favorably disposed to work, we
should not expect smooth sailing and we now turn to the constraints.
The debt crisis confronting North Africa and the Middle East is part of
a global crisis faced by most LDCs. This crisis can be accounted for by
several factors, especially the level of economic development, the terms
of trade, the domestic price level vis-a-vis the foreign price level, cost of
borrowing, and domestic policy lapses measured, for instance, by the
average debt maturity and the degree of openness of the
301
economy. The Islamic approach to economic issues has -a lot to say
about each of these factors and can therefore be used to influence them
all. Islam abhors all illegitimate excesses, including interest charging
and extortionist trade policy; it also abhors wasteful spending; it
discourages deficit financing; and it has an integrated approach to
human development. It is then clear that the Islamic approach, if
adopted, can ameliorate the debt crisis facing North Africa and the
Middle East, and some other countries as well. However, there are
problems which can stymie a full scale adoption of this approach. They
include polarization within' the Muslim world, and economic
dependence on the developed West. We recommend that:
1. See the World Bank; World Debt Tables, 1989/90 Edition, pp. 4-
17.
2. See Yima Sen (1989); "The Political Factor in the Third World
Debt Crisis", in Olusanyn, G.O. and Olukoshi, A.O. eds, The
African Debt Crisis, Nigerian Institute of International Affairs
Monograph Series,. No. 14, p. 105.
302
3. See Ekpo, A.H. (1989); "The Debt Crisis and Africa's Balance of
Payments Problems", in Olusanya and Olukoshi, op. cit, pp.. 30-
48; Ihonvbere, J.O. (1989); "The African Debt Crisis: Responses
and Options", in Olusanya and Olukoshi, op. cit, pp. 81-91; and
Nau, H.R. (1988); "The Debt Crisis: Putting Policy Before
Finance", Economic Impact, No. 65, pp. 45-48.
8. See the World Bank; World Debt Tables, Vol. 1, p. 3 and Vol.
III, p. 3.
11. For the treatment of the ADL approach see Hendry, D.F., Pagan,
A.R. and Sagan, J.D. (1984); "Dynamic Specification", in
303
Griliches, Z. and Intrilligator, M. eds., Handbook of
Econometrics, Vol. 2, Amsterdam, North Holland.
304
19. For some of these dissenting views see, e.g. El Gousi, op.cit, pp.
138 and 141.
305
12
THE SURVIVAL AND DEVELOPMENT STRATEGIES
OF THE MINORITY OF
NAIROBIAN MUSLIMS IN NAIROBI
MOHAMMED S. MUKRAS*
1. INTRODUCTION
307
employment in the formal and informal sectors is very low, as a result
of which they are faced with low and uncertain incomes. This further
implies that their access to the formal labor and formal capital markets
as well as the formal social security system is seriously limited. The sum
total of all these factors is that the welfare situation of this sub-set of the
population is very precarious.
The first part of this paper is introductory. The second part provides
definitions, and thereafter, sections three and four present empirical
evidence of interhousehold transfers and theoretical foundations.
Section five discusses the econometric model which is used to generate
the results presented in section six. The emerging conclusions are
covered in section seven.
308
2. DEFINITIONS
The survival network plays the important role of facilitating the flow
of transfers among individuals, household and community based
organizations. The term transfer is, in this context, used to refer to the
receipt or giving of one or more units of transfer by an individual, a
household, or a community organization. The units of transfer in
question can either be money, goods, or services, and when such
transfers flow among household or community organizations, they are
respectively referred to as inter-household and inter-community
transfers.
309
such income transfers constitute an important survival and development
strategy of poorer families.
TABLE 3.1
Source: Knowles, J-C- and Anker R-, 1981, "An Analysis of Income Transfers in a Developing
Countries: The Case of Kenya", Journal of Development Economics, 8, p-210-
310
525,000/= were remitted as transfers in the year 1988. Table 3.2 gives
the breakdown of these transfers into the three main functions: survival,
development and social maintenance.10
TABLE 3.2
4. THEORETICAL FOUNDATIONS
311
The survival network embraces' Muslim Brothers who are members of
the nucleus family, the extended family as well as neighbors and
friends. Common religion, spatial and social proximity, and a sufficient
degree of trust are important factors that create an enabling
environment necessary for reciprocal transactions within the survival
network.
From the point of view of the economist, this survival network can
be looked at as some form of an informal insurance institution catering
for. the economic welfare of member households. The close ties existing
among members, together with the degree of trust and the effective
access to information about the overall conduct of the members gives
this system of informal insurance a comparable advantage over a
formal insurance scheme. The main reasons for this relates to the usual
problems faced by the formal insurance schemes, such as moral
hazards, adverse selection, and deception which are -in this case taken
care of by the overall proximity of member households.
Y = Y B + Y NB (4.1)
C = C B + C NB (4.2)
312
attempt to satisfy its basic consumption needs. These three scenarios are
given by (4.3), (4.4) and (4.5) respectively.
Y = YB (4.3)
Y > YB (4.4)
Y < YB (4.5)
Y - YB > (4.6)
313
Such protection against the impacts of household income deficits is
made possible through the re-distributive role of the network. Sufficient
resources are extracted from the surplus household in order to meet the
deficits experienced by the deficit households.
TH = f(xi, E) - (5.1)
i = 1, 2, ..., n
314
E = stochastic term
Both the linear additive (5.2) and log-log (5.3) functional forms were
estimated.
A = constant term
Ei = stochastic term
X1 = explanatory variables
e = stochastic term
i = 1,2,...,n
Since the performance of the log-log form was found to be better, our
results here are based on this functional form. The performance of these
two functional forms were compared on the basis of two statistical
criteria: the statistical significance of individual parameter estimates;
and the goodness of fit of the model. Overall, the log-log form was
performed better.
315
5.3 A Priori Expectations
316
(vi) Ownership of Property (PR)
It is assumed that the more pious and generous a person is, the more
the person will feel obliged to remit transfers in an effort to
improve the well being of members of the network.
6. DATA
7. RESULTS
317
TABLE 6.1 REGRESSION RESULTS
R2 = 0.48
n = 267 Households
Results on the table suggest that the regression model was able to
explain 48 per cent of the variations of the dependent variable. In
addition, apart from the coefficient of the explanatory variable
representing the "number. of children", the sign of all the other
coefficients are in conformity with a priori expectations. The coefficients
are all found to be statistically significant at a level of 5 per cent.
318
8. CONCLUSION
ENDNOTES
319
1976, "The Structure of Sociability; Urban Migration and Urban
Ties in Kenya", Urban Anthropology 5 (pp. 199-223).
12. Oberai, A.S. and Singh 'H.k.M., 1980, 'Migration,' Remittances and
Rural Development: Findings of A Case in the Indian Punjab"
International Labor Review, Vol. 9 N0.2.
320
Section IV
1. INTRODUCTION
"
Development" is an ideological concept contained in the capitalist
paradigm. Since capitalism has dominated the world economy since the
eighteenth century, (material) progress has been given top priority in all
spheres of life. Beginning from the late seventeenth century many
Ottoman and other Oriental observers began investigating the secret of
the material progress realized in the West. The term in vogue was
"civilization" during the nineteenth century; and it was, in a sense,
replaced by "development" in the twentieth. Europeanization,
Westernization, Modernization all are other appearances of the one and
same phenomenon: material development, based on a secularized
world-view. The more value-free term for this process may be
"industrialization". Here I am not in a position to discuss the
appropriateness of a term like "Islamic development". Rather, I shall try
to outline an 800 year experience of the Anatolian Muslim peoples from
the XI to XIX (H. VI to XIV) centuries, in economic terms, and make
an attempt to derive certain implications for current theoretical and
practical experience.
323
Eastern (especially, Persian) and Byzantium influences can be observed in
certain aspects of the Ottoman institutions. Particularly in monetary and
fiscal systems, we can say that the Ottomans were as flexible as the early
Islamic societies faced with local traditions. In a sense, the Ottomans
were traditionalist, not `progressive-developmental'. Change was mostly
considered as a sign of decay, its remedy being a return to the Eternal
Law.
(In the Ottoman Archives, we have now more than 100 million
documents, illuminating many aspects of lengthy history politically,
socially as well as economically. My paper will be based on first-hand
research of relevant documents in these archives).
324
Until mid-eighteenth century the Ottoman economy was one with
high production and a favorable trade balance. 2 This high production
supported a flow of agricultural as well as industrial exports to
Europe.3 After the mid-eighteenth century, however, when serious
under-production began to emerge, Western capitalism established its
dominance over the Ottoman economic structure. The financial
structure of this system of high production and social welfare should
be studied first.
Public production and the share of State out of this production may
be studied under three headings:
The treasury was of two kinds: Internal and external. The former
covered the sultans' private revenues and expenditures. But, it was also
a source of credit for the external treasury. This second one was the
responsibility of the Sadr-i azam (modern Prime Minister) and the
Defterdar (modern Minister of Finance); thus it was the State
Treasury. With the introduction of Reforms in the late eighteenth
century (called Nizam el Cedid), there had been a shift to a multi-
treasury system. But after Tanzimat, the one-treasury system was
resumed.
325
The main principle in Ottoman finance was to adjust expenditure
according to revenue. As a corollary to this principle, a logic, of
subtraction is observed in the Ottoman accounting (and budget)
registers. That is, if revenue has come to exceed expenditure, the
surplus is retained in the Treasury. In short, a surplus budget was the
target of the Ottoman financial mind.
Major revenue sources in the budget are muqataa, jizyah and avariz
revenues. The muqataas, whose original forms were seen during the
Abbasid reign5 can loosely be defined as state enterprises run by the
private sector. They may assume monopolistic properties. Moreover,
the collection of a revenue share pertaining to the state can be
organized in muqataa form. Prominent examples are customs, mints,
mines and alum factories. The share of muqataa revenues in the
budgets oscillated between 24-40 per cent.
Muqataas were run by three main methods: iltizam, emanet and since
late seventeenth century, malikane. With the muqataa method, without
shouldering the burden of establishing a separate organization for tax
collecting, the state could determine these revenue sources and
transform them into muqataas, and then leave the task to private
enterprise. We see the muqataas in the official registers for
demography and taxation only in the cities. But, the lands belonging
directly to the Treasury were also run as muqataas. The agricultural,
commercial and industrial revenues consolidated under the title of
`muqataa revenues' in the Ottoman budgets and their respective rates
can be observed through the following table:
326
Year Rates (%)
1103/1691-2 51.7
1110/1698-9 37.7
1113/1701-2 41.6
1114/1702-3 38.1
1122/1710-1 42
1147/1734-5 29.4
1159/1146-7 40.8
1161/1748 55.3
327
Because of warring conditions, great difficulties were experienced in
the operation of the muqataas with iltizam method, leading to unstable
ups and downs in muqataa revenues. When peace was reached, new
measures were taken and revenues expanded.7
The emin (i.e. the entrusted government official) would not undertake
any responsibility concerning the amount of revenue and contested the
indemnity allocated to. him by the government. They were expected to
protect both the farmer and the land.8 The method of emanet was
preferred to iltizam in the-Ottoman fiscal tradition.
328
the pressure of financial crisis, the shortening of the iltizam periods
worsened the situation. The tax-farmer did not care to provide the
peasants with seed, draught-animal, and other `inputs' of agriculture.
With the malikane system, the social security element of the classical
timar system was to be re-substituted. In case of success, the reaya
(subjects) and the land would be protected. Agricultural productivity
would increase and thus an additional financial opportunity for
expenditures would be created. With this thinking, the new malikane
system was put into practice, first in the regions of Syria and Southern
Anatolia near to Egypt where life-long tax-farming had been a dominant
form for a ling time. The system was effective as one of the most
important financial and economic institutions of the Ottoman Empire
until the so-called Tanzimat period (1840's).
The revenues extracted in advance form the malikane system did not
reach a modest share of 3 per cent in the total budget revenues.
Moreover, the system was, not efficient in protecting the people working
in it.
The system had spread out to all the activities as well as the
provinces where the State had a tax base. However, it neither revived the
security provided by the timar system nor avoided the inconveniences
inherent in the iltizam. The chief reason for this failure was that the
malikane owners started to run their enterprises on the basis of tax-
farming, doubling the burden of the land and the working people.9
Jizyah is the capital tax the Islamic state imposes on its non-Muslim
subjects. It symbolizes the sovereignty of the Muslims, thus acquiring
the character of an `ideological' tax. It is the price paid by the non-
Muslim subjects for their security guaranteed by the Islamic state.10 The
exceptions to this capital tax are men of religion, children, those under
state service and the disabled. Those under the jizya obligation were
separated into three categories according to their wealth. The J i z y a h of
Egypt, Baghdad and Basra provinces were included in the revenue
surpluses (irsaliye) sent to the central government. Moreover, the lump-
sum jizyah of the provincial states of Eflak, Bogdan, Erdel, Dubrovnik
329
(today partly contained in the lands of Hungary, Romania and Yugoslavia)
were significant. The share of total jizyah in the budget revenues was
around 23-48 per cent and began to show increases after a reform in
1691.11
The avariz taxes, a part of which were collected in kind, considered the
tax-payers as a collectivity and made them responsible for a definite
amount, while muqataa, jizyah and other taxes were imposed upon
producers and single tax-payers. Avariz was imposed upon communities.
The unit was an avariz household. These `special' households consisted
mainly of three to five real households. For the tax-paying unit to pay the
tax, they had to be utilizing a certain dwelling (land) at the place of
taxation. Accordingly, those living in villages and those in the cities were
registered if they were actually in possession of land and a full-time trade,
respectively.13
Avariz taxes also included a list of those exempt who were either
individuals or collective groups. Those under military, religious or
financial services together with the disabled people, were exempted from
avariz taxes individually.14
Major avariz taxes included avariz akcesi and payment for nuzul, sursat
and istira. The first is a fixed tax, the amount of which increased
330
parallel to the devaluation of money through time, collected on the basis
of avariz households (i.e. several real households).
Nuzul was the provision of various foodstuffs (flour, barley etc.) for
the Imperial army when it was on the way to a war. Sursat is an
obligation on the reaya (subjects) to provide for the military certain
foodstuffs and fuels at a price determined by the government. In istira,
we see the same obligation at market prices. All these were transformed
into cash obligation as time passed.
2. Budget Expenditures
331
through private persons and especially foundations (waqfs) which were
mostly exempt from taxation and other financial responsibilities."
During the second had of the eighteenth century (in 1775), with the
implementation of a bond-policy, large muqataa revenues were sold to
the public in an effort to generate fresh resources for the State. This
bond policy , (the esham system) is one of the original examples of
today's revenue partnerships (widely used in post-1980 Turkey). The
first paper money was introduced in 1839, thus the Ottoman economy
began formally to assume a capitalistic character. In this new era,
public expenditures were financed also through the non-Muslim Galata
bankers, the mushrooming moneylenders of Jewish and Greek origin.
332
The first foreign borrowing was realized in 1854, during the Crimean
war with the Russians. The long resistance of the Ottoman State to
foreign borrowing is well known. They knew that an Islamic economy
was one based on self-financing. However such resistance was
undermined in an era of `Westernization' which had a totally different
concept of economy largely based on the utilization of credits. But, the
irrational use of the credits (mostly for wars or domestic consumption)
forced the Ottoman government into a state of bankruptcy in less than
25 years.20
333
For example, they provided the farmers with seeds, agricultural animals
etc. 'in order to increase production. For all land to be cultivated, they
contributed financially to the farmers. This economic security and
solidarity was the main factor behind high agricultural produce.21
The system was so organized that the sipahis (or timar owners) were
not able to form a landed aristocracy. (This attitude was carried over to
prevent the formation of an industrial aristocracy as well). During the
sixteenth century, the share of timar in overall public finance was
around 35 per cent. However, with the monetarization of the economy
throughout the subsequent centuries, this share sharply declined.22
334
4. FINANCING OF PRIVATE PRODUCTION
A. Sources of Credit
Though not encouraged, savings were the main credit source. High
army officers (pashas), court officers, foundations and their security
vaults were utilizing the money they had in certain forms. The
merchants were collecting money capital through the mudharabah
system and returning a certain share to the owners of that capital.25
335
There were persons and foundations who met the credit needs of
bid businesses and the craftsmen. There is detailed information on this
point in the Legal Registers. In this system, we see prominent
international traders as well as able bankers use third parties for
money payments and disbursements on their behalf.26
336
uses its own capital, rather than credit, as the base for profit-earning
activities.
C. Financing of Agriculture
337
agricultural activities concerning the shares of the labor (tenant) and the
proprietor was called muzaraah and based on the principle of the former
giving a portion of his produce to the latter. 36
338
old-age, sickness, or disabilities. There were certain state payments for
retirement or body injuries during official work. The professional army
members (Janissaries) had their own social security fund (orta sandigi)
which was operated as a credit mechanism, likewise, the guild members
had their own funds (esnaf sandigi), the urban and rural dwellers had
their avariz sandigi, all being operated on a credit basis. These latter had
the status of foundations (waqf). 39
CONCLUSION
339
ENDNOTES
1. Muhimme, 3, pp. 6; 5, pp. 269; 6, pp. 27 and 613; 10,
pp.116; 12,12, pp.599; 73/1143 and 1294.
5. Inalcik, 1959.
6. Sahillioglu, 1963.
340
18. Tabakoglu, 1985, pp: 177-197.
19. Muhimme, 98, pp. 10/27; 119, pp.13; Kepeci, No.1678, 2000,
2015; Zubde, v. 110 a-b; Rasid, I, 496; Silandar, II, 263.
341
37. Silahdar, Nusretname, pp. 240 a.
REFERENCES
I. Documents
C. Published documents
342
Akdag Mustafa (1974) Turkiye'nin ictimai va iktisadi tarihi, 2 Vol.
Istanbul.
Barkan Omer L. (1953) "H. 933-934 (M. 1527-1528) mali yilina ait
butce ornegi" Iktisat Fakultesi Mecmuasi, Vol. 15, pp. 259-329.
343
- (1978) The Ottoman Empire: The classical age 1300-1600, trans.
Norman-itzkowitz-Colin Imber, London.
344
14
PUBLIC BORROWING IN EARLY ISLAMIC HISTORY:
A REVIEW OF SOME RECORDS
M. NEJATULLAH SIDDIQI*
INTRODUCTION
It is in this context that scholars have felt the need to look back and
see what lessons can be learnt from the Islamic heritage. Did the Islamic
state in the. past borrow? If so, why and how i.e. on what terms? Were
there any alternatives to borrowing? With these and related questions
one can explore the historical records of the many governments,
spanning vast regions of the globe, over the long period of fourteen
hundred years. This is, however, a very ambitious project requiring
extended teamwork. Yet another problem with such study is the Islamic
authenticity of what the Muslim rulers have been doing all these
centuries in all these -regions. Authenticity naturally belongs to the
decisions and 'actions of the. Prophet. The consensus of the community
has extended -this authenticity to the period of the four pious Caliphs
also, i.e. to the policies of the Islamic state till the year
345
40 after hijrah which can serves as examples of Islamic policy making
and, taking into consideration other relevant factors such as need, scope
and perceived function of borrowing etc., guide Islamic statecraft in the
modern period. As regards the other Muslims rulers, their decisions and
policies have to be judged on the criteria of Qur'an and Sunnah. In the
context of public borrowing, the most important criterion on which the
legitimacy of public borrowing by Muslim rulers has to be judged is
prohibition of interest. This means that if an incidence of borrowing on
the basis of interest by a Muslim ruler is reported it has to be regarded as
an aberration rather than a -precedent, generally speaking. This does not
mean, however, that recording and analyzing such cases is of no use to
Islamic economists. There is a possibility that such a course of action was
resorted to under `extreme necessity' (idtirar). In that case it becomes
possible to condone the action despite the fact that it can not be a
precedent for others, being a violation of shari'ah. While a judgement in
such cases may be beyond the scope of an Islamic economist's vocation, it
is his job to study these cases and analyze the causes and consequences as
befits an economic historian. In fact, such a study on his part not only
facilitates proper `judgement' on such matters, it is a necessary
precondition to it.
This study covers only the periods of the Prophet, the four pious
Caliphs, the Umayyads and that of the Abbasids till the year 333
A.H./944 A.D. after which real power passed, in succession, to the
Buwaihids and the Seljuks, and this continued till the sack of Baghdad by
Holaku in 656/1258 which put and end to the Abbasid Caliphate at
Baghdad.
Our. primary task has been to record the reported cases . of borrowing
by the ruler for public purposes. Then we look into such details as the
need and circumstances which prompted borrowing, the
346
amount borrowed (in cash or kind) the identity of the lender and the
terms and conditions attached, if any. We also inquire whether the
lending was voluntary or the ruler had to coerce the lender. If available
we also look at the details of the repayment of the loan. Having noted
these features we try to analyze these cases in relation to their causes
and consequences. Finally we ponder over the lessons that can be drawn,
if any.
A serious handicap faced by the writer has been the absence of any
other study on the subject which could help in posing the questions or
looking for the answers. This should be regarded as one of the reasons,
should the discerning reader find the present study deficient in some
ways.
Our search has so far lead us to six cases of public borrowing by the
Prophet which are reported below. A possible seventh case will also be
noted in the end.
347
"
It is reported of Zaid that he heard Abu Salman saying that
Abdullah al Hawzani told him `I met Bilal, who used to give the call for
prayers for the Messenger of Allah, peace be unto him, at Halab. I
asked him to narrate about the expenditures of the Messenger of Allah,
peace be unto him. He said `He did not have any thing (to spend).1 I
used to look after it on his behalf ever since Allah called him to
prophethood till his death. It was his practice that when a man came to
him as a Muslim and he saw him in need of clothes he would order me
and I would go and borrow and buy a cloak for him, clothe him and
feed him. This continued till a person from amongst the polytheists
accosted me and said: `O Bilal, I have enough resources so you do not
borrow from any one other than me ' . I did accordingly. One day it so
happened that, as I made ablution and rose to give the call for prayer,
that polytheist came along accompanied by a group of traders. When
he saw me he called, O Abyssinian! I said, yes. He presented a grim
face to me and addressed me harshly, saying: `Do you know how many
days are left between you and the (end of the) month (when repayment
is due)?' Bilal says, `I told him it is near'. He said, `it is only four days
between you and it, after which I will capture you against what you
owe and return you to grazing sheep as you used to do before ' . I felt
what people feel (on hearing such a threat). When I had prayed the night
prayer (i.e. isha) and the Prophet, peace be unto him, retired to his
family, I sought permission to see him. He admitted me in. I said "O
Messenger of Allah, you are more dear to me than my father and
mother, the polytheist from whom I used to borrow has said this and
that and you do not have the means to repay him, nor do have I. He is
going to humiliate me. Please permit me to abscond to one of these
tribes (outside Medina) who have accepted Islam till such time as
Allah provides to His Messenger, from out of which provision he can
pay back the loan'. I came out (of the Prophet' s place) till I reached my
home and put in readiness my sword, socks, shoes and shield at the
head of my bed. When the first lights of dawn appeared on the horizon
I got ready to go. Suddenly I heard a man calling. O Bilal! you are to
report (immediately) to the Messenger of Allah, peace be unto him. I set
off till I came to him. What I saw there were four camels resting with
their loads. I sought permission to see (the Prophet). The Messenger of
Allah, peace be unto him, told me `cheer
348
up, Allah has sent what you can pay back your loan with! Then he
asked `Did you not notice the four camels in rest?' I said, `I did'. He
said, You have the camels as well as their loads. They are laden with
clothes and food which have been presented to me by the chieftain of
fidak. Take possession of them and pay off your debt'. "I did
accordingly .... "2
This incident must belong to the sixth year after the hijrah, or the
period after that, since Fidak was subdued during that period.
The one important point emerging from this report is the primacy
attached to need fulfillment. It was regarded by the Prophet to be a
purpose important enough to borrow even from non-Muslims and
without any definite means of repayment in sight.
"...Zaid bin Si'na said: `When the due date of the loan was only two
or three days away the Prophet came to attend the funeral procession
of a man from the Ansar, accompanied by Abu Bakr, Umar, Usman
and some other Companions. When, after saying the funeral prayers,
he came near a wall to sit by it I came to him and gave him a very
hard look. I took hold of his shirt and the outer robe and said, "Pay up
to me, O Muhammad! By God what I know about default on part of
you children of Abd al Muttalib is based on my direct contacts with you
people!" Then I looked towards Umar whose eyes were moving in his
face like the rotation of the heavenly bodies. He looked towards me
and said, "O jew!, you do this to the Messenger of Allah? By him Who
sent him down with truth I would have struck your head with my sword
but for what I fear to miss'. (Zaid) said, `the Messenger of Allah, peace
349
be unto him, was calmly looking at Umar and smiling. Then he said,
`Myself and he are in need of something -else (from you), that you
advise me to pay back gracefully and advise him to ask for repayment
politely. O Umar go and pay back what is due to him and give additional
twenty sa' of dates against your threat to him'. Then (Zaid, son of Si'na)
narrated how he embraced Islam."3
The phrase `till our dates arrive' most probably refers to the annual
share from Khaibar out of which a fifth was earmarked for family of the
Prophet and rest for other beneficiaries. These shares would naturally be
channelled through the public treasury. That the dates lent by Khawla
were to be repaid out of the dates coming from Khaibar leaves both
possibilities open: It could be paid out of the fifth assigned to the
Prophet's family in which case the loan would have been a private loan.
Equally possible, it could have been paid out of the part earmarked for
other beneficiaries in which case the original debt must
350
have been incurred in order to meet the urgent needs of the same
beneficiaries.
As distinguished from the first two cases, in this case the lender
was a Muslim. The second lender whose lending made possible the
repayment to the first lender was also a Muslim.
`Abu Rafi' reports that the Prophet, peace be unto him, borrowed
a small camel from a man. Then some camels from those collected as
zakat were given to him and he asked Abu Rafi' to pay back the man
the camel (owed to him). Abu Rafi' came back and said he could find
only better camels (older in age) who had their fourteenth grown. He
(the Prophet) said, `give it to him. The best among people are those
who are good at paying back."
The main point that emerges from this case is the propriety of'
borrowing for public purposes when there is a definite source of
revenue in sight. The Prophet borrowed for need fulfillment intending
to repay from zakat to be realized in the future.
351
"When the Messenger of Allah, peace be unto him, decided to march
up on Hawazin to meet them (in battle) he was informed that Safwan
bin Ummayya had coats of arms and other weapons. He sent for him -
still a polytheist - and said to him, "O Abu Ummayya lend us your
weapons so that we can face our enemy tomorrow with their help."
Safwan asked, `O Muhammad do you want to confiscate them?" He
said, `No I want them temporarily with their return guaranteed till we
bring them to you.' He said, -there is no harm in (doing) this. So he
gave him one hundred coats of arms with the accompanying weapons.
They also claim that the Messenger of Allah requested him to transport
them too, which he did.'
The battle of Hunayn took place in the eighth year after "hijrah
immediately after the conquest of Mecca. These were comparatively
better days for state finances, The accrual of money referred to in the
tradition could have been from the spoils of war consequent to the
victory at Hunayn:
352
7. The last case is that of Abbas, the Prophet's uncle, paying a year's
zakat in advance, along with that of the current year. Since this was
presumably done at the request of the Prophet," it has been construed as
a kind of borrowing. The Prophet significantly used the word aslafa for
the act, a word normally used for lending.
The Prophet borrowed both in cash and kind, in small amounts as well
as large, from Muslims as well as non-Muslims, from men as well as
women. The purpose of borrowing was need fulfillment or defense/jihad.
But he also borrowed to pay off more urgent debts. No coercion was
involved in his borrowing. Nor did it stipulate repaying more than what
was received as a loan. He borrowed when he did not possess, in cash or
kind, what could meet the purpose in view. He borrowed in anticipation
of future income from. which repayment could be made, but he also
borrowed when no definite future income was in sight. He always repaid
the debts he incurred.
b. Fai, including the product share from Khaibar which was a steady
source of revenue.
353
d.. Voluntary donations, often in response to appeal from the
Prophet.
The first three sources brought nothing during the first year of the
Prophet in Medina, hence exclusive reliance must have been placed on
the last. In the light of available reports, revenue from all these sources
was meager till year seven when Khaibar was subdued. Some cases of
small borrowing for need fulfillment seem to belong to this period. But,
as we have noted above, the two cases of big borrowing (case 5 and 6)
belong to the post-Khaibar period and relate to defense purposes.
The same applies to the next hundred years of Umayyad rule (41-
132 A.H./661-749). We could not find any instance of state borrowing at
the level of the central administration. However, there is a report from
one of the provinces where an army commander borrows from traders
to buy provisions for a twelve thousand strong army. 13 He pays them
back after some weeks."
354
care of the Khariji rebellion which dominated Persia and threatened parts
of Iraq.
"They took stock of the public treasury and discovered that it had only
two hundred thousand dirhams. This was insufficient. Muhallab then sent
for the traders and told them: For a whole year your business is
depressed because the supplies from Ahwaz and Persia have been cut off
from you. Let us have some transactions. Then you come with me and I
will, God willing, fulfill all my obligations toward you. They sold to him
and he took whatever he needed to equip his army and to
provide for it ...."16
The first century of Abbasid rule, from 1232 A.H. to 232 A.H. was
blessed by firm central administration and robust finances. Then started
the period of weak rulers, domination of Turkish army chiefs and gross
financial mismanagement. The Caliphs ruled only nominally as power
was, in fact, exercised by the army commanders while the finances were
managed by wazirs. The chief interest of the Caliph lay in the huge sums
of money flowing into his private treasury (Bait mal al Khass) thanks to
the appropriation of lands over the past and the customary gifts presented
to the Caliph, especially by the aspirants to public offices. It was not
unusual, in this period, for the public treasury to be empty while the
royalty rolled in money. The army did not get paid in time. Unusual
delays in the payment of salaries led the infantry to protests which
sometimes culminated in riots in the capital city, Baghdad.
355
The first reports of public borrowing in our sources appear during
the reign of the eighteenth Abassid Caliph Muqtadir who ruled from
295 A.H. to 320 A.H (908 A.D. to 932 A.D.) Muqtadir ascended the
throne at the young age of thirteen. Real power was wielded by his
mother and the Wazirs who were changed very frequently. As we shall
see below the urgent need to pay the army while the state coffers were
empty was behind most of the public borrowing that occurred.
The nine reports relating to public borrowing given below all belong
to the period 300 A.H. to 333 A.H. This period was ruled by four
Abbasid Caliphs, Muqtadir (295-320 A.H.), Qahir (320-322 A.H.), Radi
(322-329 A.H.) and Muttaqi (322-333 A.H.). We could not cover the
later periods for many reasons, not the least important among them is
the fact that by then the world of Islam was divided into a dozen units
having separate rulers and independent finances. Any study covering
only the nominal Abbasid caliphate with its seat at Baghdad could no
longer be credible.
1. "Ali bin `Isa 17 used to borrow from traders when some payments
came due and he had no other means to make it. He borrowed on the
basis of letters of credit (safatij) coming from the provinces but not yet
due for payment. (He borrowed) ten thousand dinars against payment
of -a profit of one and a half daniq 18 of silver for each dinar. Every
month he owed two thousand and five hundred dirhams as profit. 19
This practice continued with Yousuf bin Finhas and Harun bin Imran,
or their deputies, for sixteen years, and till after their death. They were
not turned away till their death. They had gained this position (of state
bankers) during the wazirate of Obaidullah bin Yahya bin Khaqan.20
356
The ruler did not consider it wise to turn them away so that the
jahbazah retained its credibility among the traders and the traders
would lend the jahbadh in time of need. If the bankers were to be
turned away and others21 were given that position and the traders
refused to deal with these, the affairs of the Caliphs would collapse." 22
Significantly, no `profits ' are promised in this case, nor is there any
mention of letters of credit. The author has quoted his source in giving
this report whereas the statement quoted earlier is given on his own
authority. It is also to be noted that the two bankers named above were
Jewish not Muslims. 25
"He called Yusuf bin Finhas the Jewish jahbadh, who was the
jahbadh of Ahwaz, and told him, `This situation has arisen and our
colleagues had not made the necessary preparations to deal with it. I
have assigned their emoluments to (the revenue from) Ahwaz. Now it is
very necessary that. you pay them in advance for two months. He
(Yusuf bin Finhas) mentioned the large sums already assigned for
advance payment on Ahwaz account and that it was not possible for
357
him to take on any more demands. He (the wazir) continued to argue
with him till he agreed to release one month's pay that very day .... "28
8. We have yet another report about the same year, 323 A.H. This
time the wazir tried to borrow from traders in order to pay the troops,
offering traders letters of credit (safatij), the traders disappeared and
the effort did not succeed.34
358
9. Another report by the same author, Suli, relates to the year 331 A.H.
The then Amir al-Umara, Nasir al Dawlah, upon learning that the money
changers were dealing in interest openly, warned them against doing so
and obtained their pledges to that effect. According to Suli, however,
this helped restrain- them only a little.35
359
B. Discounting letters of credit or bills of exchange, i.e. obtaining
cash by surrendering the right to receive a larger amount of cash
later. (Cases 1 and 8).
In all the cases reported above it is not the Caliph who borrowed, but
the wazir, who actually ran the administration. Most of the borrowing is
done in cash to pay the army on time, but sometimes it is done to make
some other payments. Public borrowing in this period was largely in the
nature of bridge-financing, to be repaid from sure sources of revenue in
the near future. Loans are repaid out of the kharaj revenue (or land
taxes). The lenders are Jewish bankers as well as Muslim traders. The
amounts involved are large, but not out of proportion with the state
revenues in those times. .
360
What circumstances forced a pious man and efficient financial
manager, who curtailed public expenditure in an otherwise wasteful
affluent society, to borrow an interest, and how could he justify it to his
own conscience, remains an enigma - at least till further details are
available. This deviation from clearly defined shari'ah rules seems,
however, to be a culmination of many other deviations in the financial
management of the state, the details of which fill the pages of history
books.
361
3. While early history does not present any record of borrowing for
financing economic development, it does provide an indirect
justification of the same in an age in which economic development
(especially of the third world countries) has become a sine qua non
for need fulfillment as well as for defence/jihad.
5. The state must repay what it borrows even if doing so. necessitates
further borrowing.
BIBLIOGRAPHY
362
7. al Bukhari, al Jami' al Sahih.
8. al Dar Qutni, Ali bin Umar, Sunan, Cairo, Dar al Mahasin, n.d.
363
22. Ibn Sa'd, al Tabaqat al Kubra, Beirut, Dar Sadir, n.d.
23. Ibn al Taqtaqi,. al Fakhri fi'l Adab al Sultaniyab ..., Cairo, Matba'ah
al Ma'arif, 1923.
34. Qalaqshandi, Abu'] `Abbas Ahmad bin `Ali, Subh al A`sha, Cairo,
n.d.
364
35. al Sabi, Abul Hasan al Hillal b. al Muhsin, al Wuzara, Cairo, Dar
Ihya al Kutab al `Arabiyah, 1958.
365
15
PROVISION OF PUBLIC GOODS : ROLE
OF THE VOLUNTARY SECTOR (WAQF) IN
ISLAMIC HISTORY
INTRODUCTION
The present paper aims to study the nature and extent of public goods
provided by the voluntary institution of waqf in Islamic history. It also
tries to present the voluntary sector in general and waqf in particular as
an alternative sector that has the potentiality to resolve, to a great extent
at least in an Islamic system, the issue of an efficient supply of public
services. Thus we propose to explore the possibility of utilizing this
institution in developmental activities with respect to pure public good
and mixed or quasi-public activities in contemporary Muslim economies.
To begin with we shall briefly point out the controversy associated with
the supply and allocation of public services. We shall also discuss the
nature of the voluntary sector and different constituents of this sector
especially the development, scope and dimensions of awqaf (plural of
waqf) as the important ingredient of the voluntary sector. After
discussing some evidence from Islamic history, the organization as well
as the composition of services provided by this institution will be
discussed. Making an analytical study of the whole we shall examine the
role of the state in the supervision and regulation of awqaf in Islamic
history and a desirable role for it in the present context. To conclude we
hope to establish, in the light of our discussion, some suggestions that a
modern state may adopt to make the best institution for the provision of
public welfare and to reactivate and revitalize this gradually diminishing
source of general good.
367
PUBLIC GOODS AND THE QUESTION OF THEIR EFFICIENT
SUPPLY
368
no difference at all to the amount of resources directed to control an
externality. Economic forces ensure that the same effective allocation
will happen in all cases".4 This idea known as the Coarse Theorem, sets
out to demolish traditional thinking on public goods and externalities
and it has converted many more economists to the liberal, anti-
interventionist wing of their trade. But the issue remains as
controversial as when it first appeared. There is no direction available
to resolve this controversy.
369
for it. al nafaqat al ghair al wajibah (non obligatory expenditures)
for which the state or its 'agencies cannot force someone to
contribute are examples of recommended charity.
b) Hibah, hadiyah or atryah (gift and grant). A gift or grant made for
some public purposes is also a voluntary action for helping others.
Alumra (life long hibah) and Al ruqba (hibah in waiting) are two
special types of provisions for gifts.'
370
Some pioneer writers on the voluntary sector in Islam have listed zakah
especially on invisible property (al amwal al batinah), sadaqat al fitr and
expenditure on relatives under voluntary institutions along with some other
forms of voluntarism.10 But Islamic history shows that they have been
compulsory payments. Even in the absence of official collections of zakah,
the standing divine enjoinder and its binding nature excludes it from the
category of voluntary actions. Similarly, al nafaqat al wajibah (the
obligatory expenditure on relatives and others) for which the government
or its agencies may compel a person may not be considered as voluntary
actions.
Pre-Islamic Arabia did not have a waqf system for the support of
general welfare. It was the Prophet (SAW) who initiated the institution of
waqf in the light of the Qur'anic teachings to spend and dedicate valuable
and lovable belongings in the way of achieving goodness and the pleasure
of Allah." There are two main categories of awqaf.
a) Waqf for the benefits of oneself and family called family waqf, and
b) Waqf for supporting the general good and welfare of the poor
called public waqf.
371
our discussion. We mainly deal here with public awqaf that generates wide
ranging economic repercussions.
Islamic history is full of vivid and rich evidences of awqaf in all its
ages and in every region. Their number and magnitude is so much that an
encyclopedia-like work would be required to prepare a directory of them
for every Muslim country. Here are a few precedents from countless
examples of awqaf in Islamic history starting from the Prophet's time up to
the present age.
372
It is reported by Anas (RA) that when the Prophet (SAW) came to
Madinah he ordered the construction of a mosque. He asked Banu
Najjar to sell him land. They said, "By Allah, we expect its reward from
Allah the Almighty" (And gave their land for the sake of Allah to
construct the mosque).14
Ibn Umar (RA) reports that Umar (RA received a land at Khaibar
and came to the Prophet (SAW) to consult him about it. He said, "O
messenger of Allah, I have received land at Khaibar, I have never got a
property more valuable than that. So what do you advise me regarding
it?" He replied, "If you wish, you can retain its corpus and give it away
in charity". At this Umar dedicated it providing that it should neither be
sold, nor gifted, nor bequeathed. He gave it away for the sake of poor,
the relatives, (freeing) slaves, in the way of Allah, for guests and for the
wayfarers. It would be permissible for its caretaker to eat from it
according to commonly accepted pattern and to feed a friend who does
not enrich himself from it. 15
Ahnaf (RA) reported that .... in the presence of Ali, Zubair, Talhah
and Sa'd, Uthman the third caliph said, "You do know that the Prophet
(SAW) said, whoever purchases the mirbad (land for keeping the
camels) of such and such person, Allah would forgive him, so I
purchased it and came to the Prophet (SAW) and told him that.I had
purchased that land, at which he said, "Dedicate it to our mosque and
you will be rewarded". They. confirmed, saying `Yes". Then Uthman
(RA) said to them, "You do know that the Prophet (SAW) said,
"Whoever purchases the well of Rumah, Allah will forgive him." Then I
came to the Prophet and told him that I had purchased the well of
Rumah. He said, "Dedicate it to Muslims and you will be rewarded".
They answered, "Yes". Then you do know that the Prophet (SAW) said,
"Whoever provides for the army of Misery, jaish al Usrah) Allah will
forgive him" . Whereupon he provided for them so much so that they
were not missing even a rope or a ring." They confirmed it saying "yes".
At this he said three times, "O Allah, be a witness.16
Ibn Abbas (RA) reported that the mother of Sa'ad,b. Ubadah died
when he was away from home. He told the Prophet (SAW) that in his
373
absence his mother was dead; would it benefit her to give something in
charity on her behalf? The Prophet replied "Yes". He said, "I make you
witness that I give my garden al Mikhraf as charity on her behalf'.17
and good deeds. In later period, most of the Muslim rulers, along with their people,
created awqaf from their personal property or from the state treasury. Jalal
al Din Suyuti (d. 1505) in his book Husn al Muhadarah fi Ahwal Misr wa l
Qahirah gave detailed accounts of awqaf created by Ahmad b. Tulun (254-
370 A.H.), Fatimid Caliphs, Ayyubid Salatin, and Mamluk Salatin in
Egypt for mosques, schools, libraries, hospitals, khanqahs, etc. 19
The situation has been similar in India where most of the awqaf came
from kings of the past, and from scholars, saints and nobles. 20 One of the
earliest records is that created by Muhammad Chori (1175-1206 A.D.) who
made an endowment of two villages to meet the expenses of the grand
mosque of Multan and its related affairs. 21 Evidences relating to awqaf
during the Mughal period are too numerous to be noted here. Apart from
awqaf for objectives approved by shari'ah, there are a large number of
them for upkeep of tombs, khanqah zawiyah imambara, celebration of a
Shaikh' s birthday or
374
martyrdom, etc. One such waqf is that created for the tomb of Shaikh
Muinuddin Chishti of Ajmer, a spiritual saint of 7th century hijrah.
Since centuries it attracted awqaf from rulers as well as from common
devotees from all over the country. Due to its importance several acts
have been passed for its management. 22
1. Places of worship.
2. Defence and fighting for the cause of Allah.
3. Help to the wayfarer and road services.
4. Food and lodging for the poor.
5. Water resources.
6. Education.
7. Preaching and call to the Religion.
8. Hospitals for the sick.
9. Celebration and adornment of tombs.
10. Marriage provisions for the poor.
11. Release of captives.
12. Support of handicapped.
13. Inner purification centers.
14. Research institutes, etc.
In the earliest history of Islam, when the departments were not fully
established, the institution of awqaf substituted for the state's role. On
different occasions, the Prophet (SAW) appealed to believers and drew ,
375
their attention to the need to the provision of certain public benefits and
his companions readily responded to his call and met the social need
voluntarily as it is clear from the instances of preparations for different
wars; help to As'hab al Suffah who needed state support as they were
engaged in learning; provision of drinking water, etc. The establishment
of a full state in Islam did not reduce the importance of this institution.
In fact it supplemented the state in fulfillment of its obligations towards
the provision of public the good. By, providing certain infrastructure
such as roads, means of irrigation, health care, better nutrition, and
research and educational institutions it also paved the way for the
growth of the economy. During foreign domination of Muslim
countries, awqaf helped Muslims to preserve their identity, culture and
system of education and it served as a source of strength for the
mujahidin.
Motives: The driving force of dedication or waqf creation has been the
desire to win the pleasure of Allah. Verses of the Qur'an and hadith
provided a helping hand. This gave voluntary actions among Muslims
and edge over the secular thinking that limits them to altruism, man's
nature of interdependence, love, sense of social duty and urge for
recognition and approval. No doubt, all such factors motivate man to
voluntary actions, and a desire for the pleasure of Allah and hope of
unending reward in the Hereafter sharpens these factors except the last
one, i.e. an urge for recognition and approval which are negative factors
in the eyes of Islam as they are antagonistic to deeds for the sake of
Allah. Since waqf property cannot be inherited and ordinarily cannot be
sold, and generally is exempted from any tax, motives-for "creation of
waqf may be to deprive the legitimate heirs, or to deny-..the repayment of
loans, or to avoid taxes. Ibn Taimiyah noticed this- incident and
expressed his opinion that such a waqf would not be
376
allowed unless a preferable welfare consideration a l maslahah al
rajihah was expected therefrom as it was in the case of Umar's
precedent.25
377
chances to misuse them. Mismanagement and misappropriation of waqf
properties had been a common complaint against mutawallis.26
In India during the Mughal period, the supervision over awqaf was
entrusted to the qadi or sadr appointed by the king. 33 In the post of
378
Mughal period, the British government, as against its French and
Italian counterparts in Tunis, Algeria and Tripoli, followed a-non-
interference policy regarding awqaf for many years and considered it
as the Muslims ' personal affair and so avoided any confrontation or
resentment from Muslims. It was Muslims themselves who made
several representations and demanded a government administration. In
1913, the government abandoned its policy of non-interference and in
subsequent years a number of waqf acts were passed. After
independence the government passed the Waqf Act of 1954, bringing a
uniform administrative establishment throughout the country. 34 At
present, a union waqf ministry and in some provinces state waqf
ministries exist.
379
government, instead of having such . public utilities in its own hands and
exercising control to give it to voluntary organizations.
In our brief study of awqaf in Islamic history we have seen that the
voluntary institution of, waqf had performed a very active role in
provision of public services. It also provided some infrastructure in the
past in the form of roads, canals, bridges, health services and
educational centers. But with the passage of time, in spite of increasing
the volume of awqaf, it did not perform the role for which it was meant
and decadence crept in as has been the case with many other Muslim
institutions. Beneficiaries of awqaf missed the spirit of the awqaf
creators and treated the waqf property as a source of easy and lethargic
living. It lessened the incentive to work. Thousands of lazy and idle
people sat around the awqaf on the tombs of saints (mashaikh) in the
subcontinent and in some other Muslim countries. This is also a
common phenomenon. Evils associated with public and common
ownership such as negligence, less efficient utilization of the property,
carelessness towards the maximization of its profits all crept
380
in the waqf property. Capital accumulation, the source of growth,
became negative.
There were many factors responsible for that. In the Prophet's days,
the. Companions used to consult him or he used to guide them
regarding the needs of the society. This close relationship between the
authority and waqf creators did not continue. Thus lack of state
guidance has been one of the important factors leading to an
unbalanced selection of public goals.
Another factor which harmed the waqf institution was the one man
basis of its organization. Hereditary and sometimes arbitrary
appointment or mutawalli for public waqf was liable- to mismanagement
and abuse of powers, the performance of waqf institutions would have
been far better, had the management been given to a committee or a
consultant body, with a mutawalli as its head.
381
alteration in the object of waqf has been felt in all ages. Sometimes the
purposes of awqaf, with the passage of time, became redundant or non-
economical. But the belief in the sanctity of waqf property, the purpose
and the will of the donor, ordinarily did not allow modernization or
reorganization which caused decay and disorder of the waqf property.
Again it is worthwhile to quote Ibn Taimiyah who is against such
extreme views. He says, "A person's saying that transformation or
replacement (of waqf . property) is not permissible except when
utilization of the property is impossible, is not correct; they do not have
any shari'ah or legal evidence in support of their stand ................In this
context, Imam Ahmad's stand is more flexible who says that if a mosque
is congested, then there is no harm to shift it to a place more spacious.
It should be noted that congestion is not a loss of benefit. Actually
benefit is as usual; it is people whose number has increased."40
We have seen in the preceding pages that from the earliest days of
Islam, the state supervised awqaf through the court or by establishing a
separate department. Many scholars have emphasized the government
role in this regard. Ibn Taimiyah says, "The ruler has the right to
exercise a general supervision and take action if something prohibited is
done. He should appoint some honest person if the caretaker is not
efficient or accused of misconduct. The purpose is to achieve the
desired objectives.42 On another occasion he said, "The
382
ruler should establish a department to check the accounts of waqf
property, according to needs and this may become obligatory if the
collection of fund and its disbursement is not carried out properly
without such a department because the principle is that provision of all
those means is obligatory on which fulfillment of any obligation
depends." 43
383
According to the modern analysis of demand and supply of the
public good, "benefits are available to all, so consumers will not reveal
their preference by bidding in the market but will act as free rider.
Hence a political process or voting system based on a given distribution
of money income, is needed to induce the revelation of preference. "44 In
the context of public god by the voluntary institution of awqaf, the
problem of free riders is not be a big concern. In fact, the very nature of
the voluntary institution of awqaf will eliminate "stealing free riders";
rather it will aim at providing everyone with "free rides" which will
generate a positive response from other members of the society. The
state's cooperation with such' volunteers for the better utilization of
waqf resources will relieve the former from a substantial burden
regarding the provision of public goods. In this connection the following
points may be emphasized:
2.- Removal of narrow and rigid conditions. To make the awqaf more
purposeful all such conditions which are not approved by the shari'ah
should be abolished because they create hurdles in the way of a better.
utilization of awqaf. This will be according to the Islamic teaching
which says: "Every condition not found in the book of Allah must be
rejected", and "the terms prescribed by Allah ate more apt to be
fulfilled". 46
384
their unemployment open or in disguise. It is sad fact that in India
some Hindu temple trusts have established colleges research centers
and industrial estates which helped the growth of their trust revenue as
well as the intellectual and economic upliftment of their community.
We can hardly find such examples among the thousands of awqaf made
for tombs of mashaikh and awlia. Lamenting on this situation once, an
expert on Indian awqaf observed, "What Trupati temple has been able
to achieve in terms of its reorganization, raising an income of about
Rs.500,000 (Rupees five lakhs) in 1955 to about Rs. 80,000,000 (Rupees
eight crores) in 1975 benefitting every one concerned including the
counterparts of khadims is a great eye opener. By contrast the receipt to
the darqah (tomb of hadrat Muinuddin Chishti) administration in the
case of Ajmer set up is only about Rs. 200,000 (Rupees two lakhs) and
has not increased much!"47
7. Ambiguous awqaf. Awqaf whose donors are not known; nor their
terms and conditions; or the purpose for which they were created is no
longer needed may pass in to the hand of an Islamic state (ulil amr
385
minkum) treating them as heirless property and to be used for general
welfare purposes.
8. Educative efforts are required. The state should try to alter the pattern
of awqaf and their creation through its educative efforts. It should provide
necessary information abut public needs as the Prophet (SAW) used to
inform his Companions about the need for jihad, patrolling, water,
worship places, etc. In the modern context provision of the public good
such as remedial measures relating to pollution, scientific research,
weather forecasting, etc. should be emphasized.
In the end we feel that the time has come to internationalize the
voluntary institution of awqaf by setting up a non-government world
Muslim foundation which should provide public goods on a large scale and
in a much more significant fashion than has been the case up till now, to
combat illiteracy, sickness, lack of technical know-how etc. and to establish
world center for da'awah utilizing all modern and scientific methods for
propagation of the message of Islam. An Islamic news
386
agency, telecasting programs, rehabilitation of refugees, and supporting
the suppressed fighting for the religion, and securing dignity and human
rights may be some other functions of this foundation. Its benefits should
cover all Muslims living in different parts of the world and should work
for their intellectual, social and economic upliftment. Muslims being
similar to a single organic body, their backwardness in one country
means backwardness of the whole body.
387
Pergamon Press, 1982, Lutz, Mark A. and Lenneth lux, The
Challenge of Ilumanistic Economics, California, Benjamina,1979,
Rushton, J.P. and Richard, M. 5. (editors), Altruism and Helping
Behavior, New Jersey, Lawrence Elbam Association 1981.
8. Al Qur'an, 107:7.
9. Al Qur'an, 5:2
11. Dihlawi, Shah Wali Allah, Huijat Allah. al Balighah, Beirut, Dar al
Marifah, n.d., part 2, p.116.
15. Ibid.
16. Al Nasai, Sunan al Nasai, Jaisur, Zakaria Kutub Khana, n.d., part
2,,p.127.
18. Ibn Battutah, Tuhfat al Nuzzar, Cairo, Mutbaah Wadi al Nil, 1287
A.H., part 1, p-60.
388
20. Rashid, S. Khalid, Waqf Administration in India, New Delhi,
Vikas Publishing House, 1978, p.1.
29. First Encyclopedia of Islam, Leiden, E.J. Brill, 1987, vol.8, p.1099.
30. al Qalqshandi, Abu al Abbas Ahmad, Subh al Asha, Cairo, al
Matbah al Amiriyah, 1914, p.494.
389
34. Rashid, S.K., op. cit., pp.11-36; Qureshi, M.A., op. cit., p.352.
37. In 1891, a case was filed against a mutawalli who pronounced the
word amin in a loud tone, of Qureshi, M.A., op. cit., p.21.
46. Ibn Taimiyah, Majmu Fatawa, vol.31, pp.13, 47, 48, 57-43.
47. Kkhusro, A.M., "Foreword". on Waqf Administration in India,
Rashid, S.K., op. cit., p.IX.
48. Ibn Taimiyah, Majmu Fatawa, op. cit., vol.31, pp.18, 208, 210, 213-
14, 252-53.
49. Zarqa, M.A., "Some Modern Means for the Financing and
Investment of Awqaf Projects" in Basar, Hasmet (editor,
390
Management and Development of Awqaf Properties, op. cit.,
pp.38-48; 'Al Wasail al Hadithah li'l Tamwil wa'l Istithmar" in al
amin, Hasan Abdullah (editor), in Idarah wa 'l'athmir Mumtalakat
al a Waqf, op. cit., pp. 181-202.
50. Ibn Taimiyah, Majmu Fatawa, op. cit., vol.31, pp. 206-07.
391
16
THE RELEVANCE OF THE OTTOMAN CASH WAQFS
(AWQAF AL NUQUD) FOR
MODERN ISLAMIC ECONOMICS
MURAT CIZAKCX*
INTRODUCTION
The cash waqf was basically the establishment of a trust with money,
the return from which, would be utilized for serving mankind in the
name of God. These endowments were approved by the Ottoman courts
as early as the beginning of the 15th century and by the end of the 16th,
they had become extremely popular all over Anatolia and the European
provinces of the empire. Yet, they found little, if any, application the
Arab provinces. In a society where health, education and welfare were
entirely financed by gifts and endowments the cash waqfs carried
serious implications for the very survival of the Ottoman social
structure. Moreover, they were also instrumental in the emergence of a
legally sanctioned and well developed money market.
393
the reign of Mehmed the conqueror, in the year 1505 the ratio increased
to 50% and by about 1560 they had become the dominant mode of
endowment. 2
2. LEGAL BACKGROUND
The legal issues pertaining to the legitimacy of the cash waqfs are
complex and have constituted the essence of a long lasting debate
among the jurists. The debate revolved mainly around three issues:
endowment of moveable assets the problem of perpetuity and the
potential danger of riba in transferring the endowment funds. The main
points of this centuries - long debate are summarized below, where due
to space restrictions only the Hanefi point of view, the most relevant
perspective for the Ottomans, will be emphasized.
Let us first consider the endowment of the moveable assets; since the
perpetuity of the endowed asset is the essence of any waqf, in principle,
the endowment should consist of real estate. There are, however, three
recognized exceptions to this general principle among the Hanefi
scholars. First, the endowment of moveable assets belonging to an
endowed real estate, such as, oxen or sheep of a farm, is permitted.
Second, if there is a pertinent "Hadis", and third, if it is the custom
(ta'amul) in a particular region. Indeed, exercising "istihsan", Imam
Muhammed al-Shaybani has ruled that even in the absence of a
pertinent "Hadis", the endowment of a moveable asset is permissible if
doing so is customary in a particular location.2 Apparently, even custom
was not a required condition, for, according to Al-Sarahsi, Imam
Muhammed had in practice approved the endowment of movables even
in the absence of custom. 3 Furthermore, both Imam
394
Muhammed Al-Shaybani and Abu Yusuf had confirmed, absolutely, the
endowment of movables attached to a real estate. In view of this, it is
not surprising that we see, often, such combined cash/real estate waqfs in
the Ottoman records.
395
1. Since, as mentioned above, one of the main points of the debate was
concerned. with the problem of perpetuity (proponents arguing that
these awqaf had as good a chance for survival as any other real estate,
and opponents believing that they would collapse within a relatively
short time), would it be possible now, during the last decade of the 20th
century, to look into this problem in retrospect and judge which side
was correct?
2. What exactly were the reasons for the outcome of the answer to the
first question? In other words, if these endowments, indeed, rapidly
disappeared, what were the reasons behind this failure, why were they so
badly managed? Where did they go wrong and what were their mistakes?
If, by contrast, 'they succeeded surviving for any length of time, then
what were the reasons for their relative success?
396
6. Any process of modernization must be based upon a thorough and
objective study of the past. Therefore, as an off-shoot of the second
question above, would it be possible to initiate a process of
modernization of this institution whereby the mistakes of the past can be
avoided and the virtues maintained? If yes, what characteristics should
be avoided and what others should be kept? Let us now try to answer
these questions in the order they were put.
But even this incomplete data reveals some important insights. For
some obscure reason there appears to have been a massive decline in the
number of cash waqfs between the periods 927-953/1520-1546 and 953-
986/1546-1578. But then, the awqaf survived from the earlier periods
and the newly established ones during the period; 953-986/1546-1596,
survived more or less intact into the next period; 986-1005/1578-1596,
when the numbers of the newly established awqaf increased impressively
and we observe an upswing in the overall trend. Just what forces were
behind these fluctuations is difficult to ascertain.
397
But one thing is certain; the cash waqfs do not exhibit a downward linear
trend and disappear into oblivion at the end as suggested by Barkan and
Ayverdi8, instead we observe cyclical fluctuations. This is supported by
my own on-going research: I have found four waqf censuses belonging to
the city of Bursa covering the period; 1077/1666 to 1220/1805, the
registers; B 135/150, B 199/423, B 211/434, B 352/736, which indicate that
the cash waqfs at this late period were alive and well.
The only person who did not have to provide a collateral or a surety
was certain Mehmed bin Abd-el-Rasul, who was in all probability well
known to and trusted by the waqf manager.
398
Let us now look into the question of the rate of return. The waqf
census from the year 1181/1767 cataloged under the number; B 199
423 in the Bursa Ottoman Court Registers reveals important
information. All the awqaf were registered in this "defter" according to a
pattern: First comes the name of the waqf, which reveals briefly the
overall purpose of the foundation. Then the name of the trustee is
stated. The amount of the capital (asl-i-sene-i mal) is immediately
followed by the statements "murababah fi sene-i kamile", i.e., rate of
return in a full year. This is followed by the statement "minha
elmesarif'', i.e., the total expenditure of the foundation in that particular
year.
Just prior to the writing of this article, I was able to collect a sample
of 69 cases out of the above mentioned "defter" containing some 300
awqaf. The statistical details pertaining to this sample are as follows: In
most cases the annual rate of return was preserved for "Sadakah",
which was usually paid as salaries to the muezzin or Imam of the local
mosque and to those who would read a section of the Quran everyday.
22 of the awqaf enjoyed a rate of return greater than the expenses they
incurred. 14 of these had also made profits above the expenses in the
previous year and these profits were added to the capital. Thus, it is
reasonable to assume that in all the 22 cases the profits would be added
to the "asl-i mal", i.e., capital of the foundation in the following year. In
all cases, the rate of return was usually 10% to 12%. In eight of the
awqaf there was a merger with other foundations and the capital was
thus enlarged.
The vast majority of the cases studied were cash waqfs (61 in total)
versus only 8 combined . cash/real estate waqfs. Thus, it is clear that
despite the legal debate mentioned above the cash waqfs maintained
their popularity and continued to dominate the awqaf system as late as
the second half of the 18th century.
Most of the awqaf studied were fully utilizing their capital. That is to
say, they regularly transferred all of their funds to the entrepreneurs or
the members of the general public. Only four of them kept idle money
in their safes.
399
Concerning the second question posed above, i.e., the management of
the awqaf, the following conclusions can be drawn: First of all, these
foundations were profitable. This is attested by the fact that whereas the
awqaf, in general, were generating a profit rate of 10-12 per cent per
annum, the rate of inflation was less than 5% throughout the 18th
century. 10 Thus, there is no doubt that these foundations were enjoying
substantial profits, at least, in the short run. The long term profitability,
on the other hand, is a different story altogether. Normally, the long
term profitability - could easily have been ensured by reinvesting the
above mentioned profits and adding them to the capital. This, however,
was not done. As we have seen above, the profits (murabahah fi sanai
kamile) were distributed as salaries to a number of individuals who were
performing certain religious, educational or health services. Although,
no doubt of great social importance, nevertheless, from the perspective of
the long term survival of the foundation, such expenditure was
unproductive. Consequently, the long term resilience of the waqf was
endangered.
At this point, one wonders, if there was any link between this problem
of long term profitability/survival and the rapid decline in the numbers of
cash waqfs observed by Barkan during the second half of the 16th
century. Although the unproductive investment of the awqaf profits
could explain a gradual decline and disappearance of the cash waqfs over
the long term, it cannot explain such a rapid disappearance as observed by
Barkan. In this context I would like to hypothesize that what Barkan
observed was not so much a disappearance of the cash waqfs but rather a
massive conversion of them into real estate waqfs
400
(istibdal). After all, the period in question was marked by one of the
most severe inflations in Ottoman history." Faced with an inflation of
such shocking proportions the trustees probably chose the most rational
avenue open to them; the conversion of the cash capital of the waqf
into real estate.
The legal term istibdal simply means the conversion of the endowed
asset into another type of asset. As such, istibdal considered as one of
the ten conditions (shurut-u ashere),12 which the founder of the waqf
may dictate when he establishes the waqf. Since istibdal has important
implications for the perpetuity of the waqf (te'bid) and since it is open
to unscrupulous exploitation, it has been carefully scrutinized by the
jurists both before and during the Ottoman era.
401
procedure subject to the approval of the judge. This third condition,
however, was challenged later on by the Egyptian jurist Ibn-i Nuceym in
response to some misuse. Finally, the matter was settled once and for all
by the imam-i azam of the Ottomans; Ebussuud Efendi in the year
951/1544 who ruled that istibdal would be valid only if approved by
BOTH the Ottoman Sultan AND the local judge. 13 Thus, it can be
concluded that whereas istibdal could be resorted with relative case
before 951/1544, after this date it would be far more difficult to do so. In
this context it is revealing that the rapid decline, observed by Barkan, in
the number of cash waqfs took place during precisely this critical period;
1520-1546 and 1546-1578, thus giving use the impression that large
numbers of cash waqfs might, indeed, have been converted into real
estate before 1544 when it was relatively easy to do so. In the next
period, that is two years after Ebussuud's decision, the decline in the
number of cash waqfs suddenly halted, followed in the next period by a
recovery. 14
402
diffused their capital to as many as 31 in a single year. Only 4 out of 69
kept their capital idle, while all the rest lent and thus diffused it.
The recipients of the waqf capital belonged to all the strata of the
Ottoman society, textile entrepreneurs, women, Christians, brick makers,
porters, fur makers, collectors of the jizyah tax, tailors etc. Practically
everybody who needed cash can be found on these registers. While a
detailed, computerized study of this enormously rich data will soon be
attempted by this author, even a quick look shows clearly that there was
capital accumulation at the individual level also. That is to say, an
entrepreneur could easily pool capital from two different awqaf. This was
certainly the case for a certain Christian tax farmer, Anderyas, who
obtained funds from two different awqaf in the district of Alaca Mescit.16
"... the above mentioned woman has decided to endow the said amount
which will be profitably invested through muamele-i shariye and
murabaha-i-mer'iyye at the rate of 1.25 dirhams for every 10 dirhams. The
trustees will see to it that their financial operations will be free of riba or
even a suspicion thereof'.18
403
the situation knows as "itzam-i rib", i.e., necessitating the profit. It
indicates whether the money advanced by the waqf is in the form of a
"Qard" or in the form of profit sharing. Therefore, the specific rates
given above, it has been argued, do not refer to riba but rather, state that
for every 10 dirhams earned by the borrower or entrepreneur 1.25
dirhams should be returned to the waqf 19
404
prevailing at that period. This argument is a mere hypothesis and needs
to be tested.
Second; if Barkan was right and the cash waqfs, indeed, tended to
vanish, a probable explanation can be found in the way the profits
generated by these awqaf were utilized. Only 32% of the cases
examined generated profits above costs, which were incurred entirely
for religious and educational purposes. The majority of the awqafs
studied allocated their entire profits to such expenditure. Consequently,
re-investment of the profits and enlargement of the original capital was
curiously lacking in most of the cash waqfs.
The basic function of the cash waqfs was to transfer the excess
savings of the well to do to those who needed capital. Moreover, this
institution performed this function within the framework of Islamic
financial principles. At the present time this function is performed by
modern Islamic banks. As such, cash waqfs should be considered as
405
complementary, not an alternative, to the Islamic banks already
successfully operating in most Islamic countries.
It has been explained elsewhere that while Islamic banks have proven
themselves, at least in case of Turkey, by generating profits well above
conventional riba interest-based banks, they are nevertheless subject to
criticism for resorting overwhelmingly to murabaha in transferring their
funds to the entrepreneurs. The murabahah, in modern context, however,
is considered to be dangerously close to riba. Consequently, Islamic
banks are face to face with a dilemma; while on the one hand they
generate handsome profits thanks to murabahah, on the other they are
criticized for achieving this profitability through this particular
instrument. In response to such criticism Islamic banks have made
earnest efforts to deadlock persists and murabahah dominates the
investment portfolio of these banks at the rate of 95%.21
406
continuous and close contacts between the investor (rabb ul mal) and the
entrepreneurs financed, and a willingness to lend support to them
whenever they encounter problems. Islamic banks simply do not. have
the patience or resources for such a demanding activity.
407
investment portfolio per annum, cumulatively, to the purchase of VCC
equities.
It is at this point that the cash waqfs may enter the picture. For, after
all, by definition, waqf capital once endowed cannot be withdrawn by the
founder. Thus, cash waqfs could solve the most serious problem faced
by the VCC's, shortage of long term capital.
Let us now envisage how the cash waqfs can be combined with
venture capital. Assume that person A wishes to establish a cash waqf
with his savings. The purpose of this waqf would be to help finance
entrepreneurs who wish to establish their own businesses. The founder
of the waqf, A, approaches a VCC and informs them of his intention.
Then he deposits his savings with the VCC which constitutes the capital
of this cash waqf. The VCC would then sign a mudarabah contract with
the waqf, thus becoming in reality its mudarib. When it comes to the
transfer of waqf funds to the entrepreneurs, the VCC also agrees that the
capital' of the waqf would be invested solely in mudarabah/ musharakah
partnerships, thus eliminating all doubts about the legitimacy of this
investment from an Islamic point of view. Structurally speaking, this
would be a triple mudarabah with three parties involved; the waqf, the
VCC and the entrepreneur.
408
the mudarib (entrepreneur) and 3/4th to the rabb ul mal (VCC). So, the
VCC obtains 3/4th of the profit of the entrepreneur plus the original
capital whenever the project matures (no time constraint here).
Since the VCC has signed a mudarabah contract with the waqf, the
same ratios are observed while distributing the profits between the
VCC and the waqf. Thus, the waqf obtains the original capital 3/4th of
the profit earned by the VCC, the latter keeps 1/4th of it for venture
capital services rendered. Thus, in short, the waqf obtains 3/4th of the
3/4th, or 9/16th of the profit generated by the entrepreneur. Put
differently, if the entrepreneur earns a profit of 100 dollars, the waqf
gets 56.25 dollars as its share, plus, of course, the original , capital
invested by the waqf.
409
Needless to say, the since qua non of success is proper management.
In this context it may be suggested that the involvement of a third party
in the affairs of the waqf may be desirable. The Ottomans, it will be
recalled, had successfully involved the recipients of the "murabahah" in
the management of the waqf. We have seen that whenever these
individuals suspected a mismanagement they immediately informed the
courts. By allocating, say . 1/10th, of the waqfs profit share to a neutral
third party, a body of "inspectors" can be recruited. Ideally, these
persons should be capable of analyzing the income and balance sheets of
the VCC. More pacifically, the business administration department of a
nearby university can be declared a recipient of this 1/10th and can be
given the authority to inspect the records of the VCC in the charter of
the waqf and in the original mudarabah contract signed between the
VCC and the latter.
6. CONCLUSION
While the state of our knowledge does not yet permit us to draw
conclusions pertaining to the important issue of perpetuity, we have,
nevertheless, been able to identify certain weaknesses that may have
jeopardized it.
This author believes that combining the cash waqfs with Venture
Capital sector, not only the problem of waqf capital's perpetuity but
also the problem of riba can be solved, while providing the much
needed long term capital to the Venture Capital Companies which are
essential in enhancing entrepreneurship in Islamic countries.
This author believes that combining the cash waqfs with the Venture
Capital sector, not only the problem of waqf capital's perpetuity but
also the thorny problem of riba can be solved, while providing the
410
much needed long term capital to the Venture. Capital which are essential
in enhancing entrepreneurship in Islamic countries.
ENDNOTES
6. Mandaville, ibid.
8. Ibid., p.XXXI.
11. For the rate of inflation during the second half of the 16th century
see; Murat Cizakca, "Price History and the Bursa Silk
411
Industry: A Study in Ottoman Industrial Decline, 1550-1650", The
Journal of Economic History, Vo.XL, September 1980, No.3.
16. Ibid.
17. It was through a series of imperial decrees dated 1852, 1864 and 1887
that the rate of interest was legalized in Turkey during the Ottoman
era. The most important one of these decrees, that of 1887 which
fixed .the legal rate. of interest at 9% is known as the "murabaha
decree".
412
21. Murat Cizakca and Tansu Ciller, Turk Finans Kesiminde Sorunlar
Va Reform Onerileri, (Istanbul: Istanbul Sanayi Odasi, yayin
no.1989/7, 1989), passim.
23. Ibid.
413
APPENDIXES
Foreword by Hon. Dato Seri Anwar Ibrahim Foreword
415
INAUGURAL ADDRESS
Y.B. DATO' SERI ANWAR IBRAHIM
Finance Minister of Malaysia
and President, International Islamic University Malaysia
417
can no longer isolate themselves form the international intellectual
community. As communication technologies and travel facilities turn
the world into a global village and interactions between cultures
become a daily affair dialogue is inevitable.
418
WELCOME ADDRESS
With the collapse of the totalitarian approach and the persistent crisis
within the capitalistic approach, the balance provided by the Islamic
approach is greatly needed not only to help the Ummah but humanity as well.
419
RESOLUTIONS OF THE CONFERENCE
Thanks to Allah Almighty, the Third International Conference on
Islamic Economics was held at Kuala Lumpur on Rajab 23-25, 1 4 1 2 H
(January 28-30, 1992) under the joint sponsorship of the International
Islamic University, Malaysia, Islamic Development Bank, Jeddah and
the International Association for Islamic Economics. The Conference
theme was Financing Development from Islamic Perspective.
421
broad based participative system. Without these, pragmatic and prudent
policies for development cannot be expected when they are most needed
especially to overcome rampant inefficiencies and significant wastage of
public resources.
422
to facilitate mobilization of resources for development. In this regard,
there is a special role to be played by the Central Banks of Muslim
countries by way of extending needed assistance to Islamic financial
institutions while guiding and supervising them without sacrificing
public interest. This Conference calls upon the Governors of the Central
Banks to play a positive and active role in the promotion and
strengthening of Islamic finance. Whereas in the past Islamic financial
institutions felt discriminated against, it is hoped they will receive
normal treatment in the future especially with respect to the Central
Banks' function as the lender of last resort.
The Conference also feels that Zakah can play a significant role in the
realization of the social and economic goals of Islam and its
implementation should go hand in hand with other developmental efforts.
423
This Conference assures all that in seeking to serve humanity in
general, it is not a matter of confrontation with anyone but a search for
peace in a harmonious and balanced vision for the economy of man
based on individual initiatives inspired by social goals and with the
aspiration to please Allah, the Lord of all mankind, the Creator, the
Sustainer.
424
Legal Deposit No. 1432/16
ISBN; 9960 - 627-61-6
ISLAMIC DEVELOPMENT BANK (IDB)
Establishment of the Bank
The Islamic Development Bank is an international financial institution established in pursuance of the
Declaration of Intent by a Conference of Finance Ministers of Muslim countries held in Jeddah in Dhul Qa'da 1393H
(December 1973). The Inaugural Meeting of the Board of Governors took place in Rajab 1395H (July 1975) and
the Bank formally opened on 15 Shawwal 1395H (20 October 1975).
Purpose
The purpose of the Bank is to foster the economic development and social progress of member countries and
Muslim communities individually as well as jointly in accordance with the principles of Shari'ah.
Functions
The functions of the Bank are to participate in equity capital and grant loans for productive projects and
enterprises besides providing financial assistance to member countries in other forms of economic , and social
development. The Bank is also required to establish and operate special funds for specific purposes including a
fund for assistance to Muslim communities in non-member countries, in addition to setting up trust funds.
The Bank is authorized to accept deposits and to raise funds in any other manner. It is also charged with the
responsibility of assisting in the promotion of foreign trade, especially in capital goods among member countries,
providing technical assistance to member countries, extending training facilities for personnel engaged in
development activities and undertaking research for enabling the economic, financial and banking activities in
Muslim countries to conform to the Shari'ah.
Membership
The present membership of the Bank consists of 48 countries. The basic condition for membership is that the
prospective member country should be a member of the Organization of the Islamic Conference and be willing to
accept such terms and conditions as may be decided upon by the Board of Governors.
Capital
The authorized capital of the Bank is six billion Islamic Diners. The value of the Islamic Diner, which is a unit
of account in the Bank, is equivalent to one Special Drawing Right (SDR) of the International Monetary Fund. The
subscribed capital of the Bank is 3,654.78 million Islamic Dinars payable in freely convertible currency acceptable
to the Bank.
Head Office
The Bank's head office is located in Jeddah in the Kingdom of Saudi Arabia and the Bank is authorized to
establish agencies or branch offices elsewhere.
Financial Year
Language
The official language of the Bank is Arabic, but English and French are additionally used as working
languages.
ISLAMIC RESEARCH AND TRAINING INSTITUTE ISLAMIC DEVELOPMENT BANK
TEL 6 3 6 1 4 0 0 FAX 6378927 / 6366871 TLX 601137/601945 CABLE: BANKISLAMI
P.O. BOX 9201 JEDDAH 21413 | https://www.scribd.com/document/348745791/Buku-Financing-Development-in-Islam | CC-MAIN-2019-35 | refinedweb | 42,920 | 52.7 |
I am working through the Python for Everybody course and am trying to write a program that extracts email addresses from a file and writes them to a new file, each address on a new line. The file "mbox-shot.txt’is used as a source, since it has loads of (duplicate) email adresses in it.
I did succeed in getting them from the file into a list without all other text from the file. When I have the program iterate through the list, it will print each addresss on a new line, but I cannot get it to write each address to a new line in a new file (.txt). Right now it writes all the email addresses to the file twice, all without spacing or spacing characters. I have tried multiple variations, including defining a function, return and write the result to a file (did not work), with some only the last address is written to the file and with others the same result as it is now. I did check the type(email) to confirm it is a list.
Below the code, can anyone push me in the right direction?
(I do realise the the used re for finding an email address is not perfect, but I will experiment more with that later, as well as removing duplicates.)
import re with open ('mbox-short.txt') as han : lines = han.readlines() emails = re.findall("[\w\.-]+@[\w\.-]+", str(lines)) with open ("email.txt", "a+" ) as file1 : for line in emails : file1.write(line) ## when I use print(line) the output is exactly how I want it in the file, so I must miss something (knowlegde/understanding) here?
Thanks a lot! | https://forum.freecodecamp.org/t/writing-elements-from-a-list-to-a-file-need-a-push-in-the-right-direction/428230 | CC-MAIN-2022-21 | refinedweb | 281 | 81.02 |
If you build an app you want to engage your customers so that they use your app as much as possible and also in a way that it brings value to them. Therefor you have to set up push notifications. In this Guide I will show you how that can be possible with some great tools. We are going to build a simple app that demonstrates the push notifications.
There are some powerful tools out there to make app development as easy as possible.
React Native
React Native is great because you can just code in javascript and compile to IOS and Android. So less costs and a faster development cycle.
Expo
Expo works out well because it is packaged with a lot features which you need and you can develop for IOS and Android without installing any other tools or even without having a Mac.
AWS Amplify
AWS Amplify is the glue between these tools and the backend. Here you can also use Javascript for setting up your API's, storage, authentication and authorization, database, data store and more.
Push Notifications
When you will dive deeper in these tool sets and setting up your architecture you will start loving them and when you are coming to a point where you want to use push notifications you have to say good bye to Expo because AWS Amplify doesn't come with a solution out of the box where you can use push notifications without ejecting. We have some luck that AWS has more tools that can support push notifications without ejecting.
Architecture
We will use AWS Amplify, AWS Pinpoint, AWS Lambda, AWS DynamoDB and Expo Push Notifications Server to accomplish it.
In this example we will make a message in our app. We will create a scheduled Pinpoint Campaign via the AWS Lambda Pinpoint (This can also be an immediate campaign). As soon as the campaign will be triggered, first a hook will kick off. This hook will send campaign data to the AWS Lambda Push Notifications. We will prepare the push notifications message and send it via the Expo Server SDK to Expo. This will send the push message to the client, to your app. In the meanwhile the campaign data has been send back to AWS Pinpoint to send it further to others channels (if you want). You are going to set up an email channel so you can see how it works
Getting Started
I will use NPM but course you can also you Yarn.
Set up React Native
First, we'll create the React Native application we'll be working with.
$ npx expo init pushApp > Choose a template: blank $ cd pushApp $ npm install aws-amplify aws-amplify-react-native
Set up AWS Amplify
We first need to have the AWS Amplify CLI installed.
Now we can now initialize a new Amplify project from within the root of our React Native application:
$ amplify init
Here we'll be guided through a series of steps:
- Enter a name for the project: amplifypushapp (or your preferred project name)
- Enter a name for the environment: dev (use this name, because we will reference to it)
-.
Add Graphql to your project
Your React Native App is up and running and AWS Amplify is configured. Amplify comes with different services which you can use to enrich your app. We are focussing mostly on the API service. So let’s add an API.
Amplify add api
These steps will take place:
- Select Graphql
- Enter a name for the API: pushAPI (your preferred API name)
- Select an authorisation type for the API: Amazon Cognito User Pool ( Because we are using this app with authenticated users only, but you can choose other options)
- Select at do you want to use the default authentication and security configuration: Default configuration
- How do you want users to be able to sign in? Username (with this also the AWS Amplify Auth module will be enabled)
- Do you want to configure advanced settings? No, I am done.
- Do you have an annotated GraphQL schema? n
- Do you want a guided schema creation?: n
- Provide a custom type name: user
You API and your schema definition have been created now. You can find it in you project directory:
Amplify > backend > api > name of your api
The @model directive will create a DynamoDB for you. There are more directives possible, for the full set look at the AWS Amplify docs.
Configure AWS Email Service
Log into the console and go to the SES service. Then follow these instructions to configure an e-mail address and get it activated. You will need to use this email address later as the email address where you send the mails from.
Add analytics to your project
We are going to add analytics to your project because for now this is the easiest way to set up access to pinpoint from your pinpoint function. You can also modify the cloudformation template to do so.
Amplify add analytics
Complete the steps with your information.
Add Functions to your project
By adding functions we are going to create the Lambda's.
Amplify add function
Follow these steps:
- Provide a friendly name for your resource to be used as a label for this category in the project: pushNotification
- Provide the AWS Lambda function name:
- Choose the function template that you want to use: Hello world function
- Do you want to access other resources created in this project from your Lambda function? Y
- Select the category api
- Select the operations you want to permit for pushAPI read
- Do you want to edit the local lambda function now? N
Repeat this step again but call the next function pinpoint and anwer these steps with this information:
- Do you want to access other resources created in this project from your Lambda function? Y
- Select the category Analytics
- Select the operations you want to permit for Analytics create, read, update, delete
- Do you want to edit the local lambda function now? N
Your Functions are created now and you can find it in your project directory:
Amplify > backend > function > name of your function
Go to the src directory of the Pinpoint function and install this package
$ npm install aws-sdk
Open the index.js file and paste this code. Please walk through the code and replace the right values.
/* var analyticsAmplifypushappId = process.env.ANALYTICS_AMPLIFYPUSHAPP_ID var analyticsAmplifypushappRegion = process.env.ANALYTICS_AMPLIFYPUSHAPP_REGION Amplify Params - DO NOT EDIT */ const AWS = require("aws-sdk"); AWS.config.\n <head>\n <meta http-\n</head>\n<body>\n<H2>Hallo {{User.UserAttributes.name}},</H2>\n\n <br />This is a Text Message from PinPoint. \n You have send this text: \n\n` + message + `\n</body>\n</html>`, FromAddress: "<FROM EMAIL ADDRESS>" }, DefaultMessage: { // you push message Body: message } }, Name: "push campaign", Schedule: { IsLocalTime: false, QuietTime: {}, StartTime: utcDate.toISOString(), Frequency: "ONCE" }, SegmentId: String(segmentID), SegmentVersion: 1, tags: {} } }; return new Promise((res, rej) => { pinpoint.createCampaign(params, function(err, data) { if (err) { console.log(err, err.stack); // an error occurred const response = { statusCode: 500, body: JSON.stringify(err) }; rej(response); } else { console.log(data); const response = { statusCode: 200, body: JSON.stringify(data) }; res(response); // successful response } }); }); }
You are almost there. Now let's make the next function. Go to the Push Notifications directory and then to the src directory. Install this NPM package
$ npm install expo-server-sdk
Open index.js and past this code
/* Amplify Params - DO NOT EDIT */ const { Expo } = require("expo-server-sdk"); // Create a new Expo SDK client let expo = new Expo(); exports.handler = function(event, context, callback) { try { let messages = []; // prettier-ignore for (var key in event.Endpoints) { if (event.Endpoints.hasOwnProperty(key)) { var endpoint = event.Endpoints[key]; messages.push({ to: String(endpoint.User.UserAttributes.expoToken), sound: "default", body: event.Message.apnsmessage.body, data: { "status": "ok" } }); } } // The Expo push notification service accepts batches of notifications so // that you don't need to send 1000 requests to send 1000 notifications. We // recommend you batch your notifications to reduce the number of requests // and to compress them (notifications with similar content will get // compressed). let chunks = expo.chunkPushNotifications(messages); let tickets = []; (async () => { // Send the chunks to the Expo push notification service. There are // different strategies you could use. A simple one is to send one chunk at a // time, which nicely spreads the load out over time: for (let chunk of chunks) { try { let ticketChunk = await expo.sendPushNotificationsAsync(chunk); console.log(ticketChunk); tickets.push(...ticketChunk); // NOTE: If a ticket contains an error code in ticket.details.error, you // must handle it appropriately. The error codes are listed in the Expo // documentation: // } catch (error) { console.error(error); } } })(); // Later, after the Expo push notification service has delivered the // notifications to Apple or Google (usually quickly, but allow the the service // up to 30 minutes when under load), a "receipt" for each notification is // created. The receipts will be available for at least a day; stale receipts // are deleted. // // The ID of each receipt is sent back in the response "ticket" for each // notification. In summary, sending a notification produces a ticket, which // contains a receipt ID you later use to get the receipt. // // The receipts may contain error codes to which you must respond. In // particular, Apple or Google may block apps that continue to send // notifications to devices that have blocked notifications or have uninstalled // your app. Expo does not control this policy and sends back the feedback from // Apple and Google so you can handle it appropriately. let receiptIds = []; for (let ticket of tickets) { // NOTE: Not all tickets have IDs; for example, tickets for notifications // that could not be enqueued will have error information and no receipt ID. if (ticket.id) { receiptIds.push(ticket.id); } } let receiptIdChunks = expo.chunkPushNotificationReceiptIds(receiptIds); async () => { // Like sending notifications, there are different strategies you could use // to retrieve batches of receipts from the Expo service. for (let chunk of receiptIdChunks) { try { let receipts = await expo.getPushNotificationReceiptsAsync(chunk); console.log(receipts); // The receipts specify whether Apple or Google successfully received the // notification and information about an error, if one occurred. for (let receipt of receipts) { if (receipt.status === "ok") { continue; } else if (receipt.status === "error") { console.error( `There was an error sending a notification: ${receipt.message}` ); if (receipt.details && receipt.details.error) { // The error codes are listed in the Expo documentation: // // You must handle the errors appropriately. console.error(`The error code is ${receipt.details.error}`); } } } } catch (error) { console.error(error); } } }; callback(null, event.Endpoints); } catch (error) { callback(error); } };
Now we need to push first all the service to the cloud. Go to the root your project and run this command
amplify push
Follow these steps:
- Do you want to generate code for your newly created GraphQL API?Yes
- Choose the code generation language target Javascript
- Enter the file name pattern of graphql queries, mutations and subscriptions Enter (default)
- Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions? Y
- Enter maximum statement depth [increase from default if your schema is deeply nested] Enter (default)
Go back to the src directory of your pushNotification function. Open this file: pushNotification-cloudformation-template.json and go to the "Resources": { section and paste this code:
"LambdaInvokePermission": { "Type": "AWS::Lambda::Permission", "Properties": { "Action": "lambda:InvokeFunction", "FunctionName": { "Fn::If": [ "ShouldNotCreateEnvResources", "pushNotification", { "Fn::Join": [ "", [ "pushNotification", "-", { "Ref": "env" } ] ] } ] }, "Principal": { "Fn::Sub": [ "pinpoint.${region}.amazonaws.com", { "region": { "Ref": "AWS::Region" } } ] }, "SourceArn": { "Fn::Sub": [ "arn:aws:mobiletargeting:${region}:${account}:/apps/*", { "region": { "Ref": "AWS::Region" }, "account": { "Ref": "AWS::AccountId" } } ] } } },
Save the file. This code will set the permissions so that AWS Pinpoint can invoke the Lambda as a hook. You have to do a separate push. If you try to do it with the previous push it can be the case that not all services are pushed when you try to set the permissions.
amplify push
Go to:
Amplify > backend > api > name of your api > open schema.graphql
Now the functions have been deployed we need to update also our schema. Put this code in schema.graphql. It will create an extra mutation so you can invoke the functions in your app.
type User @model { id: ID! name: String! email: String! expoToken: String } type Mutation { pinpoint(input: pinpointInput): pinpointResult @function(name: "pinpoint-${env}") } type pinpointResult { statusCode: Int body: String } input pinpointInput { token: String! name: String! email: String! message: String! id: String! }
Do another push
amplify push
- Are you sure you want to continue? Y
Go to the root of your project, then to src directory > graphql > mutations.js check if this code is there, if not please add and save it:
export const pinpoint = /* GraphQL */ ` mutation pinpoint($input: pinpointInput!) { pinpoint(input: $input) { statusCode body } } `;
Add some data via Cognito and AppSync
Go in the console to AWS Cognito and click on Manager User Pools > then on your user pool > user and groups > create user. Fill in the form and leave all the checkboxes as verified. Click on the new user and make a note of the sub value (something like b14cc22-c73f-4775-afd7-b54f222q4758) and then go to App Clients in the menu and make a note of the App client ID from the clientWeb (the bottom one) use these values in the next step.
Let’s add some data which you can use in your app. Go to the AppSync service in the console.
- Go to AWS AppSync via the console.
- Open your project
- Click on Queries
- Log in with a Cognito user by clicking on the button 'Login via Cognito User Pools' (You can create a user via Cognito in the console or via your App) (Use the data that your have written down)
- Add the following code and run the code (update with your e-mail address):
mutation PutUser { createUser( input: { id: "b14cc22-c73f-4775-afd7-b54f222q4758", name: "Ramon", email: "<EMAILADDRESS>" } ){ id name email } }
Let's build the React Native App
I made a simple (and a little bit ugly, everything in two components) app where a user needs to log in, we will get his user profile, look if there is valid ExpoToken available, if not then we request one and save that in the profile. In the app this user can make a message that will be send through a push notification and email to the user
Go to the root of your project and open App.js and replace it with this code:
import React from "react"; import { withAuthenticator } from "aws-amplify-react-native"; import Amplify, { Analytics } from "aws-amplify"; // Get the aws resources configuration parameters import awsconfig from "./aws-exports"; // if you are using Amplify CLI import Main from "./src/Main"; Amplify.configure(awsconfig); Analytics.disable(); // disabled analytics otherwise you get annoying messages class App extends React.Component { render() { return <Main />; } } export default withAuthenticator(App);
This will import everything you need and wraps your app with a HOC withAuthenticator. This creates login and signup functionality for your app.
Now create a file in the src folder with this name: Main.js and paste the following code:
import React from "react"; import { View, TextInput, Button } from "react-native"; import * as queries from "./graphql/queries.js"; import * as mutations from "./graphql/mutations"; import { API, graphqlOperation, Auth } from "aws-amplify"; import { Notifications } from "expo"; import * as Permissions from "expo-permissions"; class Main extends React.Component { constructor(props) { super(props); this.state = { profile: {}, message: "", user: "" }; this.handleSubmit = this.handleSubmit.bind(this); } async componentDidMount() { const user = await Auth.currentSession() .then(data => { this.setState({ user: data.idToken.payload.sub }); return data.idToken.payload.sub; }) .catch(err => console.log(err)); const profile = await this.getUserProfile(user); // There is no expoToken available yet, so we will request that and save it into the profile if (profile.expoToken === null) { const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS); if (status !== "granted") { alert("No notification permissions!"); return; } let token = await Notifications.getExpoPushTokenAsync(); // Only update the profile with the expoToken if it not exists yet if (token !== "") { const inputParams = { id: user, expoToken: token }; await API.graphql( graphqlOperation(mutations.updateUser, { input: inputParams }) ) .then(result => { console.log(result); }) .catch(err => console.log(err)); } } } async getUserProfile(sub) { const result = await API.graphql( graphqlOperation(queries.getUser, { id: sub }) ) .then(result => { this.setState({ profile: result.data.getUser }); return result.data.getUser; }) .catch(err => console.log(err)); return result; } async handleSubmit() { const inputParams = { message: this.state.message, token: this.state.profile.expoToken, name: this.state.profile.name, email: this.state.profile.email, id: this.state.user }; await API.graphql( graphqlOperation(mutations.pinpoint, { input: inputParams }) ) .then(result => { console.log(result); console.log("success"); this.setState({ message: "" }); }) .catch(err => console.log(err)); } render() { return ( <View style={{ marginTop: 80, marginLeft: 10, marginRight: 10 }}> <TextInput placeholder="Your push message" value={this.state.message} onChangeText={input => this.setState({ message: input })} style={{ paddingLeft: 5, height: 40, fontSize: 16, marginBottom: 6, marginTop: 2 }} ></TextInput> <Button title="Submit" onPress={this.handleSubmit} /> </View> ); } } export default Main;
Your app is ready and you can start it from your root project with:
expo start"
You need to install Expo client on a physical device and start the app otherwise you can't test the push notifications. Sign in with the user that you have created via AWS Cognito, fill in a push message, wait a few seconds .... et voilà .... you have received a push message in the app and an email message on your account.
Conclusion
It is really amazing how you can deliver these features fast to your customers with these great tools (AWS Amplify, React Native and Expo). Your app is ready to get your customers engaged :)
I was struggling with getting push notifications up and running while still keeping all the tools onboard so I can benefit from it. I had to think beyond the current limitations and that is how I came up with this architecture and implementation.
I hope you liked this guide and I am looking forward for your feedback in the comments or please share the projects where you have implemented this set up. Happy coding!
See github for the actual code: []
Discussion (2)
Using React Native AWS Amplify, AWS amplify and AWS CLI to set up the push notification in React Native app based on the expo ecosystem. Configuring GraphQL and aws-apk as well. This article provides a lot and delivers stepwise detailed integration of the overall AWS Amplify feature in the expo ecosystem. Highly recommended for beginners using expo for React Native app development.
Hello rpostulart, thank you for your guides. Much appreciated.
I would like to share some thoughts.
If we only consider push notifications then Pinpoint isn't really necessary right? Either ExpoServer.
You could go straight ahead and send the payload via fetch in your lambda, like in the Expo Docs:
So I assume you have included pinpoint only to demonstrate how these tools can be combined in a user engagement case. But unlikely the email delivery you would still not be able to track whether your push notification has been delivered or not, right? Or am I missing something?
Some observations in case people don't figure it out:
Thanks rpostulart! | https://practicaldev-herokuapp-com.global.ssl.fastly.net/aws-builders/the-guide-to-implement-push-notifications-with-react-native-expo-and-aws-amplify-4imn | CC-MAIN-2021-10 | refinedweb | 3,159 | 55.44 |
Varnish and BBR: Lower Latency OTT Video Delivery
Varnish and BBR: Lower Latency OTT Video Delivery
This tutorial will cover implementing over-the-top video over congested networks while also keeping your latency low and removing bottlenecks.
Join the DZone community and get the full member experience.Join For Free
When delivering video over-the-top (OTT), the internet is the principal highway for distributing this content. However, OTT streaming delivery requires something faster than what the internet offers in terms of how chunks/fragments are supposed to flow. Currently, publicly available wifi hotspots are the preferred networks for video consumption, but poor network infrastructure also leads to unbearable video buffering and latency.
A congested network slows down response times and directly affects the quality of service and experience of your video applications and services. Most video consumers have experienced — and not at all enjoyed — this aspect of video streaming.
The challenge, then, is to find ways to improve response time over congested networks, as the amount of traffic is only going to increase.
Varnish and Bottleneck Bandwidth and Round-trip (BBR)
Varnish is ideal for video delivery, ensuring high-performance HTTP delivery over video streaming, making up part of your media caching strategy through reliable and scalable architecture for heavy video content distribution. Naturally it helps if the network is in good shape, but if it isn’t the client response time suffers, and some mitigation will be required to minimize latency coming from TCP/IP layers.
Varnish allows for more in-depth configurations via a Varnish module (vmod-tcp), minimizing the impact of a congested network by choosing the suitable TCP/IP control algorithms proposed and developed over the years and released mostly on top of Linux operating system kernels. But with BBR we can go beyond this.
Results from a real OTT video scenario show a significant reduction in the response time from both SD (standard definition) and HD (high definition) video qualities. The combined power enabling Varnish and BBR indicates demonstrable latency reduction in delivering video chunks over congested networks.
What Is BBR?
BBR ("Bottleneck Bandwidth and Round-trip propagation time") is a new network congestion algorithm developed by Google designed to respond quickly to actual network congestion, resulting in a fair utilization of network bandwidth available with more accurate TCP/IP end-to-end congestion control decisions.
BBR relies on a network's delivery rate (maximum recent bandwidth available) and minimum round-trip-time delay in order to decide how fast to send data over the network, minimizing bufferbloat effects during the content delivery process (learn more about BBR and bufferbloat).
How Easy Is it to Enable BBR in Varnish?
BBR is easy to deploy and enable in VCL territory. BBR only requires updates on the server side, and it doesn't require video clients/players to have any special support. BBR is available if you’re using a 4.10+ Linux kernel distribution mostly for Ubuntu and Debian; otherwise a kernel update will be required (see how to install BBR on CentOS 7).
To check which flavors are available in your Linux server distribution, you just need to type in a Linux terminal:
sudo sysctl net.ipv4.tcp_available_congestion_control
Example output:
net.ipv4.tcp_available_congestion_control = reno cubic bbr
Using BBR In VCL territory
vcl 4.1;
import tcp;
backend default { .host = "127.0.0.1"; .port = "8080"; }
sub vcl_recv
{
#writes TCP_INFO into varnishlog.
tcp.dump_info();
#enables BBR in your VCL.
set req.http.x-tcp = tcp.congestion_algorithm("bbr");
}
Note that you can also play around with different delays toward a more dynamic PACE and switch between different congestion control protocols (see vmod-tcp docs for more details).
Checking if BBR Is Enabled Into varnishlog
-
How About Performance Improvements?
Now that we know how easy is to enable BBR in your VCL, let’s analyze some promising BBR results against the CUBIC and RENO standards. The evaluation scenario is composed of a client and server: the client is responsible for consuming different video chunks over the internet, and Varnish acts as origin protection in this case, serving video chunks directly from the edge.
Client (CPU: 2.2 GHz Intel Core i7):
- Is connected in a wifi hotspot and performs requests to one of our Varnish Enterprise servers, running Varnish Enterprise Version 6.0.
- Requests 2 different chunks size: 1.2 MB (SD) and 5MB (HD) over Mpeg-Dash (.m4s) ABR technology.
- On top of client-to-server communication, an internet link latency is added (200ms).
Varnish Enterprise 6.0 Server (CPU: Intel Gold 6140 @ 2.30GHz):
- Varnish-plus-6.0.5r1 running at Centos 7.5 (5.3.8-1.el7.elrepo.x86_64 kernel version).
- Runs VCL () that enables switching between different TCP/IP congestion control protocols.
- BBR, RENO and CUBIC were the set of congestion protocols evaluated.
- Tested using FQ Fair Queue traffic policing enabled.
(100 samples were taken for each protocol with 95% Confidence Interval)
Varnish and BBR presents greater stability and reduces the request latency times for SD (chunk size ~ 1.2MB) and HD (chunk size ~ 5MB) video chunks by two to three times. The comparison results clearly state the advantage of using Varnish and BBR (best case) enabled in the VCL in comparison to Varnish and RENO (worst case) and Varnish and CUBIC (acceptable case). The results enable us to conclude that using Varnish and BBR helps to reduce latencies over congested networks in OTT video streaming scenarios.
Minimize Latency: Improve Video QoE
Varnish and BBR together are a great combination proven to minimize unexpected video latency and to increase the quality of experience for video consumers with less buffering, especially for OTT video streaming delivery that relies on the client’s internet traffic for video edge delivery. Many Varnish customers have experienced this performance boost.
Varnish and BBR for OTT video use cases might be right for your video infrastructure. Here we have used the Varnish module vmod-tcp, which is a part of the Varnish Enterprise module family (see VMODS). If you are a Varnish Enterprise customer, you are already benefiting from it, and can simply “import tcp;” module in your VCL. Here are some of our recommended readings:
- Varnish Enterprise Streaming Server
- Three features that make Varnish ideal for video streaming
- Massive Storage Engine for caching huge video-on-demand (VoD) catalogs.
Note: The “initcwnd” initial congestion window (see Initcwnd settings of major CDN providers) parameter may help to increase performance as well. For now, we have focused on measuring Varnish and BBR without tuning any TCP/IP and kernel parameters. We would welcome hearing about your experiences in this area.
Stay tuned, as this is the first in a series of blog posts tackling OTT video performance achievements including low latency ABR (adaptive bitrate) video technologies with SSL/TLS security transmissions.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/varnish-and-bbr-lower-latency-ott-video-delivery | CC-MAIN-2020-24 | refinedweb | 1,152 | 53.21 |
Clearance is now a Rails engine…BLAOW!
Why
Clearance has served us well for many months. Our only complaints were shared by others:
- lots of includes
- too much generated code
- too many tests to maintain
- sometimes awkward to override functionality
With the re-institution of Rails engines in Rails 2.3, we decided to convert Clearance to engine. The process was relatively painless, the code is far cleaner, and we think we were able to scratch all our itches.
Philosophy.
Overriding.
- Write your tests for whatever action you want to add or override.
- Subclass one of Clearance’s controllers (
Users,
Sessions,
Passwords, and
Confirmations).
- Update your routes (by default, the routes will point to the namespaced Clearance controllers).
The Royal Library of Alexandria
All knowledge pertaining to Clearance can be found on its Github wiki, where you’ll find such articles as:
- Upgrading to Rails engine
- Organization of modules, routes, & flashes
- Extending Clearance with usernames, admins, or invite codes
.. and much more.
Enjoy! | https://robots.thoughtbot.com/clearance-is-a-rails-engine | CC-MAIN-2016-50 | refinedweb | 163 | 63.9 |
Hackers Counter Microsoft COFEE With Some DECAF 154.
DECAF: A welcoming news (Score:2, Insightful)
Less innocent people will be going to jail. Less family will be broke up.
The time has come to rise against the machine.
Re:DECAF: A welcoming news (Score:5, Funny)
I prefer to RAGE against the machine.
BAH-duh BAH BAH-duh BAH DAH-duh.
Re:DECAF: A welcoming news (Score:5, Funny)
Coding in the name of!
Re:DECAF: A welcoming news (Score:5, Funny)
Fuck you, I won't code what you tell me!
Re:DECAF: A welcoming news (Score:5, Funny)
are the same that hate bosses
Re: (Score:3)
From the Facebook group: "Fed up of Simon Cowell's latest karaoke act being Christmas No. 1? Me too
I've bought it from iTunes, Amazon, and re-bought the album in my local HMV. Get it done, people.
Re: (Score:2)
I've bought 3 copies and am looking forward to not having a karaoke number 1.
Re: (Score:3, Insightful)
Re: (Score:2)
I'm waiting for the "National ID card is a bad idea. Let's get it abandoned" group. Also called the "Vote for anyone but Labour" group.
Re: (Score:2)
It's not about populatiry, it's about proving that the public en masse can change anything they want.
True, as long as it is of no consequence. Anything business or government really want will come about one way or another... keeping people occupied with mindless drivel like entertainment just makes it all easier.
Oh, someone is at the doo
Re: (Score:2)
Rome wasn't built in a day, nor was it destroyed as such. I'm not promoting anarchy or disestablishmentarianism, but just that democracy is still possible. All it needs is for people to learn to get their news from multiple sources, check facts, read a little more, and investigate even a tiny amount into the back-hand / poison pill policies which are charged through Parliament on the back of "Think of the Children" / "Terrorism is bad!" legislation
But... (Score:2)
I'm also fed up with Rages " Lets venerate burglars who murder old people" misguided lyrics and their "lets make socialism acceptable so we can sell lots of Che T-Shirts at Hot Topic" attitude along with the guitarists " lack of technical expertise on a Whammy pedal, rendering it an misused, overused cliche for those of us who use it seriously."
So maybe we should buy someone who isn't prepackaged industry approved rock and roll rebellion.
Or better yet quit worrying about who's o
Re: (Score:2)
You might think it's small fry changing the outcome of the Christmas charts, but what if the next Facebook group is "Labour are shafting our rights. Let's get them out!"
Township called Rebellion indeed.
Re: (Score:2)
You win! By far the best!
Re: (Score:2)
Welcome, my son, welcome to the machine.
Re: (Score:3, Insightful)
Less innocent people will be going to jail. Less family will be broke up. [sic]
Any particular reason to think innocent people are more likely to use DECAF than the guilty? I fail to see why technical savvy should be correlated with innocence or guilt.
Re: (Score:2)
I fail to see why technical savvy should be correlated with innocence or guilt.
What exactly do you correlate Microsoft with? They routinely code more backdoors than a brothel, you really think their involvement with law enforcement won't backfire? Like you suggest, criminals are tech savvy too.
Re: (Score:3, Informative)
Note that the GP didn't say it will put disproportionally fewer innocent people - only that there will be fewer innocent people.
Fixed it for you. You and the OP made the same mistake. It's like nails on a chalk board, honestly!
You can have fewer innocent people or you can have less innocent people, but it means different things. Less innocent people are not as innocent, fewer innocent people are of a smaller number.
Re: (Score:2)
no wonder I screw up big time on Verbal section of the GRE test.
Perfect trojan horse (Score:5, Insightful).
Re: (Score:2)
Re:Perfect trojan horse (Score:5, Insightful)
And even if they post code, they could just post any old source code and claim it was used to generate the executable.
Well yeah, until someone who has an I.Q. greater than a water buffalo compiles the source code and finds out that it doesn't match up with the finished DECAF product...
That's the point of having source code out there in the first place. It can be inspected for everything from your everyday uh-ohs to your big time no-nos.
Re: (Score:2, Insightful)
And then some one with a little higher I.Q. takes the time to do something fun like disassemble the executable or hell, use wireshark to capture any network traffic the program might generate to see what it is actually doing.
Re:Perfect trojan horse (Score:4, Informative)
It's
.NET and they ran Dotfuscator over it, so you're going to have to graduate past bovine intelligence on this one.
Re: (Score:2)
I once tried to decompile a obfuscated
.NET app. It's definitely possible to figure it out, since all the calls to the CLI, etc. are the same, but it can be pretty tricky when every function and class name looks like a GUID.
But if you have the time, it's definitely possible to deconstruct it.
EDIT: I just downloaded it and took a look at the code in Reflector. It seems pretty simple (only 5 classes and the settings namespace isn't obfuscated). Anyone familiar with
.NET with about an hour of free time and the
Re: (Score:2)
If this is true then the NSA got a lot lazier, a lot more efficient, and a lot more effective. The Soviets pioneered denouncing your neighbors but this is one better.
Re:
Re: (Score:1)
This is the beauty of Open Source - you can build your own binaries when paranoid
:)
Re: (Score:2)
decaf.exe.config - no disassembly needed.
<setting name="NotifyUser" serializeAs="String">
<value>False</value>
</setting>
Re: (Score:2).
Your distrust in Microsoft is totally unwarran....
Oh, nevermind... I cant even type that with a straight face...
;-)
no source? it's a trap! (Score:1, Interesting)
Re: (Score:2)
No, that's XPRESO.
Re: (Score:3, Funny)
That's right, it's a frappe!
Microsue (Score:3, Funny)
Oh Microsoft.... is there *anything* that can't be handled by a lawsuit?
The Site... (Score:5, Informative) [decafme.org]
Re: (Score:1, Funny)
Decaf2000?
DecafXP?
DecafVista?
Decaf7?
Re: (Score:2)
So let me get this straight... (Score:5, Insightful)
Re:So let me get this straight... (Score:4, Informative)
So, set up a VM and then port it through WireShark. It shouldn't be too hard to figure out if it's communicating with some central server.
Re: (Score:2)
Communicating to some central server when you run it at least. If it stores the data and sends it on a different date you wouldn't know too easily.
Besides, it may be doing something other than sending off your data.. e.g encrypting it and ransoming you for the key to decrypt it.
Re: (Score:2)
Yeah, because it's not possible for programs to detect they're running in a VM...
Re: c
Re: (Score:2)
That seems like overkill, plus you won't know if it's installing a trojan that activates later. If you're familiar with
.NET just open it up in Reflector - even though it's obfuscated, any use of the .NET libraries like System.Net.Sockets will be in plain text.
Re:So let me get this straight... (Score:5, Funny)
Re: (Score:2)
Re: (Score:2)
Re: (Score:1)
Well you see it's like this. The OP made a statement that was a tad too broad and could be misconstrued if more than was intended was read into it. When you take a situation like that, then you add in the conversational construct known as "humor" then you arrive at one of those so-called "jokes". This "joke" is intended to result in a reflex reaction in the reader, consisting of successive, rapid contractions of the diaphragm, often accompanied by a facial expressi
Re: (Score:2)
"what the heck, where did that come from?" funny.
Now known on the Internet as "LOL SO RANDOM".
Re: (Score:2)
Re: (Score:2)
For your private information it is too late. Your info is already on closed source and quite probably badly maintained/secured computers.
Disable autorun, lock your computer (Score:5, Informative)
AFAIK, if your computer is locked COFEE relies on autorun to work, so disable autorun and lock your computer will pretty much thwart COFEE, since it would somehow require bypassing MS's supplied GINA dll, which given it's Microsoft, might know how to do, but would find it highly unlikely.
Re: (Score:1)
Re: (Score:2)
COFFEE is designed to circumvent on disk encryption. To do this it gets the keys from the running system. So it is actually perfectly reasonable that they used autorun given that it runs stuff even when the screen is locked.
Re: (Score:2, Interesting)
So it is actually perfectly reasonable that they used autorun given that it runs stuff even when the screen is locked.
Yeah, it does... in Windows 95.
Re: (Score:2) b
Re: (Score:1, Informative)
I'm sure more competant forensics people don't pull the plug. Instead they would keep the machine up and running and capture it in that state, using clips to keep it fed the voltage as it gets loaded onto a vehicle and until it gets to the forensics area. There, you use a PCI or IEEE 1394 card to dump the box's RAM.
Then, the hard disk gets imaged via a hardware write blocker (very important), the decryption keys in RAM used to decrypt the image of the HDD, and the search for whatever stuff (after ACTA, an
Easy fix for live-moving (Score:2)
Re: (Score:2)
You could use an accelerometer or a ball-and-cup arrangement similar to a seat belt locking mechanism (very sensitive, especially on newer cars.
Or the status of the USB cable plugged into the huge laser printer next to your desk, or whether eth0 is up, or by using the built-in GPS (if there is one) or the external GPS (labeled "TIME") to establish plausible deniability.
Honestly, there are about a million things you could check to have a good idea that your computer isn't being moved.
Re: (Score:2)
Read the instructions. It works with autorun, but if autorun is disabled you're suppose to use the file manager to browse to the USB device and execute it.
If you really read into the COFEE instructions, you'd see it doesn't give too much up. Well, it says a lot, but not about 3rd party software. It mostly gives standard MS stuff from the registry. Decrypted login passwords, what's set to run at boot time, etc. It would be a good forensic tool for cleaning up after a break
Re: (Score:2)
but if autorun is disabled you're suppose to use the file manager to browse to the USB device and execute it.
That is why I said lock the computer, then they can't get to the file manager.
Re: (Score:2)
$ apt-cache search GINA dll
$
Dammit, now I can't check out COFEE
:(
Not open source (Score:2)
>The article notes that DECAF is not open source, so you aren't really going to know for sure what it will do to your computer.
And most people running MS-Windows know for sure what THAT will do to their computers?
Does seem odd, though, that DECAF would not be open so people (in the know) would trust it and could learn from it. Oh well.
This is the best idea they've come up with yet... (Score:4, Insightful)
...to distribute rootkits and create botnets. Even better than those "Free Antivirus Software" downloads.
Seriously, is anybody going to trust something like this without the source? Somebody intelligent enough not to open unsolicited email attachments, at any rate.
(And yes, I realize there might be "legitimate" reasons for keeping the source out of law enforcement's hands, but frankly [at risk of trolling] I would rather be spied on by the government than identity thieves.)
Re:This is the best idea they've come up with yet. (Score:2)
When was the last time you read the source of an application to audit it?
Re: (Score:2)
And yes, I realize there might be “legitimate” reasons for keeping the source out of law enforcement&s hands [...]
WTH? Machine code IS source code! Just in another language that is a tiny bit harder to read (assisted by tools). So there really is no real point in hiding the source code. Everybody who wants to look at what it does, can still do that.
How else would the CPU know what to do with it?
It’s sad, when even on Slashdot, people think that “closed” source would be anymore than security trough obscurity theater.
Re: (Score:2)
Sure, it's security through obscurity.
And sometimes, security through obscurity works.
... for long enough. Sure, you can disassemble megabytes of machine code. But if it takes man-years to read enough to know what it is doing, you still win if the people reading it take real-years to get practical results.
It's that you can't really know how much effort people are putting into defeating the obscurity, and how much success they are having until "too late", that makes security through obscurity so unreliabl
Re: (Score:2)
It's
.NET and they ran Dotfuscator over it, so it's not that simple. At this point it's pretty damned obscure.
Re: (Score:2)
Even obfuscated, it's only 5 classes (which reference an unobfuscated settings namespace that gives you a little more info). Anyone familiar with
.NET with some time on their hands could reverse engineer it.
Meh... (Score:1)
I think I'll just stick to Pepsi
Arguments (Score:5, Insightful)
Re: (Score:3, Insightful)
One would think that Microsoft has little to no problems doing this without the source.
Re: (Score:2)
Re: (Score:2)
One would think that Microsoft has little to no problems doing this without the source.
It's written in
.NET, so even though it's obfuscated it's not that hard to reverse engineer it using Reflector. If I (a teenager who only dabbles in coding) could reverse engineer it in a few hours*, I have little doubt that some MS employee who is being paid to do so could figure it out in under a week.
*I have not reverse engineered it, but I have looked at the source, so I can say that it really isn't that complex.
Re: (Score:1)
Re: (Score:2)
I just did a Google search to see if anyone has reported it to be a virus and found nothing. It's probably safe.
I'm installing it now. I'll let you know what hap
Perhaps there is more here than meets the eye. (Score:1)
Please... (Score:2)
Confused? (Score:2, Redundant)
Re: (Score:3, Funny)
Cofee attempts to decrypt your drive.
Just wait!!! (Score:5, Funny)
Soon I'll Release my Beta version of FRENCH VANILA
(Forensic Reducing Emulator Named Coherantly and Handsomely for Very Awesome Naughty and Illicit Activities)
Best DECAF is.... (Score:1)
Wait, what--? (Score:4, Insightful)
...so you aren't really going to know for sure what it will do to your computer.
You're saying you don't know how to run a debugger in a VM session? or registry and file monitoring utilities? I get that analyzing machine code may be a bit of a lost art, but if you have the binary file you have everything you need to figure out what it does -- eventually. Someone will reverse-engineer it. In fact, I rather expect the authors knew this when they released it.
Re: (Score:2)
if you have the binary file you have everything you need to figure out what it does
It's even better than that.
.NET EXEs actually contain MSIL (a type of intermediate language) and are easily decompiled into the original source code (or something resembling it). DECAF has been obfuscated (all the variable/function/class names changed to meaningless letters), but it's simple enough that you could figure it out in under an hour, if you're familiar with .NET, especially since system libraries (e.g. System.Net.Sockets) will be referenced in plain text.
simple tools (Score:2)
There is so much more COFEE should have done. It looks like it takes a look at your current running state. It grabs netwrok connections you have open, running processes, and user account names that are logged in. Things that get lost when you power a computer off. The autorun is just to make it simple for the user. I don't expect this is the only tool ran. I expect it is quick snapshot before you pull the plug.
Microsoft did take care to get the correct versions of the tools for each OS. You know how yo
OT: Aaaaaagh! (Score:2)
Im a gamer, not a grammer major. This post is full of spelling and grammer mistakes.
Head... exploding... you evil.. bastard...
I am confused. (Score:2, Insightful)
Re: (Score:2)
No, you're not confused.
Re: (Score:2)
Umm, because the password used to encrypt the data is on the SAME PC ?
Or to use a car analogy, the things inside a locked car are safe, unless you leave the keys in the lock.
WINNAR! (Score:2)
there is a built-in method for bypassing its security features
Ding ding ding ding ding!
And what does the COFEE generated data prove? (Score:2)
Seriously, what does COFEE generated data prove? If my computer would run XP and for some reason some official would want to plug a USB stick with the label "COFEE" into it, then what ever data they claim to find I could deny easily that it was mine. After all, on the USB stick there could have been ANY program which plants ANY data on the computer it was plugged into!
As far as I know, part of proper computer forensics work is to first (!) dublicate the hard drive in question, then generate a checksum for b
Re: (Score:2)
It proves you don't know much about computer forensics, that's for sure.
Re: (Score:2)
It was forseen! (Score:1)
You don't understand! The cat *is* out of the bag! (Score:2)
People, you don't understand what this means !!
This marks an end of an era ! Up until now investigators could be pretty comfortable assuming that their forensics analysis were giving off accurate data about the use and activity of the computer. Tools to analyse file, network and disk access are based on the assumption that the metadata has not been tampered with.
It is enough that you download and run this program every now and then to render every analysis of your computer pretty meaningless as eviden
Re:LiveCD (Score:4, Funny)
I first encrypted all my temporary data, encrypted everything in cache, it was a sweet algorithm. But I figured that wasn't enough, an onion-rings didn't help either. (I tried, I failed.)
So then I decided to use my PC without keyboard, so they couldn't log my keystrokes or via processing the audio for my keystrokes discover what I was typing. From there up, everything was a success, I could later remove my monitor so noone could see what I was doing and I could just imagine keyboardinupt on my PC.
I wasn't ever so productive and most of all SECURE.
Soon enough, I felt my mousemovements could also be secured by removing my mouse. Once I mastered this way of working, they suggested I also could work without turning on my PC, as they could measure my work by reading radiation from my CPU "if they really would be wanting to read my work", just tossing out my HD wasn't sufficient. So, right now, I'm 100% secure, sitting at my desk, imagening my work.
I did read something about mindreading, but I think that's just FUD.
Re: (Score:2)
Half of the services on Windows try to access DNS. Even mundane stuff you wouldn't think of like Print Spoolers etc
... it's for network exploration, to see what's connected to your network, mostly (in little-girl-from-Aliens-voice).
Re: (Score:2)
Not surprised at all the typical slashdot anti-law enforcement rhetoric in here... especially all of the "innocent people will be saved!" statements. But I *am* a bit surprised that some of the commenters have said what they have. Do this many people really not want truly guilty people caught and prosecuted?
I suspect your average Slashdotter is more concerned with the Fourth Amendment rights that prosecutors as a whole like to ignore when they're trying to build a case against someone who's alleged to have committed a crime.
Re: (Score:2)
For 8 years running, the entire fucking federal government ignored the 4th amendment, which may very well be continuing. This is not some sort of extra paragraph that has to be stricken from court records. It's rampant, it's all over. FISA means nothing to you? The fact that it is a sufficient way to get wiretaps on the bad guys, but NO! It's not ENOUGH, we need REAL TIME monitoring of EVERYBODY (with AT&T's help).
You don't see it because you are one of them. Strange, how every cop or wannabe cop is
Re: (Score:2)
Do this many people really not want truly guilty people caught and prosecuted?
Guilty of what and at the expense of what? Could you cite specific examples, as you seem so eager to chastise others for failing to provide?
I don't want people truly guilty [alternet.org] of possessing marijuana to be caught and prosecuted. I don't want people truly guilty [stateofprotest.com] of indulging in whimsical fantasies involving fictional characters to be caught and prosecuted. I don't want people truly guilty [arstechnica.com] of copyright infringement to be caught and prosecuted. Had this been some years ago I would not have wanted people truly gui [belfasttelegraph.co.uk] | http://tech.slashdot.org/story/09/12/16/0239231/Hackers-Counter-Microsoft-COFEE-With-Some-DECAF | CC-MAIN-2015-32 | refinedweb | 3,817 | 73.07 |
writers will block, waiting for the first thread's transaction to complete (or to be aborted).
Here is an example function that does transaction-protected increments on database records to ensure isolation:. */ db_open(dbenv, &db_fruit, "fruit", 0); /* Open database: Key is a color; Data is an integer. */ db_open(dbenv, &db_color, "color", 0); /* * Open database: * Key is a name; Data is: company name, cat breeds. */ db_open(dbenv, &db_cats, "cats", 1); add_fruit(dbenv, db_fruit, "apple", "yellow delicious");, DB_RMW)) {, tid, &key, &data, 0)) { case 0: /* Success: commit the change. */ if ((ret = tid->commit(tid, 0)) != 0) { dbenv->err(dbenv, ret, "DB_TXN->commit"); exit (1); } return (0); case DB_LOCK_DEADLOCK: default: /* Retry the operation. */ if ((t_ret = tid->abort(tid)) != 0) { dbenv->err(dbenv, t_ret, "DB_TXN->abort"); exit (1); } if (fail++ == MAXIMUM_RETRY) return (ret); break; } } }
The DB_RMW flag in the DB->get() call specifies a write lock should be acquired on the key/data pair, instead of the more obvious read lock. We do this because the application expects to write the key/data pair in a subsequent operation, and the transaction is much more likely to deadlock if we first obtain a read lock and subsequently a write lock, than if we obtain the write lock initially. | http://docs.oracle.com/cd/E17276_01/html/programmer_reference/transapp_inc.html | CC-MAIN-2016-36 | refinedweb | 202 | 52.9 |
In many real-life systems, the state of the system is strictly binary. For example, a team can either win or lose, a stock can either go up or down, a patient can have a disease or not. A data scientist often encounters target variables that obey this type of duality. For instance, individual health metrics can be used to diagnose certain medical conditions, such as heart disease, or they can be used to confirm pregnancy. In these cases, the answer is either ‘yes’ or ‘no’, or ‘true’ or ‘false’. Mathematically, this can be represented as a ‘1’ or ‘0’, and can then be incorporated into a predictive model with other numerical health metrics. There are several statistical models constructed to identify binary variables such as these — the logistic model is one of them.
The logistic model is a model that uses the logistic function:
Where e is the natural logarithm base, x0 is the value of the sigmoid’s midpoint, L is the curve’s maximum y value, and k is the logistic growth rate. The function looks like this:
Note that the y values range from 0 to 1 (in this case, L is 1). In the case of the examples I listed, the target variable is either 0 or 1, and the logistic function outputs the probability of being in either state. This probability is determined by a linear combination of all the predictor variables. In this case, the model is a binary logistic regression, but it can be extended to multiple categorical variables. If this is the case, a probability for each categorical variable is produced, with the most probable state being chosen. This is known as multinomial logistic regression. This function is used for logistic regression, but it is not the only machine learning algorithm that uses it. At their foundation, neural nets use it as well.
When performing multinomial logistic regression on a dataset, the target variables cannot be ordinal or ranked. The algorithm also typically produces the best results when there are a low number of categories in the target variable. If you have a larger number, another machine learning algorithm would be better suited. For my example, we’ll pick a dataset that consists of three categories.
Implementing the Model. We will try to predict the correct cultivar of each wine based on a linear model created with the 13 features.
import pandas as pd from sklearn.linear_model import LogisticRegression import matplotlib.pyplot as pl) wine_df.Class = wine_df.Class - 1
We’ll first import the pandas library (Python Data Analysis Library) and the wine dataset, then convert the dataset to a pandas DataFrame. I’ll use the logistic regression algorithm from the scikit-learn package (refer to the documentation for help with any of the functions that I use in my code). To properly determine the efficacy of the model, we’ll split the dataset into a test and training set. This will allow us to train our model on a sample of the data, and then test it on data that it has not seen. Since we are using a linear model, the training will converge the coefficients of each term in the model to values that most accurately predict the highest probability for the correct class.) clf = LogisticRegression(solver='lbfgs',multi_class='multinomial') clf.fit(train_x, train_y) clf.score(test_x, test_y)
The score is the percentage of correct predictions in the test set. Ninety-four percent is pretty good for a first attempt. Feel free to change the solver method within the argument of LogisticRegression. Different methods will converge to more optimal coefficients and produce better scores. You can find more methods here. | https://sweetcode.io/machine-learning-multinomial-logistic-regression/ | CC-MAIN-2020-34 | refinedweb | 612 | 55.24 |
This be bootstrapping in the browser, as Angular 2 also lets us bootstrap in a WebWorker and on the server.
Most Angular 1.x apps start with
ng-app, which typically sits on the
<html> or
<body> tag of your application:
<!doctype html> <html ng- <head> <title>Angular 1.x</title> <script src="angular.js"></script> <script src="app.js"></script> <script src="app.component.js"></script> </head> <body> <my-app> Loading... </my-app> </body> </html>
For
ng-app to work, however, we actually need to create a "module". A module is essentially a container for logic that's specific to something in our application, such as a feature. The module name needs to correspond to the value passed into
ng-app, which in this case is just
"app". So we create the relevant module name as such:
// app.js angular.module('app', []);
And that's pretty much it; we have
ng-app and
angular.module() as the key ingredients to bootstrapping in this example.
The alternative way to bootstrapping in Angular 1.x is through use of the
angular.bootstrap method, which is a way to manually bootstrap single, or multiple Angular 1.x applications. The ingredients are the same, as
ng-app essentially calls the
bootstrap method for us. So using
angular.bootstrap gives us that exposed method to be able to manually bootstrap our app.
Again, we'll need an
angular.module() setup, and then we can bootstrap the application:
// app.js angular.module('app', []); angular.bootstrap(document.documentElement, ['app']);
So the
angular.bootstrap method's first argument is the DOM node you wish to mount your application to, and the second (optional) argument being an Array of module names you wish to bootstrap, which is typically just a single module. There is also a third (optional) argument for invoking our app in strictDi mode:
// app.js angular.module('app', []); angular.bootstrap(document.documentElement, ['app'], { strictDi: true });
When bootstrapping a "Hello world" in Angular 1.x, we'll need a root element. This element is the root container for our app, which we can create using the
.component() method:
// app.component.js const myApp = { template: ` <div> {{ $ctrl.text }} </div> `, controller() { this.$onInit = function () { this.text = 'Hello world'; }; } }; angular .module('app') .component('myApp', myApp);
That's "Hello world" status in Angular 1.x, so let's continue to Angular 2!
When it comes to Angular 2 bootstrapping, there are some notable changes. A few of them are: shift to TypeScript; using ES2015 modules; and
ng-app is no longer with us, though the concept of "modules" is still prevalent through the
@NgModule decorator.
There is also another new addition to bootstrapping, an absolute requirement for a root component/container for our app (we don't technically need a
<my-app> to get Angular 1.x alive and kicking). Let's roll through these and learn how to bootstrap in Angular 2.
For the purposes of the following code snippets, we're going to assume you've setup Angular 2 to cut out all the boilerplate stuff, we'll focus on the bootstrapping phase.
Just like with Angular 1.x, we need some HTML setup with our scripts, of which I'm going to be just using some CDN links. When you're developing, you'll want to use local ones.
<!doctype html> <html> <head> <title>Angular 2</title> <script src="//unpkg.com/zone.js@0.6.12/dist/zone.js"></script> <script src="//unpkg.com/reflect-metadata@0.1.3/Reflect.js"></script> <script src="//unpkg.com/systemjs@0.19.31/dist/system.js"></script> <script src="//unpkg.com/typescript@1.8.10/lib/typescript.js"></script> <script> System.config({ transpiler: 'typescript', typescriptOptions: { emitDecoratorMetadata: true }, paths: { 'npm:': '' }, map: { 'app': './src', '', 'rxjs': 'npm:rxjs' }, packages: { app: { main: './main.ts', defaultExtension: 'ts' }, rxjs: { defaultExtension: 'js' } } }); System .import('app') .catch(console.error.bind(console)); </script> </head> <body> <my-app> Loading... </my-app> </body> </html>
You'll ideally want to use System.js or Webpack to load your application – we're using System.js as you can see above. We're not going to go into details as to how System.js works, as it is outside the scope of the Angular migration guide.
Note how we're also using
<my-app> just like in the Angular 1.x example too, which gives us the absolute base we need to get started with Angular.
The next thing we need to do is create an Angular 2 module with
@NgModule. This is a high-level decorator that marks the application's entry point for that specific module, similar to
angular.module() in Angular 1.x. For this, we'll assume creation of
module.ts:
// module.ts import {NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import AppComponent from './app'; @NgModule({ imports: [BrowserModule], declarations: [AppComponent], bootstrap: [AppComponent] }) export class AppModule {}
From the above, we've imported
NgModule from the Angular core, and, using the decorator, we add the necessary metadata through
imports,
declarations and
bootstrap. We can specify
providers inside the decorator for the injector. We also now import the
BrowserModule and tell
@NgModule that this is the module we want to use. For more on
@NgModule, check the from angular.module to ngModule migration guide.
You'll also see we've imported the
AppComponent, which is what we need setup in the "Root Component" section shortly.
To bootstrap our Angular 2 app, we need to first import the necessities from
@angular, and then call the
bootstrap function:
// main.ts import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; platformBrowserDynamic();
Note that how we've used 'platform-browser-dynamic' to target the browser platform
Wait, this won't work just yet! The
platformBrowserDynamic function returns a few new methods on the
prototype chain that we can invoke. The one we need is
bootstrapModule, so let's call that:
// main.ts import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; platformBrowserDynamic().bootstrapModule();
Finally, we need to import our exported
AppModule decorated by
@NgModule, and pass it into the
bootstrapModule(); method call:
// main.ts import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {AppModule} from './module'; platformBrowserDynamic().bootstrapModule(AppModule);
The
bootstrapModule function we import gets invoked, and we pass in the
AppComponent reference, of which is going to be our "Root component" just like we saw in our Angular 1.x example.
As we're already importing
{App}, we need to create the component for it. Much like the
.component() syntax in Angular 1.x, we have a similar API called
@Component(), which is actually a TypeScript decorator. Note the similarity between an Angular 1.x
.component(), which contains a "controller". In Angular 2, controllers no longer exist, instead we use an ES2015 Class to contain this logic:
import {Component} from '@angular/core'; @Component({ selector: 'my-app', template: ` <div> {{ text }} </div> ` }) export default class App { public text: string; constructor() { this.text = 'Hello world!'; } }
Notable changes here are the new
selector property, which defines the name of the custom element. In this case, we're using
my-app, which corresponds across to
<my-app>. This is also a nicer change than the camelCase syntax we used for component/directive naming in Angular 1.x.
Pingback: Dew Drop - February 20, 2017 (#2425) - Morning Dew() | http://developer.telerik.com/topics/web-development/bootstrapping-browser-angular-2/ | CC-MAIN-2017-17 | refinedweb | 1,203 | 51.65 |
Forum: WixelHello, Tony.).
Forum: WixelI want to be able to test that it is actually transmitting the analog inputs but with only one green led staying solid the TX lights are out and not coming on since i wrote to it.
Forum: WixelHi, Wixels came in the mail today.
Forum: WixelHi.
Forum: WixelI have found that the Wixel Config Util does not write my new code to the wixel unless I close it then open it, pick the proper app file then click "Write to Wixel". I have tried several ways to avoid having to close and re-open the Util but nothing else seems to work (I moved up to v. 1.2 from 1.1 - did not help). I have tried recompiling the new code then - clicking write; clicking erase then clicking write; clicking stop app, clicking erase, then clicking write; nothing seems to work.
Forum: WixelOK, so I guess eclipse isn't really that well integrated with gcc.
Forum: WixelThe way Wixel apps get compiled is determined by the Wixel SDK's Makefile and Eclipse just runs "make" to use it. The settings you found don't affect the contents of the Makefile. You can compile apps without Eclipse.
Forum: WixelThat did the trick!!
Forum: WixelHello.
Forum: WixelI get the following:
Forum: WixelHi Jon, email did not turn up in any folders in my gmail or in the mailbox on here. Email gremlin ate it.
Forum: WixelI do not know of a program you can use like that to test code for the Wixel.
Forum: WixelHi Jonathan, Ive not received an email yet, perhaps its still sitting in someones buffer (checked other folders in my gmail.)
Forum: WixelI responded to an email from you yesterday asking about this same setup. In case you missed it, and for everyone else reading this: you should be able to use a pair of Wixels with your Simple Motor Controllers like that. However, you would have to write your own app to appropriately interpret your joystick commands and transmit them to the Wixel generating control signals for the SMC. (I recommend using serial commands.)
Forum: WixelHi, I volunteer at a disabled sailing club called Sailability.
Forum: WixelHi, nejcmedv.
Forum: WixelHello,
Forum: WixelNo, you cannot use the wireless serial app with more than two Wixels on the same channel because the protocol is not designed to handle that case.
Forum: WixelHello,
Forum: WixelHello David,
Forum: WixelHello.
Forum: WixelHello.
Timestep is not constant.
They are smaller as set on application on PC. This probably means I receive data faster than required.
Forum: WixelHello all,
Forum: WixelHello,
Forum: WixelDavid,
Forum: WixelHello, Keith.
This app allows you to wirelessly extend the reach of your microcontroller's I/O lines up to 50 feet using two or more Wixels.
Forum: WixelJeremy,
Forum: WixelYou might be able to find a way to send strings through the I/O Repeater App using a clever protocol, but it is probably not practical or recommended.
Forum: WixelThanks, Jeremy for your swift reply. I guess you are saying yes to my first question: That you can't send strings with the io_repeater app, correct?
Forum: WixelHello.
Forum: WixelDoes the io_repeater app only send digital data? I'm asking because I need to extend the range of an app I'm writing that sends strings from a PC through a Wixel to a remote Wixel that sits on an Arduino that displays the string on an LCD. I have this all working using the wireless serial app, but the range is too short. Here is the dataflow:
Forum: WixelYes, that was a typo on my part. The length variable should read "values".
Forum: WixelShouldn't you be using "sizeof(values)"?
Forum: WixelI thought that had something to do with it, that makes sense then.
typedef struct values
{
uint16 rawADC;
float temp;
int32 cTime;
} values;
memcpy(packet,values,sizeof(dataValues));
Forum: WixelHello, Dan.
packet[1] = rawADC;
packet[2] = Temp;
packet[3] = cTime;
Forum: WixelSo are you saying that the variable "Temp" declared as Float on the TX module isn't passed through to the RX module as a float? I did notice that if I change the function type to %d I get my temperature, just not in float form, it displays it as a whole number. This doesn't explain the other two data bytes though?
int32 CODE param_input_mode = 0;
int32 CODE param_send_delay = 2000;
int32 lastTx;
uint16 cTime;
uint16 rawADC;
float Temp;
Forum: Wixel
printf("%f\r\n",rxData[2]);
Forum: WixelI have a small project I'm working on for my house. I have two wixels right now setup as transmitter and receiver. The TX module has a thermistor and some fancy math on it to send it to the receiver. I plan on adding more functionality in the future but I thought I'd start small for now. I also have the TX module dump its data to the COM port just for display purposes at this point. The issue is, the data that's being output from the TX modules printf() statements are different from the RX modules. I've tried different formats %u %d %ld, etc and various integer types, nothing seems to work. Any help would be appreciated. I'm hoping its something I'm just overlooking.
uint8 XDATA * rxData;
// Check if there is a radio packet to report and space in the
// USB TX buffers to report it.
if ((rxData = radioQueueRxCurrentPacket()) && usbComTxAvailable() >= 64)
{
printf("%u\r\n",rxData[1]);
printf("%f\r\n",rxData[2]);
printf("%u\r\n",rxData[3]);
printf("\r\n\r\n");
radioQueueRxDoneWithPacket();
}
int32 CODE param_input_mode = 0;
int32 CODE param_send_delay = 2000;
int32 lastTx;
uint16 cTime;
uint16 rawADC;
float Temp;
int32 CODE param_input_mode = 0;
int32 CODE param_send_delay = 2000;
int32 lastTx;
uint16 cTime;
uint16 rawADC;
float Temp;
void grabTemp()
{
// Assuming a 10k Thermistor. Calculation is actually: Resistance = (4096/ADC)
//Resistance = ((20470000/RawADC) - 10000);
/******************************************************************/
/* Utilizes the Steinhart-Hart Thermistor Equation: */
/* Temperature in Kelvin = 1 / {A + B[ln(R)] + C[ln(R)]^3} */
/* where A = 0.001129148, B = 0.000234125 and C = 8.76741E-08 */
/******************************************************************/
rawADC = adcRead(0); //Grab ADC Reading
Temp = logf(((20470000/rawADC) - 10000));
//Temp = 1 / (0.003354016 + (0.000256985 * Temp) + (0.000002620131 * Temp * Temp * Temp));
Temp = 1 / (0.001129148 + (0.000234125 * Temp) + (0.0000000876741 * Temp * Temp * Temp));
Temp = Temp - 273.15; // Convert Kelvin to Celsius
Temp = (Temp * 9.0)/ 5.0 + 32.0; // Convert to Fahrenheit
cTime = getMs();
if ((getMs() - lastTx) >= param_send_delay)
{
lastTx = getMs();
printf("RawADC = %u\r\n",rawADC);
printf("Temperature = %f\r\n",Temp);
printf("CTime = %d\r\n",cTime/1000);
printf("\r\n\r\n");
}
}
void txData()
{
static uint16 lastTx = 0;
uint8 XDATA * packet;
if ((uint16)(getMs() - lastTx) >= param_send_delay && (packet = radioQueueTxCurrentPacket()))
{
lastTx = getMs();
//Length
packet[0] = 2; // must not exceed RADIO_QUEUE_PAYLOAD_SIZE
//Data
packet[1] = rawADC;
packet[2] = Temp;
packet[3] = cTime;
//Send
radioQueueTxSendPacket();
}
}
Forum: WixelYayy, got a free Wixel today from Waterott, what a nice service !!!
Forum: WixelThanks very much, Jeremy and Jonathan!
Forum: WixelGmorning
Forum: WixelSince it was working and is not now, it is likely that something probably got damaged. It would be up to Watterott if they want to replace your Wixel. Alternatively, if you contact us directly at support@pololu.com and reference this forum post, I might be able to help you with a discount on a replacement.
Forum: WixelHi, and thanks for the fast replys :)
Forum: WixelCould you measure the Wixel's VALT and 3V3 pins and verify they are outputting the correct voltage? Could you also try swapping your two Wixels used for transmitting and receiving and see if the problem follows the bad Wixel?
Forum: WixelHi, Albert.
Forum: WixelHi
Forum: WixelHello, Robert.
Forum: WixelHi
Forum: WixelHi Jon,
Forum: WixelHello, Albert.
Forum: WixelHello Jonathan,
Forum: WixelI do not think communicating over email would help much. We generally do not respond any quicker over email than over the forum. Also, keeping the discussion on the forum might help people who have a similar question, and it allows other members of the community a chance to jump in and help.
Forum: Wixelhi jonathan
Forum: WixelHello.
Forum: WixelPlease help me !
Forum: WixelHello.
Forum: WixelThanks Martan. Hopefully Pololu will attend to clarify the remaining ones.
Forum: WixelNumber four is not going to work, the Wixel does not have that sort of range. You might, on a good day, get 75ft or so.
Forum: WixelHi & thanks for providing such promising and advanced products.
Forum: WixelJust trying to find engineering solutions for stuff. I want to emphasize that the Wixel, in my initial application, performed really well. I put the master about a foot off the ground in the middle of my layout area and I had a good 50ft radius of solid control- as long as the destination node wasn't moving. I should also say that each Wixel would, with a healthy power supply- drive several standard servos over twisted wire to the tune of 100ft or so. So it's a pretty beefy little widget. It just depends on your application.
Forum: WixelHello, joep.
Forum: WixelNot to tout other manufacturers on the Pololu Board but you may want to look to other solutions rather than hacking about like this if you need range. Not to bash the Wixel, I had a blast writing code for mine and the range for me (outside) was a reasonable 50-60ft. For stationary things, it was fine but when I added moving vehicles, not so much. I won't go on about it here, I have more details on my blog if you are interested.
Forum: WixelTimely topic for me, so thanks!
Forum: WixelHello.
Forum: WixelHey guys,
Forum: WixelI would be surprised if the impedance matching components are the same for the "F" configuration and the 1/4 wave whip, but it seems possible. Does anyone know?
Forum: WixelFrom what I gather from the TI documents and the Wixel docs, a 1/4 wave monopole with ground
Forum: WixelThis is very useful information! Thanks for posting.
Forum: WixelI was trying using two wixels to monitor a tank level. The one wixel was connected to
Forum: WixelFor an app that demonstrates a more direct, raw way to receive packets from the radio, you might look at the test_radio_signal_rx app. This app uses the same radio register settings as the other apps, but it interacts with the radio in a simpler way so you are more likely to be able to change the radio settings without causing subtle timing issues.
Forum: WixelSo there are several registers that need to be updated (Sync Word, Modulation, data rate, etc). The sniffing app seems to be looking for more structure in the packets. I need something more raw.
Forum: WixelHello.
Forum: WixelHello,
Forum: WixelI did measure P1_1 to gnd while in PM2 sleep and it was 0V
Forum: WixelI.
Forum: WixelHere is the schematic. As mentioned the sensor is powered off P1_1. P1_7 is the UART RX
Forum: WixelHello, Martan.
Forum: WixelHello, Burke.
isPinHigh(1)
Forum: WixelI am using a wixel to control a Futaba S3114 servo. I have the following code, based on the test_servos app, "working" but not as I would expect. It does move the servo from side to side through about 90 degrees.
/** test_servos app:
*
* This app tests the servo library by using it to transmit servo pulses on
* all six available pins: P0_2, P0_3, P0_4, P1_2, P1_1, and P1_0.
*
* This is mainly intended for people who are changing the servo library. If
* you just want to use the library to control a servo from a Wixel, see the
* example_servo_sequence app.
*/
#include <cc2511_map.h>
#include <servo.h>
#include <wixel.h>
#include <usb.h>
#include <usb_com.h>
// Here we define what pins we will be using for servos. Our choice is:
// Servo 0 = P0_2
// Servo 1 = P0_3
// Servo 2 = P0_4
// Servo 3 = P1_2
// Servo 4 = P1_1
// Servo 5 = P1_0
uint8 CODE pins[] = {2, 3, 4, 12, 11, 10};
uint8 bStrikeMagnet = 0;
uint32 ulStartTime = 0;
void myServosInit()
{
// Start the servo library.
servosStart((uint8 XDATA *)pins, sizeof(pins));
// Set the speed of servo
servoSetSpeed(5, 0); // Not actually necessary because default speed is 0 (no speed limit).
}
void updateServos()
{
if ((getMs() - ulStartTime) < 1000)
{
servoSetTarget(5, 1000);
LED_YELLOW(0);
}
else if ((getMs() - ulStartTime) >= 1000 && (getMs() - ulStartTime) < 2000)
{
servoSetTarget(5, 1000);
LED_YELLOW(1);
}
else
{
bStrikeMagnet = 0;
}
}
// Takes care of receiving commands from the USB virtual COM port.
void receiveCommands()
{
if (usbComRxAvailable() == 0){ return; }
switch(usbComRxReceiveByte())
{
case 's': // Start/Stop
if (servosStarted())
{
servosStop();
}
else
{
servosStart(0, 0);
}
break;
}
}
void main()
{
systemInit();
usbInit();
myServosInit();
while(1)
{
boardService();
usbComService();
usbShowStatusWithGreenLed();
// if button is pushed then cycle servo back and forth once
if (!isPinHigh(1))
{
bStrikeMagnet = 1;
ulStartTime = getMs();
}
updateServos();
receiveCommands();
// The red LED will be on if any of the servos are moving.
LED_RED(servosMoving());
}
}
Forum: Wixel.
Forum: WixelI was able to track the issue down to my sensor circuit. The sensor was being powered from
Forum: WixelIf anyone is interested, I've posted up my Master/Slave code for the Wixel. These apps use the packet addressing feature of the TI chip to implement a round robin type protocol to control up to 64 slaves with each slave controlling up to 6 servos. It also supports 3 analog inputs back to the master from each slave. I've posted the source and exes in a zip file, apologies for not doing a git thing or similar but I made changes to some of the libraries and include files in the SDK (and forgot exactly where and what) so I just figured it would be best to grab an image.
Forum: WixelToday.
Forum: WixelI am glad you found out what was causing the problem, but it is too bad it came with the loss of your Wixel.
Forum: WixelThere is a sensor with power connected from P1_1 . Since I set all digital outputs to 0 / low before
Forum: WixelOK,.
Forum: WixelI think I figured it out, looks like the Wixel was on its dying breath or possibly some bad connection that I never saw fried it.
Forum: WixelHello.
Forum: WixelOK
Forum: WixelWixel is powered by battery ( 4xAAA )
void makeAllOutputs() {
int i;
for (i=0; i < 16; i++) {
setDigitalOutput(i, LOW);
}
}
Forum: WixelHello.
Forum: WixelI am having some issues using two Wixels in Wireless Serial App (both UART-Radio) mode.
Forum: WixelWere slasi's changes for radiomacsleep() / resume() ever merged into the SDK ? I am attempting
Forum: WixelJon
Forum: WixelHello.
Forum: WixelHi
Forum: WixelI started over again and downloaded the bundle for your site - everything is working fine!
Forum: WixelThe Wixel SDK is available as part of the Wixel Development Bundle, which you probably downloaded. The Pololu GNU Build Utilities are separate from the Wixel SDK but they are both included in the bundle. We do not distribute the SDK on SourceForge.
Forum: WixelHi David
Forum: WixelHello. | http://forum.pololu.com/atom.php?f=30 | CC-MAIN-2014-10 | refinedweb | 2,457 | 63.9 |
Acme::Pr0n - expose the naughty bits of modules to the world
use Acme::Pr0n qw( Regexp::English );
Acme::Pr0n exposes the naughty bits of other modules. Simply pass a list of module names you want to uncover, and everything (well, every function, anyway) normally hidden will be imported into your namespace.
It looks in @EXPORT and @EXPORT_OK, and ignores those. You can see those functions anyway. Where's the fun in that?
Please note that you must have loaded the module you want to leer at -- it's a little like consent. The victim module must also have a version greater than 0.18. If there's no version, Acme::Pr0n won't bother guessing. It will
carp(), so be ready for that.
None, by default. I suppose you could use this module on yourself, but you'll probably go blind if you do that. It's also under the age of consent.
Modules with custom
import()s are more or less immune. The author considers this to be a feature, at least until he writes Glob::Util. It's a surprisingly tricky problem.
chromatic (
chromatic at wgz dot org), with substantial thematic help from Michael G Schwern, Mark-Jason Dominus, Joel Noble, and Norm Nunley. Yikes. You really had to be there.
Dave Cross suggested looking in %INC. Go, Dave.
DJ Adams let me upload the initial version in the hallway at OSCON 2002 from his laptop. Now he's tainted too!
Juerd (
jwaalboer at convolution dot nl) suggested some POD fixes. Thanks! | http://search.cpan.org/dist/Acme-Pr0n/lib/Acme/Pr0n.pm | CC-MAIN-2015-06 | refinedweb | 254 | 76.93 |
/* * Copyright (C) 2007 "HTMLParserErrorCodes.h" namespace WebCore { const char* htmlParserErrorMessageTemplate(HTMLParserErrorCode errorCode) { static const char* const errors[] = { "%tag1 is not allowed inside %tag2. Moving %tag1 into the nearest enclosing <table>.", "<head> must be a child of <html>. Content ignored.", "%tag1 is not allowed inside %tag2. Moving %tag1 into the <head>.", "Extra %tag1 encountered. Migrating attributes back to the original %tag1 element and ignoring the tag.", "<area> is not allowed inside %tag1. Moving the <area> into the nearest enclosing <map>.", "%tag1 is not allowed inside %tag2. Content ignored.", "%tag1 is not allowed in a <frameset> page. Content ignored.", "%tag1 is not allowed inside %tag2. Closing %tag2 and trying the insertion again.", "%tag1 is not allowed inside <caption>. Closing the <caption> and trying the insertion again.", "<table> is not allowed inside %tag1. Closing the current <table> and inserting the new <table> as a sibling.", "%tag1 is not allowed inside %tag2. Inserting %tag1 before the <table> instead.", "%tag1 misplaced in <table>. Creating %tag2 and putting %tag1 inside it.", "</br> encountered. Converting </br> into <br>.", "XML self-closing tag syntax used on %tag1. The tag will not be closed.", "Unmatched </p> encountered. Converting </p> into <p></p>.", "Unmatched %tag1 encountered. Ignoring tag.", "%tag1 misnested or not properly closed. Cloning %tag1 in order to preserve the styles applied by it.", "<form> cannot act as a container inside %tag1 without disrupting the table. The children of the <form> will be placed inside the %tag1 instead.", "XML self-closing tag syntax used on <script>. The tag will be closed by WebKit, but not all browsers do this. Change to <script></script> instead for best cross-browser compatibility." }; if (errorCode >= MisplacedTablePartError && errorCode <= IncorrectXMLCloseScriptWarning) return errors[errorCode]; return 0; } const char* htmlParserDocumentWriteMessage() { return "[The HTML that caused this error was generated by a script.] "; } bool isWarning(HTMLParserErrorCode code) { return code >= IncorrectXMLCloseScriptWarning; } } | http://opensource.apple.com/source/WebCore/WebCore-7533.18.1/html/HTMLParserErrorCodes.cpp | CC-MAIN-2015-06 | refinedweb | 302 | 63.46 |
0
I'm trying to using Try, Except to check an input() to make sure it's not blank.
I'm using it at a different part of my program to check a float(input()) and it catches it if someone leaves it blank or enters a string, but I assume that's because it's checking the type to make sure it's a number, and a string isn't a number and leaving it blank isn't a number.
However, for just the input(), I need to check to make sure it's not a number and to check to make sure it isn't blank, but since it's just a plain-ol' input, it accepts anything thrown into it, so it doesn't raise an exception.
How can I check to make sure a string is entered?
This is my function:
def checkInput(prompt): result = None while result == None: try: result = input(prompt) return result except: print("Please insert an appropriate value!") | https://www.daniweb.com/programming/software-development/threads/381248/using-try-except-to-catch-a-blank-input | CC-MAIN-2017-17 | refinedweb | 166 | 58.15 |
ASP.NET MVC Beta has just been released and it comes with a Go-Live license that allows you to deploy ASP.NET MVC applications in production environments. Scott Guthrie and Phil Haack have put out two excellent blogs, explaining new features and improvements in the beta version.
There are not many changes between ASP.NET MVC Preview 5 and Beta. However, you will need to make a few changes to your applications after you install the Beta release. Most of these changes are apparent when you try to compile your application by using the latest binaries, so we do not list every possible change. The compiler will guide you there. The following list describes some of the changes that you must make.
· Update the references to the following assemblies to point to the new Beta versions of the assemblies:
System.Web.Abstractions.dll
System.Web.Routing.dll
System.Web.Mvc.dll
By default, these assemblies are located in the following folder:
%ProgramFiles%\Microsoft ASP.NET\ASP.NET MVC Beta
· In the Web.config namespaces section, add the following namespace entry if it is not there already:
<add namespace="System.Web.Mvc.Html"/>
· The Form HTML helper was renamed to BeginForm.
· After you have made these changes, compile your application and resolve any compilation errors. Most of the errors will be the result of one of the breaking changes listed earlier. | http://blogs.msdn.com/b/zxue/archive/2008/10/20/asp-net-mvc-beta-released.aspx?Redirected=true | CC-MAIN-2015-22 | refinedweb | 231 | 58.18 |
I want to make text strikethrough using CSS.
I use tag:
button.setStyle("-fx-strikethrough: true;");
But this code is working, please help.
You need to use a CSS stylesheet to enable strikethrough on a button. Using a CSS stylesheet is usually preferable to using an inline CSS setStyle command anyway.
/** file: strikethrough.css (place in same directory as Strikeout) */ .button .text { -fx-strikethrough: true; }
The CSS style sheet uses a CSS selector to select the text inside the button and apply a strikethrough style to it. Currently (as of Java 8), setStyle commands cannot use CSS selectors, so you must use a CSS stylesheet to achieve this functionality (or use inline lookups, which would not be advisable) - the style sheet is the best solution anyway.
See @icza's answer to understand why trying to set the
-fx-strikethrough style directly on the button does not work.
Here is a sample application:
import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.StackPane; import javafx.stage.Stage; public class Strikeout extends Application { @Override public void start(Stage stage) throws Exception { Button strikethrough = new Button("Strikethrough"); strikethrough.getStylesheets().addAll(getClass().getResource( "strikethrough.css" ).toExternalForm()); StackPane layout = new StackPane( strikethrough ); layout.setPadding(new Insets(10)); stage.setScene(new Scene(layout)); stage.show(); } public static void main(String[] args) { launch(args); } }
Button does not support the
-fx-strikethrough CSS property, so setting this has no effect.
Here is the official JavaFX 8 CSS reference: JavaFX CSS Reference Guide
The
-fx-strikethrough is defined for the
Text node.
Button only supports the following:
cancel,
default, and all inherited from
Labeled:
-fx-alignment, -fx-text-alignment, -fx-text-overrun, -fx-wrap-text, -fx-font, -fx-underline, -fx-graphic, -fx-content-display, -fx-graphic-text-gap, -fx-label-padding, -fx-text-fill, -fx-ellipsis-string
And
Labeled inherits these from
Control:
-fx-skin,
-fx-focus-traversable.
So looking at the supported properties, the following works (of course it's not strikethrough):
button.setStyle("-fx-underline: true"); | https://javafxpedia.com/en/knowledge-base/26843951/not-working-ccs-style-javafx--fx-strikethrough | CC-MAIN-2020-40 | refinedweb | 341 | 50.94 |
Name: rlT66838 Date: 08/10/99 If my first line of my javadoc comment ends in a question mark instead of a period, the next line gets included as part of the first line. Not good. Question marks are good for describing boolean attributes or methods that return a boolean value. I know that the requirement is to find a line that ends in a period and then a space, but perhaps this can be extended to include a quesion mark and a space also. -----Test Case----------------------------- public class JavadocDemo { /** First line. Second line. */ public boolean correct() { } /** First line? Second line. */ public boolean notCorrect() { } } (Review ID: 93457) ====================================================================== | https://bugs.java.com/bugdatabase/view_bug.do?bug_id=4261388 | CC-MAIN-2018-09 | refinedweb | 107 | 70.63 |
Opened 4 years ago
Last modified 4 months ago
#8763 new bug
forM_ [1..N] does not get fused (10 times slower than go function)
Description (last modified by )
Apparently idiomatic code like
forM_ [1.._N] does not get fused away.
This can give serious performance problems when unnoticed.
-- Slow: forM_ [0.._N-1] $ \i -> do ... -- Around 10 times faster: loop _N $ \i -> do ... {-# INLINE loop #-} loop :: (Monad m) => Int -> (Int -> m ()) -> m () loop bex f = go 0 where go !n | n == bex = return () | otherwise = f n >> go (n+1)
Full code example: - the relevant alternatives are commented.
Attachments (1)
Change History (33)
comment:1 Changed 4 years ago by
comment:2 Changed 4 years ago by
I believe let-floating happens due to the full-laziness transform. Do you get better performance with -fno-full-laziness ?
comment:3 Changed 4 years ago by
A comment in
SetLevels (which I just came across) in the code indicates that this problem should have been taken care of:
-- We are keen to float something to the top level, even if it does not -- escape a lambda, because then it needs no allocation. But it's controlled -- by a flag, because doing this too early loses opportunities for RULES -- which (needless to say) are important in some nofib programs -- (gcd is an example).
So either my assumption is wrong, or this does not work as desired.
comment:4 Changed 4 years ago by
It turns out that this comment is obsolete; the flag is never set. I quote from
SimplCore
-- Was: gentleFloatOutSwitches -- -- I have no idea why, but not floating constants to -- top level is very bad in some cases. -- -- Notably: p_ident in spectral/rewrite -- Changing from "gentle" to "constantsOnly" -- improved rewrite's allocation by 19%, and -- made 0.0% difference to any other nofib -- benchmark
This comment was introduced in eaeca51efc0be3ff865c4530137bfbe9f8553549 (2009) by SPJ.
Maybe rules matching should look though unfoldings more easily (at the risk of losing sharing)? There is no point in worrying about sharing
[0..N] in a rule application whose purpose is to eliminate that list.
comment:5 Changed 3 years ago by
@nomeata
Regarding your suspicion that it gets floated out as a constant, I don't see an improvement when getting the upper bound m of
[1..m] from an IO action. What do you think?
comment:6 Changed 3 years ago by
It might still get floated out of some local function. Have you tried coming up with a minimal example?
comment:7 Changed 3 years ago by
@nomeata
There is an example I made for this, mentioned in the bug description.
The performance I measure for that is:
- using
forM_with
ghc -O: 2.0 s
- using
loopwith
ghc -O: 1.6 s
- using
forM_with
ghc -O2: 0.9 s
- using
loopwith
ghc -O2: 0.3 s
- using
forM_with
ghc -O2 -fllvm: 0.75 s
- using
loopwith
ghc -O2 -fllvm: 0.15 s
I tried to make an even smaller benchmark () but the performance is identical there although the same thing changes as before.
Could you try my two benchmarks and see if you get the same behaviour?
comment:8 follow-up: 9 Changed 3 years ago by
I have updated the gist at to contain both the matmult example (where the difference between
forM_ and
loop is big) and the simple example (where no difference can be measured).
(Note that measuring the simple example with
-fllvm is pointless because it can optimize it away completely. It can't do that with the matmult though.)
comment:9 follow-up: 11 Changed 3 years ago by
I have updated the gist at to contain both the matmult example (where the difference between
forM_and
loopis big) and the simple example (where no difference can be measured).
The simple example doesn't use the same list in different places, so GHC is capable of eliminating it and giving you a loop on unboxed
Int#s, at least with
-O2. In the matmult example, you need to conceal the fact that both lists are the same from GHC to get a loop on unboxed
Int#s.
So in principle, GHC can do the desired thing, just the sharing gets in the way. Can somebody think of a situation where sharing is beneficial for
forM_ [a .. b] $ \n -> do ... code? If not, perhaps special-casing
enumFromTo arguments for
forM_ etc. is, at least for standard integer types, something to be considered.
comment:10 Changed 3 years ago by
Preventing it from sharing sounds sensible for me: If the
[a .. b] was something expensive to compute (a list of primes, say), I suspect any sane person would easily share it manually by declaring it top-level.
comment:11 Changed 3 years ago by
Replying to daniel.is.fischer:
The simple example doesn't use the same list in different places
Unfortunately, I still get no difference in performance even if I duplicate the loops to
forM_ [1.._MAX] $ \i -> do
UM.unsafeWrite v 0 i
forM_ [1.._MAX] $ \i -> do
UM.unsafeWrite v 0 i
Any idea?
comment:12 Changed 3 years ago by
comment:13 Changed 3 years ago by
I've got lost in this thread. If someone thinks there is a real bug here, in GHC 7.8, could you re-articulate what you think it is?
Simon
comment:14 Changed 3 years ago by
@simonpj: Summary:
1) I reported that my manually written loop is much faster than
forM_ [1..n] in some cases, suggesting that in some cases optimizing the list away doesn't work well.
2) nomeata said some technical things that are a bit beyond me.
3) I submit two benchmarks in the gist at, a "matmult" benchmark where there is a big difference between
forM_ and the hand-written
loop, and a "simple" benchmark where they are equally fast.
4) Daniel suspects the slow case comes from using the same syntactical list twice, and that in this case GHC floats it out to share it, which breaks eliminating it. He suggests we might special-case
enumFromTo when used with
forM_ to prevent it.
5) I give a counter example for his suspicion, by changing my "simple" benchmark, where using the same list twice gives the same good performance as using it once.
I get the same behaviour for 7.6 and 7.8.
comment:15 Changed 3 years ago by
Slight correction, @Niklas, it's not a suspicion that it's the floating out of the list to the top-level and consequently the use of the list for looping instead of unboxed
Int#s, that is direct from the core (
-ddump-simpl is your friend in all matters related to performance). The question is under which exact circumstances GHC floats the list out. To answer that, you need somebody knowing how GHC works.
comment:16 follow-up: 17 Changed 3 years ago by
I've tried with 7.8.2. I get the same performance for
matmultForM_ and
matMultLoop.
I'm not using criterion; just using
+RTS -s, with
_SIZE = 300.
So I can't reproduce the problem.
Simon
comment:17 Changed 3 years ago by
comment:18 Changed 2 years ago by
With 7.10.1, compiling with -O2, I see a factor of 2 difference in performance:
benchmarking matmultForM_ time 10.90 μs (10.89 μs .. 10.91 μs) 1.000 R² (1.000 R² .. 1.000 R²) mean 10.89 μs (10.89 μs .. 10.91 μs) std dev 32.72 ns (18.98 ns .. 65.42 ns) benchmarking matmultLoop time 5.404 μs (5.387 μs .. 5.419 μs) 1.000 R² (1.000 R² .. 1.000 R²) mean 5.409 μs (5.398 μs .. 5.420 μs) std dev 37.99 ns (33.64 ns .. 44.26 ns)
with
-fllvm it is a factor of almost 3
benchmarking matmultForM_ time 9.796 μs (9.788 μs .. 9.806 μs) 1.000 R² (1.000 R² .. 1.000 R²) mean 9.802 μs (9.795 μs .. 9.815 μs) std dev 31.64 ns (21.92 ns .. 49.61 ns) benchmarking matmultLoop time 3.499 μs (3.497 μs .. 3.502 μs) 1.000 R² (1.000 R² .. 1.000 R²) mean 3.499 μs (3.497 μs .. 3.503 μs) std dev 10.27 ns (7.068 ns .. 16.47 ns)
comment:19 Changed 2 years ago by
comment:20 Changed 2 years ago by
comment:21 Changed 2 years ago by
Milestone renamed
comment:22 Changed 19 months ago by
seeing same issue and performance on 7.10.3. This is on MacOS but I believe the problem occurs on multiple platforms,
This is with _SIZE = 10. Even if I replace
forM_ [0.._SIZE-1]
with
forM_ [0..10-1]
I see the same problem so I don't think it has to do with top level constant expressions
comment:23 Changed 19 months ago by
comment:24 Changed 11 months ago by
still seeing the same problem on 8.0.1. Any chance of this getting fixed in 8.0.2? If not 8.0.2 I hope 8.1
comment:25 Changed 11 months ago by
I'm afraid 8.0.2 is out of the question. However, 8.2.1 is a possibility. Of course, any help that you, the reader, can offer would expedite the process.
comment:26 Changed 11 months ago by
Changed 11 months ago by
Test case
comment:27 Changed 11 months ago by
Here is a test case that does not require criterion. With
ghc-8.0.1 -O2 -ddump-simpl, you can see that
foo is compiled into code that uses a top-level CAF containing
GHC.Enum.eftInt 0# 799#.
comment:28 Changed 11 months ago by
comment:29 Changed 11 months ago by
It looks like this is the same issue as described in #7206. The branch mentioned in fixes my test case.
comment:30 follow-up: 31 Changed 11 months ago by
Good to know that's it.
The program in rep.hs is rather unusual because it has a constant list, not dependent on input data. Real programs usually depend on input data. So this probem may be less of a probem in practice than in benchmarks.
It would be great if someone felt able to dig into #7206 and figure out why it's not a straight win
Simon
comment:31 Changed 11 months ago by
Real programs usually depend on input data. So this probem may be less of a probem in practice than in benchmarks.
Just wanted to chime in that I found this problem in a real-world program, where I looped over all 32-bit integers. Similarly, these known-at-compile-time iteration lists may appear in inner loops of algorithms or data structures (like B-trees with fixed B, or image convolution kernels with fixed size, e.g. 3x3 image templates).
comment:32 Changed 4 months ago by
Given that 8.2.1-rc1 is imminent, I'm bumping these off to the 8.4
People on #ghc think that it is because the
[1.._N]gets floated out as a top-level constant expression:
nomeata: nh2: I’d consider that a bug nomeata: I believe the problem is that [0..512] does not depend on any local values nomeata: so it is floated out as a top-level value nomeata: and there it is not matched by any rules thoughtpolice: let floating strikes again thoughtpolice: (well, floating-out being a non-optimization, anyway.) Fuuzetsu: does this mean that if I use [0 .. 512] twice in a program in different places, it will only be computed once? hvr: Fuuzetsu: there's a chance, yes Fuuzetsu: neat thoughtpolice: well, not so neat. in cases like this you really don't want to float out some things, because it hurts later opportunities to optimize sometimes (e.g. float out a binding that otherwise would have triggered a RULE or fusion, perhaps) thoughtpolice: unfortunately floating like this is one of the harder things to 'fight against' when you don't want it, from what i've seen. | https://ghc.haskell.org/trac/ghc/ticket/8763 | CC-MAIN-2017-34 | refinedweb | 2,027 | 75.4 |
Created on 2015-10-13 22:50 by vapier, last changed 2020-02-26 19:19 by serhiy.storchaka. This issue is now closed.
the ac_cv_have_long_long_format test has a nice compile-time fallback for gcc based compilers:
CFLAGS="$CFLAGS -Werror -Wformat"
AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
#include <stdio.h>
#include <stddef.h>
]], [[
char *buffer;
sprintf(buffer, "%lld", (long long)123);
sprintf(buffer, "%lld", (long long)-123);
sprintf(buffer, "%llu", (unsigned long long)123);
]])],
ac_cv_have_long_long_format=yes
)
unfortunately, this turns on the global -Werror flag in order to check things. that means if the code triggers unrelated warnings, the test still fails ;(. this comes up w/bionic which complains about unsafe use of the sprintf function, and can come up in general in this code because buffer is not initialized :).
the good news is that gcc-4.2 has supported a directed -Werror=format option.
so instead of using -Werror -Wformat, you could use -Werror=format. the downside is that the fallback no longer works with <=gcc-4.1, but maybe that's ok considering gcc-4.2 was released May 2007 (almost 9 years ago) ?
note: this also applies to various other tests in the configure file.
NB: landing a fix in py3.5+ (and ignoring 3.[0-4]) is fine, but please also to fix py2.7 :)
It is too later for 2.7. The long long type is required for recent Python 3 versions, so this macro is no longer used. | https://bugs.python.org/issue25397 | CC-MAIN-2021-17 | refinedweb | 239 | 68.97 |
Real Time Signal Processing in Python
Wouldn't it be nice if you could do real time audio processing in a convenient programming language? Matlab comes to mind as a convenient language for signal processing. But while Matlab is pretty fast, it is really only fast for algorithms that can be vectorized. In audio however, we have many algorithms that need knowledge about the previous sample to calculate the next one, so they can't be vectorized.
But this is not going to be about Matlab. This is going to be about Python. Combine Python with Numpy (and Scipy and Matplotlib) and you have a signal processing system very comparable to Matlab. Additionally, you can do real-time audio input/output using PyAudio. PyAudio is a wrapper around PortAudio and provides cross platform audio recording/playback in a nice, pythonic way. (Real time capabilities were added in 0.2.6 with the help of yours truly).
However, this does not solve the problem with vectorization. Just like Matlab, Python/Numpy is only fast for vectorizable algorithms. So as an example, let's define an iterative algorithm that is not vectorizable:
A Simple Limiter
A limiter is an audio effect that controls the system gain so that it does not exceed a certain threshold level. One could do this by simply cutting off any signal peaks above that level, but that sounds awful. So instead, the whole system gain is reduced smoothly if the signal gets too loud and is amplified back to its original gain again when it does not exceed the threshold any more. The important part is that the gain change is done smoothly, since otherwise it would introduce a lot of distortion.
If a signal peak is detected, the limiter will thus need a certain amount of time to reduce the gain accordingly. If you still want to prevent all peaks, the limiter will have to know of the peaks in advance, which is of course impossible in a real time system. Instead, the signal is delayed by a short time to give the limiter time to adjust the system gain before the peak is actually played. To keep this delay as short as possible, this "attack" phase where the gain is decreased should be very short, too. "Releasing" the gain back up to its original value can be done more slowly, thus introducing less distortion.
With that out of the way, let me present you a simple implementation of such a limiter. First, lets define a signal envelope \(e[n]\) that catches all the peaks and smoothly decays after them:
\[ e[n] = \max( |s[n]|, e[n-1] \cdot f_r ) \]
where \(s[n]\) is the current signal and \(0 < f_r < 1\) is a release factor.
If this is applied to a signal, it will create an envelope like this:
Based on that envelope, and assuming that the signal ranges from -1 to 1, the target gain \(g_t[n]\) can be calculated using\begin{equation} g_t[n] = \begin{cases} 1 & e[n] < t \\\\ 1 + t - e[n] & e[n] > t \end{cases} \end{equation}
Now, the output gain \(g[n]\) can smoothly move towards that target gain using
\[ g[n] = g[n-1] \cdot f_a + g_t[n] \cdot (1-f_a) \]
where \(0 < f_a \ll f_r\) is the attack factor.
Here you can see how that would look in practice:
Zooming in on one of the limited section reveals that the gain is actually moving smoothly.
This gain can now be multiplied on the delayed input signal and will safely keep that below the threshold.
In Python, this might look like this:
class Limiter: def __init__(self, attack_coeff, release_coeff, delay, dtype=float32): self.delay_index = 0 self.envelope = 0 self.gain = 1 self.delay = delay self.delay_line = zeros(delay, dtype=dtype) self.release_coeff = release_coeff self.attack_coeff = attack_coeff def limit(self, signal, threshold): for i in arange(len(signal)): self.delay_line[self.delay_index] = signal[i] self.delay_index = (self.delay_index + 1) % self.delay # calculate an envelope of the signal self.envelope *= self.release_coeff self.envelope = max(abs(signal[i]), self.envelope) # have self.gain go towards a desired limiter gain if self.envelope > threshold: target_gain = (1+threshold-self.envelope) else: target_gain = 1.0 self.gain = ( self.gain*self.attack_coeff + target_gain*(1-self.attack_coeff) ) # limit the delayed signal signal[i] = self.delay_line[self.delay_index] * self.gain
Note that this limiter does not actually clip all peaks completely, since the envelope for a single peak will have decayed a bit before the target gain will have reached it. Thus, the output gain will actually be slightly higher than what would be necessary to limit the output to the threshold. Since the attack factor is supposed to be significantly smaller than the release factor, this does not matter much though.
Also, it would probably be more useful to define the factors \(f_a\) and \(f_r\) in terms of the time they take to reach their target and the threshold \(t\) in dB FS.
Implementing audio processing in Python
A real-time audio processing framework using PyAudio would look like this:
(
callback is a function that will be defined shortly)
from pyaudio import PyAudio, paFloat32 pa = PyAudio() stream = pa.open(format = paFloat32, channels = 1, rate = 44100, output = True, frames_per_buffer = 1024, stream_callback = callback) while stream.is_active(): sleep(0.1) stream.close() pa.terminate()
This will open a
stream, which is a PyAudio construct that manages input and output to/from one sound device. In this case, it is configured to use
float values, only open one channel, play audio at a sample rate of 44100 Hz, have that one channel be output only and call the function
callback every 1024 samples.
Since the
callback will be executed on a different thread, control flow will continue immediately after
pa.open(). In order to analyze the resulting signal, the
while stream.is_active() loop waits until the signal has been processed completely.
Every time the
callback is called, it will have to return 1024 samples of audio data. Using the class
Limiter above, a sample counter
counter and an audio signal
signal, this can be implemented like this:
limiter = Limiter(attack_coeff, release_coeff, delay, dtype) def callback(in_data, frame_count, time_info, flag): if flag: print("Playback Error: %i" % flag) played_frames = counter counter += frame_count limiter.limit(signal[played_frames:counter], threshold) return signal[played_frames:counter], paContinue
The
paContinue at the end is a flag signifying that the audio processing is not done yet and the
callback wants to be called again. Returning
paComplete or an insufficient number of samples instead would stop audio processing after the current block and thus invalidate
stream.is_active() and resume control flow in the snippet above.
Now this will run the limiter and play back the result. Sadly however, Python is just a bit too slow to make this work reliably. Even with a long block size of 1024 samples, this will result in occasional hickups and discontinuities. (Which the
callback will display in the
print(...) statement).
Speeding up execution using Cython
The limiter defined above could be rewritten in C like this:
// this corresponds to the Python Limiter class. typedef struct limiter_state_t { int delay_index; int delay_length; float envelope; float current_gain; float attack_coeff; float release_coeff; } limiter_state; #define MAX(x,y) ((x)>(y)?(x):(y)) // this corresponds to the Python __init__ function. limiter_state init_limiter(float attack_coeff, float release_coeff, int delay_len) { limiter_state state; state.attack_coeff = attack_coeff; state.release_coeff = release_coeff; state.delay_index = 0; state.envelope = 0; state.current_gain = 1; state.delay_length = delay_len; return state; } void limit(float *signal, int block_length, float threshold, float *delay_line, limiter_state *state) { for(int i=0; i<block_length; i++) { delay_line[state->delay_index] = signal[i]; state->delay_index = (state->delay_index + 1) % state->delay_length; // calculate an envelope of the signal state->envelope *= state->release_coeff; state->envelope = MAX(fabs(signal[i]), state->envelope); // have current_gain go towards a desired limiter target_gain float target_gain; if (state->envelope > threshold) target_gain = (1+threshold-state->envelope); else target_gain = 1.0; state->current_gain = state->current_gain*state->attack_coeff + target_gain*(1-state->attack_coeff); // limit the delayed signal signal[i] = delay_line[state->delay_index] * state->current_gain; } }
In contrast to the Python version, the delay line will be passed to the
limit function. This is advantageous because now all audio buffers can be managed by Python instead of manually allocating and deallocating them in C.
Now in order to plug this code into Python I will use Cython. First of all, a "Cython header" file has to be created that declares all exported types and functions to Cython:
cdef extern from "limiter.h": ctypedef struct limiter_state: int delay_index int delay_length float envelope float current_gain float attack_coeff float release_coeff limiter_state init_limiter(float attack_factor, float release_factor, int delay_len) void limit(float *signal, int block_length, float threshold, float *delay_line, limiter_state *state)
This is very similar to the C header file of the limiter:
typedef struct limiter_state_t { int delay_index; int delay_length; float envelope; float current_gain; float attack_coeff; float release_coeff; } limiter_state; limiter_state init_limiter(float attack_factor, float release_factor, int delay_len); void limit(float *signal, int block_length, float threshold, float *delay_line, limiter_state *state);
With that squared away, the C functions are accessible for Cython. Now, we only need a small Python wrapper around this code so it becomes usable from Python:
import numpy as np cimport numpy as np cimport limiter DTYPE = np.float32 ctypedef np.float32_t DTYPE_t cdef class Limiter: cdef limiter.limiter_state state cdef np.ndarray delay_line def __init__(self, float attack_coeff, float release_coeff, int delay_length): self.state = limiter.init_limiter(attack_coeff, release_coeff, delay_length) self.delay_line = np.zeros(delay_length, dtype=DTYPE) def limit(self, np.ndarray[DTYPE_t,ndim=1] signal, float threshold): limiter.limit(<float*>np.PyArray_DATA(signal), <int>len(signal), threshold, <float*>np.PyArray_DATA(self.delay_line), <limiter.limiter_state*>&self.state)
The first two lines set this file up to access Numpy arrays both from the Python domain and the C domain, thus bridging the gap. The
cimport limiter imports the C functions and types from above. The
DTYPE stuff is advertising the Numpy
float32 type to C.
The class is defined using
cdef as a C data structure for speed. Also, Cython would naturally translate every C struct into a Python dict and vice versa, but we need to pass the struct to
limit and have
limit modify it. Thus,
cdef limiter.limiter_state state makes Cython treat it as a C struct only. Finally, the
np.PyArray_DATA() expressions expose the C arrays underlying the Numpy vectors. This is really handy since we don't have to copy any data around in order to modify the vectors from C.
As can be seen, the Cython implementation behaves nearly identically to the initial Python implementation (except for passing the
dtype to the constructor) and can be used as a plug-in replacement (with the aforementioned caveat).
Finally, we need to build the whole contraption. The easiest way to do this is to use a setup file like this:
from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext from numpy import get_include ext_modules = [Extension("cython_limiter", sources=["cython_limiter.pyx", "limiter.c"], include_dirs=['.', get_include()])] setup( name = "cython_limiter", cmdclass = {'build_ext': build_ext}, ext_modules = ext_modules )
With that saved as setup.py,
python setup.py build_ext --inplace will convert the Cython code to C, and then compile both the converted Cython code and C code into a binary Python module.
Conclusion
In this article, I developed a simple limiter and how to implement it in both C and Python. Then, I showed how to use the C implementation from Python. Where the Python implementation is struggling to keep a steady frame rate going even at large block sizes, the Cython version runs smoothly down to 2-4 samples per block on a 2 Ghz Core i7. Thus, real-time audio processing is clearly feasable using Python, Cython, Numpy and PyAudio.
You can find all the source code in this article at
Disclaimer
- I invented this limiter myself. I could invent a better sounding limiter, but this article is more about how to combine Python, Numpy, PyAudio and Cython for real-time signal processing than about limiter design.
- I recently worked on something similar at my day job. They agreed that I could write about it so long as I don't divulge any company secrets. This limiter is not a descendant of any code I worked on.
- Whoever wants to use any piece of code here, feel free to do so. I am hereby placing it in the public domain. Feel free to contact me if you have questions. | http://bastibe.de/2012-11-02-real-time-signal-processing-in-python.html | CC-MAIN-2017-17 | refinedweb | 2,069 | 55.54 |
Network Storage Protocols Discussions
I get that there is a global namespace for NFS and for CIFS and that all the systems are sharing a global IP across all the systems.
In the "Data ONTAP 8.0 Cluster-Mode" white paper there is a statement that says the following:
"By offering a single system image across multiple storage nodes, the global namespace eliminates the need for complex automounter maps and symbolic link scripts."
Are they saying that all controllers in the cluster have access to all the disks? If so, are we now creating a SAN between all the controllers and storage shelves in the cluster?
My assumptions are that each storage system has access to it's disks and the "Cluster-Mode" is only a statement in regards to the front end (I.e. NFS / CIFS Global Namespace.)
Does this sound correct?
First off, if you really want a deep dive on cluster mode, I strongly suggest you have you local team come in and give you one. They should be able to give far more detail than is feasible here.
That being said, each controller in the cluster has access to data on all of the other controllers through a back-end interconnected network. So if you have 8 controllers in your cluster, you can access data from all 8 from any one node in the cluster, thus giving you front-end scalability. This is particularly important when you consider high-performance aggregates (i.e. aggregates which are striped across multiple cluster controllers).
Like I said, there's plenty of deep dive info available on this, but I wanted to give you a quick, high-level answer.
Hope this helps.
Will do.. I'll see if I can get into a deep dive up here. I need it I guess.
My assumptions are that you'd have to have a connection from every controller to every shelf in the cluster. In this case you'd need a fiber channel switch zoned for connectivity on the back end of some sort to allow ownership across all the controllers to all the disks.
I guess the real question is this: In a 7.x world, every disk has a primary and a secondary owner.
In the 8.x world, are there primary, secondary.. and tertiary etc.. owners on 1 disk? This to me would make it Single System Image.
What happens if you lose both controllers in 1 node of the cluster. Does node 2 have the ability to take control of those disks that were assigned to the first node?
I'm sure I'm botching this all up and will reach out to our guys up here to get some further wisdom in regards to 8.0 Cluster-Mode.
Thanks! | https://community.netapp.com/t5/Network-Storage-Protocols-Discussions/Does-anyone-know-how-8-0cm-is-going-to-achieve-SSI/td-p/43299 | CC-MAIN-2021-04 | refinedweb | 462 | 73.47 |
/dev.
NOTE that devfs is entirely optional. If you prefer the old disc-based device nodes, then simply leave CONFIG_DEVFS_FS=n (the default). In this case, nothing will change. ALSO NOTE that if you do enable devfs, the defaults are such that full compatibility is maintained with the old devices names.
There are two aspects to devfs: one is the underlying device namespace, which is a namespace just like any mounted filesystem. The other aspect is the filesystem code which provides a view of the device namespace. The reason I.
The cost of devfs is a small increase in kernel code size and memory usage. About 7 pages of code (some of that in __init sections) and 72 bytes for each entry in the namespace. A modest system has only a couple of hundred device entries, so this costs a few more pages. Compare this with the suggestion to put /dev on a ramdisc.
On a typical machine, the cost is under 0.2 percent. On a modest system with 64 MBytes of RAM, the cost is under 0.1 percent. The accusations of "bloatware" levelled at devfs are not justified. | http://www.makelinux.net/books/Linux-Filesystem-Hierarchy/dev | crawl-003 | refinedweb | 191 | 74.79 |
On Thu, Jun 27, 2019 at 09:55:53AM -0400, David Mertz
Rewrite it in what way? What problem are you trying to solve?
If you just want to "flush" the local variables at the end of each loop and ensure that they have been deleted, you can explicitly delete them:
del f, g, datum
If you are talking about the kind of refactoring Chris was talking about, I don't see any reason, or opportunity, to do that. If anything, you could reverse the refactoring:
def frobnicate(data): stuff = [] for datum in data: stuff.append(munge_result(process_the(datum))) return stuff
which leads to the obvious comprehension:
return [munge_result(process_the(datum)) for datum in data]
which allows us to eliminate the variable re-use:
return list(map(lambda x: munge_result(process_the(x)), data))
[...]
Without
looking at the source code in
process_the() we have no way of knowing
whether
f is being bound to a new object each time or some completely
different arbitrary action.
That's exactly the situation right now. Functions can perform arbitrary actions and return the same object each time.
def process_the(arg): print("do something arbitrary") return None
-- Steven | https://mail.python.org/archives/list/python-ideas@python.org/message/OCJYGIXC3MBQGMJ532GEHWUXII5AAFWX/ | CC-MAIN-2020-40 | refinedweb | 193 | 60.24 |
Google Code Jam 2014 Solution - Magic Trick
This is the first in a series of posts where I'm going to go in depth on how to solve the Google Code Jam questions. In most cases I'll use the raw code I submitted but I may make some editorial edits if I feel the code is particularly hacky (CodeJam favours speed mostly over beauty).
Problem
The first question revolved around a magician with a particularly easy magic trick. He arranged 16 cards in a 4 by 4 square and asked a chosen audience member to pick one card and say the row it was in. He then re-arranged the cards and asked the audience member to pick the row it was in again and revealed what the card was.
The secret was simple, the magician just put all four cards from the selected row into different rows for the second go and found the card that appeared in both. Solving the problem just meant we needed to find the intersection of the two chosen rows (the card that appears in both).
Representation
First thing that came into my head was how to represent the data in the program. The most obvious would be a 4x4 array of numbers for each time the magician shuffled. The corresponding selected rows would be held as numbers so they could be queried by accessing the array at
grid1[row-1].
Using this model makes our solution easier as well as we can leverage C#'s excellent Linq libraries on our arrays and use
grid1[row1-1].intersect(grid2[row2-1]) to cleanly return the intersection. If the amount of items returned is 0 then the audience member has cheated. If its 1 then the magician has guessed correctly. If its more than this then the magician has made a mistake re-arranging his cards (0 could also mean this but the specification of the problem prioritised 0 as audience cheating).
Solution
Just a quick few notes. I figured casting to numeric types wasn't needed as the comparison did not involve any sort of operators apart from equals so saved a few lines of code. The
ReadLn() and
ReadArray() functions you will also see alot more of in the next few solutions.
using System.IO; using System.Linq; namespace SDX.GCJ.MagicTrick { class Program { private static StreamReader input; private static StreamWriter output; static int ReadLn() { return int.Parse(input.ReadLine()); } static string[] ReadArray() { return input.ReadLine().Split(' '); } static void Main(string[] args) { input = new StreamReader("in.txt"); output = new StreamWriter("out.txt", false); var cases = ReadLn(); for (int i = 1; i <= cases; i++) { var row1 = ReadLn(); var grid1 = new string[4][]; var grid2 = new string[4][]; grid1[0] = ReadArray(); grid1[1] = ReadArray(); grid1[2] = ReadArray(); grid1[3] = ReadArray(); var line1 = grid1[row1-1]; var row2 = ReadLn(); grid2[0] = ReadArray(); grid2[1] = ReadArray(); grid2[2] = ReadArray(); grid2[3] = ReadArray(); var line2 = grid2[row2-1]; var intersect = line1.Intersect(line2).ToArray(); string outputstr = "Case #" + i + ": "; if (intersect.Length == 1) { output.WriteLine(outputstr + intersect[0]); } else if (intersect.Length > 1) { output.WriteLine(outputstr + "Bad magician!"); } else { output.WriteLine(outputstr + "Volunteer cheated!"); } } output.Close(); } } } | https://blog.snapdragonit.com/google-code-jam-2014-solution-magician/ | CC-MAIN-2017-39 | refinedweb | 528 | 64.41 |
Newland scanners library
Project description
trimarlib-newland
Python library for interfacing Newland scanners. depends on
pyserial package as well - it is used as a transport layer with the devices.
This dependecy is defined in
setup.py and is satisfied automatically at installation time.
newlandlib/tests directory, they are named after the device and
functionality being tested. Testing is based on
unittest Python built-in package.
The
Makefile defines three test targets:
unit-tests,
integration-tests and
tests (invokes both
unit and integration tests).
Unit tests
unit-tests are fairly fast and do not require any device to be attached to the machine, they test
utility methods. They may be invoked manually one-by-one (e.g.
python -m newlandlib.tests.test_fm100_utils)
or by the
Makefile (i.e.
make unit-tests).
Integration tests
integration-tests are very slow due to number of tests involved (full testing of FM100 device
takes ca. 3 hours) and they require the device to be attached to the machine running the code. They may be
invoked one-by-one (similarly to unit tests, e.g.
python -m newlandlib.tests.test_fm100_commands) or
in batch by the
Makefile (i.e.
make integration-tests).
Deployment
The library is not intended to be used in a standalone configuration - the primary purpose is to be used
by higher-level applications, which should define it as a dependency. However it is perfectly correct
to install it manually using
pip.
Versioning
The project is versioned using a simple pattern based on repository tagging feature. See Makefile for implementation details, for versions available see tags on this repository.
Usage
See docstrings for API documentation.
Example of device initialization using auto-discovery feature:
from newlandlib import FM100 ports = FM100.discover() dev = FM100(ports[0]) dev.configure() def callback(sender, *, data, codeid=None, aimid=None): print('sender={}, data={}, codeid={}, aimid={}'.format(sender, data, codeid, aimid)) dev.callback = callback dev.start()
The
callback method will be invoked with each scanned barcode.
License
This software is licensed under the MIT License - see LICENSE.
Related documents
This software is based upon the following documents from Newland:
- FM100 Integration Guide (v1.2.1, 22/02/2017)
- FM420 Integration Guide (v1.1.4, 07/08/2014)
- FM430 User Guide (v1.2.1, 19/07/2018)
- Programming Guide Based on Newland Unified Commands Set (v1.0.0, 12/02/2018)
- Serial Programming Command Manual (v1.3.0, 15/11/2016)
Project details
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/trimarlib-newland/ | CC-MAIN-2019-47 | refinedweb | 425 | 52.36 |
I was kindly requested recently to do a brief – and it was stressed several times that it really had to be brief, not something I am particularly well-known for – presentation on any topic that I considered interesting, relevant and stimulating for our Knowledge Center on Web and Java. My talk was to be the first of many, where all 20 odd members of this Knowlegede Center will do such Ten Minute Talks over the coming months’ meetings. The real challenge for me, apart from that absurd 10 minute limit of course, was not to find a subject – I had dozens. I toyed for example with topics such as: Byte Code generation/manipulation, Oracle Rules, JavaScript and DHTML, ADF Faces/ Java Server Faces, Hibernate, AspectJ and Aspect Oriented Programming, JFreeChart, “XUL, HTC, Flash, XForms and other Client Side technology”, Google Maps, J2EE Design Patterns. I found it very hard to pick just one, primarily because selecting one means de-selecting many others. In the end I decided to demonstrate and discuss the concept of AJAX (Asynchronous JavaScript and XML). Or rather, I discussed a slightly broader definition:
Any method for partially updating the web page displayed in the Browser based on server-interaction without the browser losing focus
I was more concerned with the concepts and potential functionality than the specific technology used. Within this self-defined scope, I discussed three approaches:
- Frame refresh – Based on multiple frames where one frame is reloaded (and potentially updates the other frames using JavaScript and Client Side DOM Manipulation
- Oracle UIX – Partial Page Rendering – Based on (hidden) IFRAME and DOM Manipulation (this discusses the built-in features of Oracle UIX and presumably ADF Faces)
- “regular AJAX”- Based on (hidden) XmlHttpRequestObject and DOM Manipulation
Sort of AJAX, based on frame-refreshing
As an example of the first, rather old-fashioned way of doing AJAX (or at least something which falls under my definition of AJAX), I demonstrated the Repository Object Browser, a tool I developed in the late 1990s using Oracle’s Web PL/SQL Toolkit, largely in PL/SQL using large quantities of JavaScript (no DHTML back then, no DOM manipulation or innerHTML etc.). The ROB (or Oracle Designer Web Assistant as it was called before it was included in the Oracle Designer product in 2003) contains a number of Trees or Navigators. These are all created on the Client, using document.write() statements. Initially, only the top-level nodes for the three are downloaded to the client. Whenever the user expands a tree-node, a (hidden) frame is submitted with a request for the child-nodes of this particular tree-node. When this frame has received the response (onLoad event in the hidden frame), it starts copying the node data to a node-array held in the “top” window and subsequently the tree is completely redrawn – again using document.write. As it turns out, this makes for quite a nice, responsive tree. Compared to the XmlHttpRequest object it feels somewhat clumsy, but it certainly does the job. And since it is the hidden frame that sends the request and gets refreshed, the frame(s) visible and accesible to the user are still available – no loss of focus there.
AJAX in UIX
As discussed in an earlier post – AJAX with UIX – PrimaryClientAction for instantaneous server-based client refresh – Oracle’s UIX has its own AJAX implementation. It uses an IFRAME that is submitted, refreshed and read from – instead of the XMLHttpRequest() object or the ActiveXObject(“Microsoft.XMLHTTPâ€?). This implementation is easy to use, pretty robust – even on somewhat older browsers and quite effective. UIX has the notion of Partial Page Refresh – where only specific components in a page are refreshed through the IFRAME based on the server response to the IFRAME-submit. This submit is triggered by a so-called primaryClientAction. This is a property defined in the UIX page on interactive items such as button and text-inputs. You can link targets – refreshable UIX elements in the UIX page – to a primaryClientAction. Whenever the action occurs, the form with the updated data is sumitted and the target element gets refreshed.
Conceptually, there is very little difference between submitting a request from an IFRAME and creating a request object programmtically and submitting that. The main difference between do it yourself AJAX and UIX is the server side handling of the request: UIX has built in functionality for rendering an appropriate (partial) response – using the same page definitions that also render the main, fullblown pages; when used for a partial render action, the same UIX page suddenly renders just a subset of the nodes, only the ones required for refreshing certain elements. The second big difference lies in the client side handling of the partial response: UIX has JavaScript libraries that know how to refresh the targets of a primaryClientAction from the response received in the IFRAME. Based on element IDs, values are copied from the IFRAME to the main page. This requires no page specific programming whatsoever.
UIX uses this AJAX-like technology (primaryClientActions and associated targets) for these operations:
- expand tree nodes
- sort data in a table (multi-record layout)
- navigate to next or previous data set (in table or multi-record layout)
- perform server-side validation and/or derivation
- select from List of Values
- find value from List of Values based on partial input; this means that for example when the user types in the first one or two letters of the name of a candidate manager, through partial page refresh the application will attempt to complete the name.
- detail disclosure; this is represented through the Hide/Show links: any record in the multi-record layout can be ‘disclosed’. When that happens, through Partial Page Refresh additional fields for this record are retrieved from the server and displayed, just like is done for Employee CLARK and Department ACCOUNTING in the picture below
These UIX specific operations are illustrated in the next picture:
Download
Download the examples of AJAX in UIX: AjaxUixAdfSample.zip Note: this application was generated using JHeadstart; it requires the JHeadstart runtime library (that is included in the zip file). The zip-file furthermore contains a JDeveloper 10.1.2 Application Workspace.
AJAX based on XmlHttpRequest – based on text and/or xml
I have looked at several aspects of using XmlHttpRequest: using static – files – or dynamic – jsp or servlet – resources to send the Request to, interpreting the Response as plain text or as XML and working in synchronous (wait for response, freeze browser while waiting) or asynchronous (continue working in the browser while the request is processed on the server) mode.
Drawing heavily from the examples I found on the internet, especially those by Tug Grall – Tug Gralls Weblog on AJAX, for example some AJAX examples -, I worked out some examples. You can download all of them below.
The core of each example is a bit of JavaScript that sets up an XmlHttpRequest Object and processes the Response. In each example, the request is slightly different, as is the response and the way the response is to be processed into the webpage. Note that each example starts from a static HTML file.
// this script is based on code taken from var xmlHttpRequest; // global variable, the xmlHttpRequest object that used for AJAX /** * Create and load the data using the XMLHttpRequest */ function doAjaxRequest(url, object) // url is the target to send the request to, // object is an input parameter to the JavaScript function that will process any state change in the request { //); // true indicates ASYNCHRONOUS processing; false would mean SYNCHRONOUS xmlHttpRequest.onreadystatechange = function () {processRequestChange(object)}; xmlHttpRequest.send(null); }// doAjaxRequest /** * Handle the events of the XMLHttpRequest Object */ function processRequestChange(object) { if (xmlHttpRequest.readyState == 4) { if(xmlHttpRequest.status == 200) { processResponse(xmlHttpRequest.responseXML); // process the response as XML document; // alternatively, process xmlHttpRequest.responseText, interpreting the response as plain text or HTML }>" } }//processRequestChange
This code assumes that the document contains an element with id statusZone, probably a DIV element, that is used to display messages; for example:
<div id="statusZone" style="position: absolute; top: 0px; top: 0px; left: 0px; right: 0px; z-index:1;" />
. If that element does not exist, you can simply remove the lines starting with
document.getElementById("statusZone").
A typical initiation of an AJAX request would be a call like:
doAjaxRequest("", document.getElementById("ajaxTargetObject").
AJAX – retrieving XML documents, used to populate Select Lists
A typical example of using AJAX is the following: a user can select a value from a Select List, for example Country, Car Make, Department. When he has done so, he can select a value from a second, associated Select List, for example City, Car Type or Employee. Ideally, the values in the second list is restricted based on the selection made in the first list; after having chosen United Kingdom as Country, you would not want to find Cities like Amsterdam, Berlin, New York and Nairobi in the Cities List. Besided, if all possible City, Car Type or Employee values for the second list are loaded along with the page, it takes much longer to load the page and make it available to the user. If the values for the secondary list are only populated when the selection is made in the first list, the initial page load is much faster. The refresh of the second list can be done by a full page refresh, but it would be so much nicer if it happens ‘on the fly’ – asynchronous and instantaneously. Enter AJAX.
In our example, we have a SELECT with a list of Departments. These departments are loaded using AJAX when the HTML document is loaded in the browser. The relevant HTML:
<body onLoad="loadDepartmentData();" class="content" style="text-align:left;margin: 20px 20px 20px 20px;"> <h1>AJAX with XMLHttpRequest Demonstration - Dependent Lists</h1> <p> This demonstration shows how ... <form method="post" action="#" name="demo"> <table> <tr> <td> <p>Department:</p> </td> <td> <select name="dept" id="dept" onChange="loadEmployee();" class="selectText"> </select> </td> </tr> <tr> <td> <p>Employee:</p> </td><td> <select name="emp" id="emp" class="selectText" > </select> </td> </tr> </table> ...
The JavaScript functions used for populating the Department list:
/** * Load the department data in the select object * (Could be done in a generic manner depending of the XML...) */ function loadDepartmentData() { var target = document.getElementById("dept"); loadXmlData("dept.xml",target); } <script> // this page is taken from var xmlHttpRequest; /** * Create and load the data using the XMLHttpRequest */ function loadXmlData(url, object) { //); xmlHttpRequest.onreadystatechange = function () {processRequestChange(object)}; xmlHttpRequest.send(null); } /** * Handle the events of the XMLHttpRequest Object */ function processRequestChange(object) { if (xmlHttpRequest.readyState == 4) { if(xmlHttpRequest.status == 200) { if (object.id == "emp" ) { copyEmployeeData(); } else if (object.id == "dept" ) { copyDepartmentData(); } }>" } } /** * Populate the list with the data from the request * (Could be done in a generic manner depending of the XML...) */ function copyDepartmentData() { var list = document.getElementById("dept"); clearList(list); addElementToList(list, "--", "Choose a Department" ); var items = xmlHttpRequest); } < object * (Could be done in a generic manner depending of the XML...) */ function loadEmployee() { var target = document.getElementById("emp"); var deptList = document.getElementById("dept"); clearList(target); if (deptList.value==50) { loadXmlData('ajaxgetemployees?dept=50',target ); // ajaxgetemployees is a Servlet that returns an XML Document } else if (deptList.value==20) { // invoke a JSP that uses JSTL (SQL and XML) to retrieve Employee details from the database and return an XML document loadXmlData('DeptStaffXML.jsp?deptno=20',target ); } else { // retrieve employees from a static XML file on the web server (emp_10.xml, emp_30.xml) var file = "emp_"+ deptList .value +".xml" loadXmlData(file,target ); } } /** * Populate the list with the data from the request * (Could be done in a generic manner depending of the XML...) */ function copyEmployeeData() { var list = document.getElementById("emp"); var items = xmlHttpRequest ); } } else { alert("No Employee for this department"); } }
Three different methods are used here to produce the XML Document with Employee details: a static XML file on the web server, a Servlet that returns an XML Document and a JSP that accesses the database using JSTL SQL and also returns an XML Document. The Servlet is coded as follows:
package nl.amis.ajax.view; import javax.servlet.*; import javax.servlet.http.*; import java.io.PrintWriter; import java.io.IOException; public class AjaxGetEmployees extends HttpServlet { private static final String CONTENT_TYPE = "text/xml; charset=windows-1252"; private static final String DOC_TYPE; public void init(ServletConfig config) throws ServletException { super.init(config); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Thread.currentThread().sleep(3000); // pause this servlet's (thread) execution for 3 seconds } catch (InterruptedException e) { } String deptno = ""; try { deptno = request.getParameter("dept"); } catch(Exception e) { e.printStackTrace(); } response.setContentType(CONTENT_TYPE); PrintWriter out = response.getWriter(); if (DOC_TYPE != null) { out.println(DOC_TYPE); } out.println("<EMP><ROW><EMPNO>100</EMPNO><ENAME>JELLEMA</ENAME></ROW><ROW><EMPNO>200</EMPNO><ENAME>TOBIAS</ENAME></ROW></EMP>"); out.close(); } }
The JSP that used to return Employees from the database makes use of JSTL, specially the SQL library next to the Core library. The DataSource is defined directly in the JSP – better would be to set it up in the Application Server. Note that in order to use the JSTL libraries (in application servers before J2EE 1.4) you need to specify the Tag Libraries in the web.xml file of the application server (see the download file for all code and configuration files). The JSP is coded like this:
<%@> <EMP> <c:forEach <ROW><EMPNO><c:out</EMPNO><ENAME><c:out</ENAME></ROW> </c:forEach> </EMP>
AJAX – retrieving entire HTML Fragments into a web-page
There are many ways in which to make use of AJAX and a background, asynchronous server request and response. One of the things we can do is have the server send an HTML fragment, for example from a static file, a JSP or Servlet, and paste it somewhere in the requesting page. We can easily include some sort of container object – typically a DIV element – in our webpage and have it absorb and display the server response.
In the next picture we see an example. The page contains three buttons. Each one is linked to a Department. The yellow rectangle is a DIV whose background-color is set to yellow. This is the container element in which the HTML fragment resulting from an AJAX call is published.
When the first button is pressed, the following AJAX call is made:
httpRequest.open("GET", "AjaxDivContents.jsp?deptno="+deptno, true); where deptno is a parameter passed in to the JavaScript function. The JSP AjaxDivContents.jsp uses JSTL SQL to retrieve the Employees from the Database and writes an HTML table from those Employee records. This HTML is returned and pasted into the DIV, using the innerHTML property:
var contentViewer = document.getElementById("contentViewer"); contentViewer.innerHTML = httpRequest.responseText;
The result looks like this:
Of course when buttons are pressed for other departments, the process is repeated with a different deptno value. Note that the HTML page is loaded once, with the buttons, the JavaScript and the DIV contentViewer element. When a button is pressed, the server is asked – asynchronously – to return a bit of HTML. That HTML is put inside the DIV – while the rest of page is not changed! Only the DIV contents is refreshed.The entire process is illustrated in the next picture:
Initially I had some qualms about using the innerHTML property. I had the impression that FireFox would not support it – but it does. And I had the idea I had to make use of W3C DOM methods, since it would be ‘better’ in some way. However, using cloneNode() or importNode() on the XmlHttpRequest.responseXML() did not give me true HTML elements for some reason – the text was displayed (node values), but not their HTML characteristics.
tableNode = httpRequest.responseXML.getElementsByTagName('table')[0]; // find the first table element in the XML response contentViewer.appendChild(tableNode.cloneNode(true)); // apparently only FireFox
Interestingly enough, this post on a forum demonstrates how using innerHTML to set a piece of fragment, also adds real elements (nodes) into the Document tree. That is, after using innerHTML, you cannot discern between nodes in the Document tree added by createNode() and by innerHTML(). I did not know about performance etc. Then I came across this article: Benchmark – W3C DOM vs. innerHTML. It clearly indicates that using innerHTML is usually much faster than achieving the same effect using W3C DOM methods.
This put together really converted me: innerHTML is fine! Actually, it is pretty cool.
The JSP that returns the HTML fragment looks like this. Note that it does not include HTML and BODY tags, it is just a fragment:
<%@ page</h3> <table id="tbl"><tr><th>Empno</th><th>Name</th></tr><c:forEach <tr><td><c:out</td><td><c:out</td></tr> </c:forEach> </table>
Needless to say that the DataSource really should be defined at Servlet Container level and not hardcoded in this JSP.
Download
Download the examples of regular AJAX – using static XML, JSP/JSTL and Servlet on the Server Side: AjaxExample.zip. Again, this a JDeveloper 10.1.2 Application Workspace. However, the HTML, JSP/JSTL and Servlet Code is not tied to JDeveloper in any way and all code can be run with any Servlet Container or Java IDE.
Resources
Googling on AJAX results in a wealth of hits. There are a few that I found very helpful, so these I will mention:
AJAX in WikiPedia
Apache Direct Web Remoting (DWR), an introduction
Fifty Four Eleven – a huge collection of references to AJAX examples and articles – a very good demo of some straightforward AJAX applications
AJAX with BabySteps – a very useful tutorial
JSON – JavaScript Object Notation – a library for data interchange: exchanging Java Objects through JavaScript for example
Very Dynamic Web Interfaces by Drew McLellan February 09, 2005 (article on O’Reilly XML.com)
Tug Gralls Weblog on AJAX – which provided some very good demos
This article is really useful, thank you very much
this is very good. can u give me the code for validation of state and city using drop down box. means when user select a state from a drop down box it’s correspending city should populate in another drop down box.and again user select a city in this drop down box it’s corresponding locality populate in another drop down box in AJAZ and jsp or servlet.
Good article by Chris Schalke: Anatomy of an AJAX Transaction
Very very good.
The artice could be very useful for me, but some of your scripts are badly corrupted (f.e. copyDepartmentData() function). | https://technology.amis.nl/2005/08/24/enhancing-web-applications-with-ajax-xmlhttprequest-uix-report-from-an-amis-ten-minute-techtalk/ | CC-MAIN-2015-48 | refinedweb | 3,077 | 50.97 |
#include <avr/sleep.h>byte mode = 1;volatile boolean switchPress = false;volatile boolean lastSwitchPress = false;unsigned long modePress;void setup(){ //Serial.begin(115200); pinMode(6, OUTPUT); pinMode(9, OUTPUT); digitalWrite(2, HIGH); //enable pull up attachInterrupt (0, buttonPress, LOW); sleepCPU();}//function to put everything to sleepvoid sleepCPU(){ // disable ADC ADCSRA = 0; set_sleep_mode (SLEEP_MODE_PWR_DOWN); sleep_enable(); // will be called when pin D2 goes low attachInterrupt (0, buttonPress, LOW); // turn off brown-out enable in software MCUCR = _BV (BODS) | _BV (BODSE); MCUCR = _BV (BODS); sleep_cpu ();}void loop(){}
You could quickly find out by using a razor knife.Cut a power trace, insert the ammeter across the cut, then solder the trace.
I can't believe the converter or charger are sucking up 4.4mA. This is kind of disappointing to say the least. The whole thought process was that with everything asleep, the battery drain would be negligible.
According to the datasheet for the converter, the quiescent current is less than 50uA and for the charger it should be less than 5uA. What could I be missing here?
Please enter a valid email to subscribe
We need to confirm your email address.
To complete the subscription, please click the link in the
Thank you for subscribing!
Arduino
via Egeo 16
Torino, 10131
Italy | http://forum.arduino.cc/index.php?topic=148110.msg1113001 | CC-MAIN-2015-14 | refinedweb | 210 | 53.71 |
Hi,
I’m a newbie and it was my first experiences with stepper. I’m also french (nobody is perfect) and my english is poor.
I have to drive a stepper with high torque to made 2 rounds when a button is pressed…
Configuration :
- Arduino Uno R3
- MotorShield Rev3 (2A/circuit) with Stepper Library
- Stepper 57SH76-M (torque 1,8 Nm, 2.8 A, 4 wires)
I just add a simple button and a LED to show when it’s running.
I’ve read the documentation i can found at Arduino reference, tutorial and many blogs but i’m a bit confused with what happened.
I’ve understand that it was better to power the Motorshield with an external power directly (and cut the Vin track below), but i don’t want to cut the track now, just made some quick experiment before doing a irreversible action
I just connect the stepper and only the USB power to Arduino.
The motor works at low speed, below 35 rpm it’s OK (low torque of course).
Then a add an external power (AC-DC wall adapter) to the Arduino (doc said i can) : i could achieve 50-60 rpm, but when the stepper stop it has a sort of very little shake (it make noise like an old power and you can feel small shake if you put you finger on it)…
Note : the L298 became hot, even if i do not make the stepper turn.
If a remove the USB power (there is only the external wall adapter 6V), the Arduino seems to hang, the button do nothing and the LED (but also the small LED on motorshield for each line) blink at
First,
I do not understand. What happened ?
Perhaps the steppers has a too big torque and requirements for the Motor Shield or do i miss something (i’m new in electronics).
Do i have to cut now the Vin tracks and plug an external power of 12V ?
I think i need real instruction about power usage
Second,
The MotorShield Rev3 also lack of documentation ()
I do not found anywhere an explanation i could understand of usage for the pins (4 pins for each phase), brake is not explain, PWM neither…
The sample code only call the constructor with direction pins and set PMW and brake as output… but i don’t know why.
I’m really confused.
Thanks.
Below the code i used (adapted from standard sample) :
#include <Stepper.h>
// constants won’t change. They’re used here to
// set pin numbers:
const int buttonPin = 2; // pushbutton pin
const int ledPin = 4; // LED pin
const int pwmA = 3; // PWM Channel A
const int pwmB = 11; // PWM Channel B
const int brakeA = 9; // Brake Channel A
const int brakeB = 8; // Brake Channel B
const int dirA = 12; // Direction Channel A
const int dirB = 13; // Direction Channel B
const int STEPS = 200;
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
int rpm=30; // stepper speed (round per minute)
int stepButton=200; // stepper steps when button pressed
Stepper myStepper(STEPS, dirA, dirB); // init the stepper class
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, HIGH);
//);
// Set the RPM of the motor
myStepper.setSpeed(rpm);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
Serial.begin(9600);
delay(200);
digitalWrite(ledPin, LOW);
}
void loop(){
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
digitalWrite(ledPin, HIGH);
myStepper.setSpeed(rpm);
myStepper.step(stepButton);
// turn off the brake ?
// digitalWrite(brakeA, LOW);
// digitalWrite(brakeB, LOW);
}
else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
} | https://forum.arduino.cc/t/motorshield-and-stepper-troubles/168545/9 | CC-MAIN-2021-21 | refinedweb | 616 | 52.12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.