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
During the development of a new application, almost always, there is a need to have components with specific features in order to meet the requirements of a project or just to make things more natural and comfortable to use. Because of this, you will either extend your component from an existing one or create one from scratch. In both cases, it can bring you a lot of headache, and for a while deviate you from your main goal of development. An example of such a problem is the customization of the tabbed pane (JTabbedPane) to give it the functionality of open tabs' closing. JTabbedPane You can solve this problem by adding a button to the tab content, which often appears to be confronting the content, and not good looking at all, or extending the tabbed pane to have the close button embedded in the title bar of each tab. For the second choice, a comparably simple solution can be the usage of a component for tab title rendering. The component can be set for every tab (setTabComponentAt(index, component )) and you need to implement it to show the title and close button. setTabComponentAt(index, component ) An alternative solution can be the usage of this extension of JTabbedPane that adds not only the functionality of closable tabs, but also gives the ability to control the event of tab closing. The usage of the code is very simple; just use ClosableTabbedPane instead of JTabbedPane. ClosableTabbedPane // Implementation with close event handeling public class TabFrame extends JFrame { private ClosableTabbedPane tabbedPane; public TabFrame() { tabbedPane = new ClosableTabbedPane() { public boolean tabAboutToClose(int tabIndex) { String tab = tabbedPane.getTabTitleAt(tabIndex); int choice = JOptionPane.showConfirmDialog(null, "You are about to close '" + tab + "'\nDo you want to proceed ?", "Confirmation Dialog", JOptionPane.INFORMATION_MESSAGE); return choice == 0; // if returned false tab // closing will be canceled } }; getContentPane().add(tabbedPane); } // Simple implementation public class TabFrame extends JFrame { private ClosableTabbedPane tabbedPane; public TabFrame() { tabbedPane = new ClosableTabbedPane() ; getContentPane().add(tabbedPane); } } In the first implementation, you can see that the tabAboutToClose(tabIndex) function of ClosableTabbedPane is overridden to control the event of tab closing. The returned true/false value indicates whether the tab should be closed or not. Here you can do your processing before closing the tab. tabAboutToClose(tabIndex) true/false If you do not need to control the closing event, just use the second code. The interesting part of this project is that it was written without diving into the tabbed pane implementation, while achieving the desired functionality. This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) tabbedPane.setBounds(10,10,10,10); 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.
http://www.codeproject.com/Articles/18496/JTabbedPane-with-Closing-Tabs?msg=3767342
CC-MAIN-2016-44
refinedweb
467
51.18
Getting Started¶ The basics : Theory : The PandAI library has been built upon the design pattern of composition. There exists a main AIWorld Class which governs all updates of any AICharacters added to it. Each AICharacter has its own AIBehavior object which keeps track of all position and rotation updates based on the type of AI which is acting on that character. So in short : AIWorld -> AICharacter -> AIBehavior Each AIBehavior object has the functionality to implement all the steering behaviors and pathfinding behaviors. So once you get a reference to this object from the AICharacter, it should give you the ability to call the respective functions. Implementation: Following are the steps to get the basics of PandAI working. Don’t worry if you can’t understand some of them. Step 1: To use our AI library into your game you need to import PandAI into your game code via: from panda3d.ai import * Step 2: Create an object of the AIWorld class which defines your AI in your game world. Step 3: Setup a task which runs continuously which keeps calling the ‘Update()’ function for your previously created AIWorld object Step 4: To test this out let us also implement a simple call to the ‘seek’ behavior function in PandAI. To do this we need two objects: A seeker and a target. For this example, we will use Ralph (seeker) and an arrow model (target). Step 5: Create an ‘AICharacter’ object and attach it to your AIWorld class (previously created). The AICharacter constructor looks for a NodePath, this can be a Model or an Actor or even an Empty NodePath. Step 6: Get a reference to the AIBehaviors object of your previously created AICharacter class via the ‘getAiBehaviors’ function(). Step 7: Call the seek function on your AIBehaviors reference (previously created). The seek function takes a NodePath or a Vector3 position to seek to. Step 8: Start your AIWorld update task which you created earlier. Step 9: Watch how your awesome seek function works! The actual code: import direct.directbase.DirectStart from panda3d.core import * from direct.showbase.DirectObject import DirectObject from direct.task import Task from direct.actor.Actor import Actor #for Pandai from panda3d.ai import * class World(DirectObject): def __init__(self): base.disableMouse() base.cam.setPosHpr(0, 0, 55, 0, -90, 0) self.loadModels() self.setAI() def loadModels(self): # Seeker ralphStartPos = Vec3(-10, 0, 0) self.seeker = Actor("models/ralph", {"run":"models/ralph-run"}) self.seeker.reparentTo(render) self.seeker.setScale(0.5) self.seeker.setPos(ralphStartPos) # Target self.target = loader.loadModel("models/arrow") self.target.setColor(1, 0, 0) self.target.setPos(5, 0, 0) self.target.setScale(1) self.target.reparentTo(render) def setAI(self): #Creating AI World self.AIworld = AIWorld(render) self.AIchar = AICharacter("seeker",self.seeker, 100, 0.05, 5) self.AIworld.addAiChar(self.AIchar) self.AIbehaviors = self.AIchar.getAiBehaviors() self.AIbehaviors.seek(self.target) self.seeker.loop("run") #AI World update taskMgr.add(self.AIUpdate,"AIUpdate") #to update the AIWorld def AIUpdate(self,task): self.AIworld.update() return Task.cont w = World() base.run() Note It doesn’t matter where your seek is first called (ie. before the AIWorld update or after) it should still work as soon as the Update starts processing. Note: This above example is only for seek but if you go to each of the pages, a separate example is provided showing you each AI individually. If you want to get a working demo of this tutorial, please visit : Next Step: Now that you have a basic working program of PandAI, you should proceed to the Steering Behaviors page and gain more knowledge of the system from there.
https://docs.panda3d.org/1.10/cpp/programming/pandai/getting-started
CC-MAIN-2020-24
refinedweb
609
50.94
I am struggling with implementing this when I have a list of values for, say, 4 points that I want to add:I am struggling with implementing this when I have a list of values for, say, 4 points that I want to add:h.pt3dadd(xvec, yvec, zvec, dvec, sec=section) ... Add the 3d location and diameter point (or points in the second form) at the end of the current pt3d list ... Note: A more object-oriented approach is to use sec.pt3dclear() instead. Gives the error Code: Select all from neuron import h, gui import numpy as np dend=h.Section(name='dend') dend.pt3dclear() xvec=h.Vector(np.array([-0.72,-0.72,-0.72,-0.72])) yvec=h.Vector(np.array([-16.42,-18.16,-22.14,-24.13])) zvec=h.Vector(np.array([0.0,0.0,0.0,0.0])) dvec=h.Vector(np.array([2.4,2.2,2.0,1.96])) dend.pt3dadd(xvec, yvec, zvec, dvec) I get the same error with:I get the same error with:TypeError: must be real number, not hoc.HocObject While I get other errors when trying the following: Code: Select all xvec=h.Vector([-0.72,-0.72,-0.72,-0.72]) I'm using Neuron 7.7.2: Code: Select all xvec=[-0.72,-0.72,-0.72,-0.72] # gives the error: must be real number, not list xvec=np.array([-0.72,-0.72,-0.72,-0.72]) # gives the error: TypeError: only size-1 arrays can be converted to Python scalars What am I doing incorrectly when trying to supply vectors instead of scalars as arguments to pt3dadd? Code: Select all print(neuron.version) 7.7.2
https://www.neuron.yale.edu/phpBB2/viewtopic.php?f=2&t=4259&sid=80c1699a5707636a5939b8d7752a7043
CC-MAIN-2021-21
refinedweb
287
55.74
Am 21.04.2012 20:47, schrieb Reimar Döffinger: > On Sat, Apr 21, 2012 at 05:51:22PM +0200, Roland Scheidegger wrote: >> + int *rip; >> + > > Why int * and not void *? You're right that's cleaner. > Also, tailing whitespace. I'll fix that. > >> - "movzbl "MANGLE(last_coeff_flag_offset_8x8)"(%k6), %k6\n\t" >> +#ifdef BROKEN_RELOCATIONS >> + "movzbl "LABEL_MANGLE(last_coeff_flag_offset_8x8)"-1b(%14, %q6), %k6\n\t" >> +#else >> + "movzbl "LABEL_MANGLE(last_coeff_flag_offset_8x8"(%k6), %k6\n\t" >> +#endif > > Why did you change the else case? Besides the missing ) I don't think > it's correct to use LABEL_MANGLE for that one. I missed the bracket indeed (mistakenly removed the mangle initially). As for LABEL_MANGLE vs. MANGLE I can change it back. LABEL_MANGLE is only different from MANGLE in case of ARCH_X86_64 && defined(PIC) (which equals BROKEN_RELOCATIONS) hence it doesn't really matter, I don't know which one is "more correct" but I'll change it back. Roland
http://ffmpeg.org/pipermail/ffmpeg-devel/2012-April/123646.html
CC-MAIN-2015-14
refinedweb
149
59.09
Google Cloud for Data Science: Beginner's Guide While AWS EC2 is the leader in cloud computing, Google Cloud has developed a very compelling and competitive Cloud Computing platform. In this tutorial, you will learn how to: - Create an instance on Google Compute Engine (GCE), - Install a data science environment based on the Anaconda Python distribution, and - Run Jupyter notebooks accessible online. Working in the cloud instead of on your own machine has two main advantages for data science projects: - Scalability: you can tailor the power (RAM, CPU, GPU) of your instance to your immediate needs. Starting with a small and cheap instance and adding memory, storage, CPUs or GPUs as your project evolves. - Reproducibility: a key condition of any data science project. Allowing other data scientists to review your models and reproduce your research is a necessary condition of a successful implementation. By setting up a working environment on a virtual instance, you make sure your work can easily be shared, reproduced, and vetted by other team members. Google Compute Engine Although built around the same concepts and elements (instances, images and snapshots), EC2 and GCE differ on both access and resources organization. A key aspect of the Google Cloud Platform (GCP) is its project-centered organization. All billing, permissions, resources and settings are grouped within a user-defined project which basically acts as a global namespace. This not only simplifies the interconnected mapping of the resources you use (storage, databases, instances, ...) but also access management from role-based permissions to actual ssh keys and security. When it comes to user friendliness and access and role management, I find that working on the GCP is easier than working with AWS especially using multiple services. The GCP also offers certain services which are particularly relevant for data science, including but not limited to: - Dataprep to build data processing pipelines, - Datalab for data exploration, - the Google Machine Learning Engine built on TensorFlow - BigQuery a data warehouse solution that holds many fascinating Big Data datasets. A low learning curve and data friendly services make the GCP a must have in your data scientist toolbox. Before you start launching instances and installing Python packages, let's spend a few moments to review some of the common vocabulary used in Cloud Computing. VMs, Disks, Images and Snapshots A Virtual Machine (VM) also called "an instance" is an on-demand server that you activate as needed. The underlying hardware is shared among other users in a transparent way and as such becomes entirely virtual to you. You only choose a global geographic location of the instance hosted in one of Google's data center. A VM is defined by the type of persistent disk and the operating system (OS), such as Windows or Linux, it is built upon. The persistent disk is your virtual slice of hardware. An image is the physical combination of a persistent disk and the operating system. VM Images are often used to share and implement a particular configuration on multiple other VMs. Public images are the ones provided by Google with a choice of specific OS while private images are customized by users. A snapshot is a reflection of the content of a VM (disk, software, libraries, files) at a given time and is mostly used for instant backups. The main difference between snapshots and images is that snapshots are stored as diffs, relative to previous snapshots, while images are not. An image and a snapshot can both be used to define and activate a new VM. To recap, when you launch a new instance, GCE starts by attaching a persistent disk to your VM. This provides the disk space and gives the instance the root filesystem it requires to boot up. The disk installs the OS associated with the image you have chosen. By taking snapshots of an image, you create instant backups and you can copy data from existing VMs to launch new VMs. Let's put all of that in practice and get started with your first VM! Getting Started with Your First VM on GCP To open an account on the GCP, you need a standard Google (Gmail) account. At time of writing, Google offers a 12 months / $300 free trial of the platform. Although this offer comes with certain restrictions (no bitcoin mining, for instance), it should be sufficient to get you started working in this environment. To create your GCP account with the free trial, go to cloud.google.com and click on the try it free button. You will be asked to login with your Google account and add your billing information. Once your account is created, you can access the web console at. You will first use the web console to define and launch a Debian-based instance and then switch to the web-based shell terminal to install all the necessary packages for your data science stack. But first you need to create a new project: - Go to the Resource Management page, - Click on "Create a new project", - Specify your project's title and notice how Google generates a project ID on the fly. - Edit the project ID as needed and click on "Create". The project ID has to be unique across the GCP naming space, while the project title can be anything you want. I name my project datacamp-gcp as shown below: By default, when you create a new project, your Google account is set as the owner of the project with full permissions and access across all the project's resources and billing. In the roles section of the IAM page, you can add people with specific roles to your project. For the purpose of this tutorial, you will skip that part and keep you as the sole user and admin of the project. Create an instance To create your first VM, you just go through the following steps: - Go to your dashboard at and select the project that you just created. - In the top left menu select "Compute Engine" and click on "VM instances". - In the dialog, click on the "Create" button. You are now on the "Create an Instance" page. Name the instance: you can choose any name you want. I name my instance starling. Select the region: the rule of thumb is to select the cheapest region closest to you to minimize latency. I choose east-d. Note that prices vary significantly by region. Select the memory, storage and CPU you need. You can use one of several presets or customize your own instance. Here, I choose the default setup n1-standard-1with 3.75 Gb RAM and 1vCPU for an estimated price of $24.67 per month. Select the boot disk and go with the default Debian GNU/Linux 9 (stretch) OS with 10 Gb. If you prefer using Ubuntu or any other linux distribution, click on the "Change" button and make the appropriate selection. Since Ubuntu is a close derivation of Debian, either distributions will work for this tutorial. 5.Make sure you can access the VM from the internet by allowing http and https traffic. 6.(Optional) Enable a persistent disk for backup purposes: Click on the "Management, Disks, networking, SSH keys" link. This displays a set of tabs, select the "Disks" tab and unselect the "Deletion Rule". This way, when you delete your instance, the disk will not be deleted and can be used later on to spin up a new instance. 7.Finally, click on "Create". Your instance will be ready in a few minutes. Notice the link "Equivalent command line" link below the Create button. This link shows the equivalent command line needed to create the same instance from scratch. This is a truly smart feature that facilitates learning the syntax of gcloud SDK. At this point, you have a running instance which is pretty much empty. There are 2 ways you can access the instance. Either by installing the gcloud SDK on your local machine or by using Google's Cloud Shell. Google's Cloud Shell Google's Cloud Shell is a stand alone terminal in your browser from which you can access and manage your resources. You activate the google shell by clicking the >\_ icon in the upper right part of the console page. The lower part of your browser becomes a shell terminal. This terminal runs on a f1-micro Google Compute Engine virtual machine with a Debian operating system and 5Gb storage. It is created on a per-user, per-session basis. It persists while your cloud shell session is active and is deleted after 20 minutes of inactivity. Since the associated disk is persistent across sessions, your content (files, configurations, ...) will be available from session to session. The cloud shell instance comes pre-installed with the gcloud SDK and vim. It is important to make the distinction between the Cloud shell instance, which is user-based, and the instance you just created. The instance underlying the cloud shell is just a convenient way to have a resource management environment and store your configurations on an ephemeral instance. The VM instance that you just created, named starling in the above example, is the instance where you want to install your data science environment. Instead of using the Google Cloud shell, you can also install the gcloud SDK on your local machine and manage everything from your local environment. Here are a few useful commands to manage your instances. List your instances gcloud compute instances list Stop the instance (takes a few seconds) gcloud compute instances stop <instance name> Start the instance (also takes a few seconds) gcloud compute instances start <instance name> and ssh into the starling instance gcloud compute ssh <instance name> Setting up the VM Run that last command in your Google Shell window to log in your instance. The next steps will consists in: - Installing a few Debian packages with apt-get install. - Installing the Anaconda or Miniconda distribution. - Setting up the instance to make Jupyter notebooks securely accessible online. Debian packages Let's start by installing the Debian packages: - bzip2, which is required to install Mini/Anaconda, - git, which is always useful to have, and - libxml2-dev, which is not required at this point but you will often need it when installing further Python libraries. Run the following commands, which work for both Ubuntu and Debian, in the terminal: $ sudo apt-get update $ sudo apt-get install bzip2 git libxml2-dev Anaconda / Miniconda Once the above packages are installed, turn your attention to installing the Anaconda distribution for Python 3. You have the choice between installing the full Anaconda version which includes many scientific Python libraries, some of which you may not actually need or installing the lighter Miniconda version which requires you to manually install the Jupyter libraries. The process is very similar in both cases. To install the lighter Miniconda distribution, run $ wget $ bash Miniconda3-latest-Linux-x86_64.sh $ rm Miniconda3-latest-Linux-x86_64.sh $ source .bashrc $ conda install scikit-learn pandas jupyter ipython The install shell script is downloaded and run with the first 2 lines. You should accept the license and default location. In line 3, the no longer needed shell file is removed. Sourcing .bashrc on line 4, adds the conda command to your $PATH without having to open a new terminal. And finally, the last line installs the required python libraries: scikit-learn pandas jupyter ipython. The commands to install the full Anaconda distribution are very similar. Make sure to check the download page to get the latest version of the shell script file: $ wget $ bash Anaconda3-5.0.1-Linux-x86_64.sh $ rm Anaconda3-5.0.1-Linux-x86_64.sh $ source .bahsrc To verify that everything is installed properly, check your python version with python --version and verify that the right python is called by default with the command which python. You should be getting something similar to You now have a working Python environment with the standard data science libraries installed ( sklearn, pandas) . Allowing Web Access The third and final step is to configure your VM to allow web access to your Jupyter notebooks. You first need to make the VM accessible from the web. To do that, you will create a firewall rule via the Google Cloud console. Go back to your Instances dashboard and in the top left menu, select "VPC Network > Firewall rules". Click on the "CREATE FIREWAL RULE" link and fill out the following values: - Name: jupyter-rule (you can choose any name) - Source IP ranges: 0.0.0.0/0 - Specified protocols and ports: tcp:8888 - and leave all the other variables to their default values. The form should look like: This firewall rule allows all incoming traffic (from all IPs) to hit the port 8888. Using the "Equivalent command line link", you can see that firewall rule can also be created from the terminal with the following command line: $ gcloud compute --project=datacamp-gcp firewall-rules create jupyter-rule --direction=INGRESS --priority=1000 --network=default --action=ALLOW --rules=tcp:8888 --source-ranges=0.0.0.0/0 Now go back to the VM page (top left menu > Compute Engine > VM instances), click on your VM name. Make a note of your VM IP address. This is the IP address that you will use in your browser to access your Jupyter environment. In my example, the IP address is: 35.196.81.49, yours will be different. and make sure the Firewall rules are checked: Jupyter Configuration Jupyter notebooks come with a configuration file that needs to be generated and edited in order to setup online access to your notebooks. In the terminal, run jupyter notebook --generate-config to generate the configuration file. And jupyter notebook password to generate a password. Tip: make sure that this is a strong password! Now edit the configuration file you just created with vim .jupyter/jupyter_notebook_config.py and add the following line at the top of the file c.NotebookApp.ip = '*' (to switch to edit mode in vim, just type the i character). Quit and save with the following sequence ESC:wq. This will allow the notebook to be available for all IP addresses on your VM and not just the URL you may be familiar with when working on your local machine. Launch You are now ready to launch your Jupyter notebook with the command line: $ jupyter-notebook --no-browser --port=8888 And you should see something like that in the terminal: In your browser go to the URL: http://<your_VM_IP>:8888/ to access your newly operational Jupyter notebook. To check that everything is working as expected, create a new Python 3 notebook, and import pandas Intermezzo A few notes on your current setup: The IP address you used in your browser is ephemeral. Which means that every time you restart your VM, your notebooks will have a different URL. You can make that IP static by going to: Top left menu > VPC Network > External IP addresses and select "static" in the drop down menu The security of your current setup relies on the strength of the Jupyter notebook password that you defined previously. Anyone on the internet can access your Jupyter environment at the same URL you use (and bots will absolutely try). One powerful but very unsecure core feature of Jupyter notebooks is that you can launch a terminal with sudo access directly from the notebook. This means that anyone accessing your notebook could take control of your VM after cracking your notebook password and potentially run anything that would send your bills through the roof. The first level measures to prevent that from happening includes Making sure your Jupyter password is a strong one - Remember to stop your VM when you're not working on it You are also currently running the server over http and not https which is not secure enough. Let’s Encrypt provides free SSL/TLS certificates and is the encryption solution recommended in the jupyter documentation. For more information on security issues related to running a public Jupyter notebook, read this. IPython Jupyter notebooks are very convenient for online collaborative work. But you can also run an IPython session from your terminal simply with the ipython command. That will open an IPython session which has all the bells and whistles of a Jupyter notebook such as magic commands (%paste, %run, ...) but without the web interface. R It's easy to set up your VM to be enable R notebooks in your Jupyter console. The instructions for enabling R Markdown are available from this great DataCamp tutorial: Jupyter And R Markdown: Notebooks With R by Karlijn Willems. Conclusion Google Cloud offers many interesting services for data science and powerful yet easy to setup VM instances alongside a very attractive free trial offer. The web console is easy to navigate and often displays the command line equivalent to current configuration pages, thus lowering the barrier to using the gcloud SDK. In this article, you've learned how to select and launch a VM instance, install the necessary Debian packages, Anaconda distribution and data science stack and finally how to setup the access rules to launch a Jupyter notebook accessible from your browser. Although the whole process may seem a bit complex the first time, it will quickly become familiar as you create and launch more and more VMs. And in case things become a bit too muddled, you can always delete the VM you're working on and restart from scratch. That's one of the perks of working in the cloud. After a few times you will be able to spin up complete data science environments on Google Cloud in a few minutes. Feel free to reach out and share your comments and questions with me on twitter: @alexip.
https://www.datacamp.com/community/tutorials/google-cloud-data-science
CC-MAIN-2019-35
refinedweb
2,966
61.16
Read digital input In this example, let's try to read digital signals using a pushbutton. When you press or release the button, the input value will change accordingly, either true or false. You can see the result in the serial monitor.. note In a breadboard, the holes beside the blue horizontal line are all connected. They are for ground. The holes beside the red line are the same and connect to the power pin. In the middle, there are 30 rows. The holes A, B, C, D, E in the same row are connected internally. The holes F, G, H, I, J are the same. So make sure the button is placed in the right direction. info You can notice the wires are in different colors. Usually, red is for the wire connected to power, and black is for ground. Example code You can find the example code by clicking the bottom left corner of IDE: / GettingStarted / ReadDigitalInput. // Read the input voltage on a specified digital pin. The value you get will be either true or false. // Import the library to enable the relevant classes and functions. import SwiftIO // Import the board library to use the Id of the specific board. import MadBoard // Initialize the pin D1 as a digital input pin. let pin = DigitalIn(Id.D1) // read the input every second. while true { // Declare a constant to store the value you read from the digital pin. let value = pin.read() // Print the value and you can see it in the serial monitor. print(value) // Wait a second and then continue to read. sleep(ms: 1000) } Background Button pin = DigitalIn(Id.D1) The button connects to pin D1. The digital pins can be used as both input and output. You will set it when initializing the pin. Here the pin serves as input, so you need the class DigitalIn. let value = pin.read() The method read() allows you to get the input value. The return value is either true or false, representing high and low level respectively. So you can know the states of the button according to the values. If you press the button, the pin connects to 3V3, so the value will be true. Once you release the button, the input value will be false. print(value) The function print() can print the values out. You can view them on the serial monitor by connecting the serial port to your computer. Here is a guide to tell you how to open the serial monitor. Reference DigitalIn - read the input value from a digital pin. init(_:mode:)- initialize the digital input pin. The first parameter needs the id. You can refer to the corresponding Idenumeration. The parameter mode already has a default value. read()- read values from a input pin. It will return a boolean value. truecorresponds to a high level, and falsecorresponds to a low level. print() - print the values out. MadBoard - find the corresponding pin id of your board.
https://docs.madmachine.io/tutorials/general/getting-started/read-digital-input
CC-MAIN-2022-21
refinedweb
494
69.79
![if gte IE 9]><![endif]> DB version is Openedge 10.2, running in Windows 2003 R2 Enterprise Edition VM, I created a table (with 3 CHARACTER columns) using Data Administration tool (Admin -> Load Data and Definitions -> Data Definitions (.df file). Now, I want to load data into the table using a .d file, contents below: "100" "101" "101A""100" "101" "101B""100" "101" "101C" And I see multiple options to accomplish this: Questions: 1. Admin -> Load Data and Definitions -> Table contents (.d file) option in Data Administration tool seems to be disabled. Why? I have OE Enterprise RDBMS 1 year EVAL license. I also tried launching the tool using rx option (prowin32 -p _admin -rx), the option is still disabled. 2. I was trying to use 'input from' command: INPUT FROM stgrp.d. REPEAT: IMPORT stgrp.pgroup stgrp.parent stgrp.subgroup. END. INPUT CLOSE. This command just displays the line number for the next command, and sits there. I ran this command from sqlexplorer prompt. What am I missing? SQLExplorer>INPUT FROM stgrp.d. 1> REPEAT:2> IMPORT stgrp.pgroup stgrp.parent stgrp.subgroup. 3> END.4> INPUT CLOSE.5> 3. I see one more option online - prodict. What is it, how do I execute it, and from where? This is my first time working on openedge, appreciate any help I can get. Thank you! rv. > If so, is there a way to load the data with what I have? - See more at: .... 3) another option since you have ascii file, would be a bulk load (proutil dbname -C bulkload dbname.fd) - you can create the bulk loader description file in data administration. 1) it's probably the license (assuming you have the database connected); "showcfg" will tell you (or configinfo icon) 2) SQLExplorer uses SQL(92) syntax, it does not know what to do with ABL commands; you need to execute this from the procedure editor (prowin32 or mpro) and you would need to create a record in the table first, ie input from stgrp.d. repeat: create stgrp. import stgrp. end. input close. Option 1: I don't know why Load Table Contents would be disabled - somebody from Progress with access to the source-code should be able to answer that question. Could it be a licensing issue? 2. Option 2: You are writing an ABL program, but are trying to execute it in the SQL Explorer. ABL you can execute within the Progress Editor (Start -> All Programs -> OpenEdge -> client). Also, you are missing the statement CREATE stirrup. before the import. Option 3: this is basically the same as running the Table Load within the admin-tool. It's just a wrapper program which can be run from a shell-script (for automating dumps and loads of data and definitions). It is actually running the same as the Admin-Tool UI. I am suspecting, that it won't do the trick as it most likely runs into the same restriction that caused the option to be disabled in the tool... Thomas Hutegger tmh@smat-consulting.com SMAT-Tools - Web-Apps with RollBase simpleness, ABL flexibility and power 1) showcfg: Configuration File: C:\Progress\OpenEdge\PROGRESS.CFG Company Name: Product Name: OE Enterprise RDBMS Installation Date: Wed Sep 23 09:06:47 2015 User Limit: 5 Expiration Date: 10/21/2016 Serial Number: Control Numbers: Version Number: 10.2B Machine Class: KB Port Number: 31 2) I opened the tool using prowin32 -p _admin -rx. I opened a procedure editor to run the command: INPUT FROM "C:\data\tfs\stgrp.d". REPEAT: CREATE stgrp. IMPORT stgrp. END. INPUT CLOSE. It gave me a compiler message - 'This version of PROGRESS compiles only encrypted programs. (1086)'. I am not sure if I am in the correct window! For option 2: When I go to Start -> All Programs -> OpenEdge -> client, I get a message in the bottom of the window saying - 'openedge client "This version of PROGRESS requires a start up procedure (495):' 'Press space bar to continue' When I press space bar, the window closes. I assume there might be help on this problem online, looking.. replying to you as well, Thank you for your help. rv UPDATE - I am not able to find any useful information online yet, still looking.. But i keep thinking that it is something to do with license! Can someone please point me in the right direction? you are missing the 4gl dev license. It is what allows you to run uncompiled code and allows the use of the menus in the data dictionary for what you are trying to do. For some reason, I am not able to find some basic information online, guess i need to go home now! What I have is a windows VM used for development only purposes, we wouldn't want to pay for license at this point. Is 4GL a paid version? This is the only information I could find in one of the pdfs I see online: 4GL Development / Provision / OE Studio / OE Architect • Licensed as with all standard products • Must only be installed at your customer sites if registered to them If so, is there a way to load the data with what I have? Ah, overlooked this in your earlier response. Thanks Libor. I will look into this option, try it and post the result. Excellent, Thank You very much! I was able to load data in all 3 tables.. (had to fix the .d file for a couple of tables with DATE columns, but that is data issue) and grant some privileges!
https://community.progress.com/community_groups/openedge_rdbms/f/18/p/26408/90604
CC-MAIN-2019-13
refinedweb
927
73.98
MASM32 Downloads #include <stdio.h> //if is found in the first 1k, F5 will build all as C codevoid TheFunc(int ThePassedNumber) { ThePassedNumber = 0x11111111; // manipulates the stack content, i.e. [the arg]}void TheFunc_ptr(int *ThePassedNumber) { *ThePassedNumber = 0x22222222; // gets a pointer and writes there}void TheFunc_ref(int &ThePassedNumber) { ThePassedNumber = 0x33333333; // gets a pointer and writes there (identical to TheFuncPtr)}int main(void) { //__asm int 3; // for Olly int TheNumber; int& TheRef = TheNumber; /*00401079 ³? 8D45 F8 lea eax, [ebp-8]0040107C ³. 8945 F0 mov [ebp-10], eax ; save a pointer to ptr TheNumber */ TheNumber = 0x12345678; // writes to local memory /*0040107F ³? C745 F8 78563412 mov dword ptr [ebp-8], 12345678 */ printf("Original number=\t%xh\n", TheNumber); //__asm int 3; TheFunc(TheNumber); /*004010A2 ³. 8B55 F8 mov edx, [ebp-8]004010A5 ³? 52 push edx004010A6 ³? E8 6EFFFFFF call 00401019...TheFunc Ú$ À55 push ebp ; CppConsoleJJ.TheFunc(ThePassedNumber)00401031 ³. 8BEC mov ebp, esp00401033 ³. C745 08 11111111 mov dword ptr [ebp+8], 11111111 ; WRITE TO STACK0040103A ³. 5D pop ebp0040103B À. C3 retn */ printf("My number func'ed=\t%xh (i.e. not changed)\n", TheNumber); TheFunc_ptr(&TheNumber); /*004010C9 ³. 8D4D F8 lea ecx, [ebp-8] ; ptr TheNumber004010CC ³? 51 push ecx004010CD ³? E8 4CFFFFFF call 0040101E...TheFunc_ptr Ú$ À55 push ebp ; CppConsoleJJ.TheFunc_ptr(ThePassedNumber)00401041 ³. 8BEC mov ebp, esp00401043 ³. 8B45 08 mov eax, [ebp+8]00401046 ³. C700 22222222 mov dword ptr [eax], 222222220040104C ³. 5D pop ebp0040104D À. C3 retn */ printf("My number ptr'ed=\t%xh\n", TheNumber); TheFunc_ref(TheRef); /*004010F0 ³. 8B45 F0 mov eax, [ebp-10] ; value of TheRef004010F3 ³? 50 push eax004010F4 ³? E8 2AFFFFFF call 00401023...TheFunc_ref Ú$ À55 push ebp ; CppConsoleJJ.TheFunc_ref(ThePassedNumber)00401051 ³. 8BEC mov ebp, esp00401053 ³. 8B45 08 mov eax, [ebp+8]00401056 ³. C700 33333333 mov dword ptr [eax], 333333330040105C ³. 5D pop ebp0040105D À. C3 retn */ printf("My real number= \t%xh\n", TheNumber); printf("My ref'ed number=\t%xh\n", TheRef); return (0);} ...void TheFunc_ptr(int *ThePassedNumber) { *ThePassedNumber = 0x22222222; // gets a pointer and writes there}#ifdef __cplusplusvoid TheFunc_ref(int &ThePassedNumber) { ThePassedNumber = 0x33333333; // gets a pointer and writes there (identical to TheFuncPtr)}#endif... References are cute!MyArray[5]=1005, ElementFive=1005MyArray[5]=2010, ElementFive=2010MyArray[5]=4020, ElementFive=4020MyArray[5]=8040, ElementFive=8040 <<<<<<< great, isn't it?Hit Enter to end this disaster MyArray[5]=8040, ElementFive=8040 <<<<<<< great, isn't it? The reference becomes invalid when realloc() moves the memory block ... what a mystery ::) But all that is in sharp contrast to the enthusiastic article quoted above. As Manos rightly writes, references are apparently dangerous nonsense. what is their added value for programming, compared to a pointer? the author explicit warns about invalid references References and Dynamically Allocated MemoryFinally, beware of references to dynamically allocated memory. One problem is that when you use references, it's not clear that the memory backing the reference needs to be deallocated--it usually doesn't, after all. This can be fine when you're passing data into a function since the function would generally not be responsible for deallocating the memory anyway.On the other hand, if you return a reference to dynamically allocated memory, then you're asking for trouble since it won't be clear that there is something that needs to be cleaned up by the function caller. Quote from: jj2007 on December 16, 2013, 09:11:12 AMAs Manos rightly writes, references are apparently dangerous nonsense. All that has been said also applies for pointers! Just replace the reference with a pointer and see what happen. void TheFunc_ptr(int *ThePassedNumber) {printf("Passed as ptr: %i\n", *ThePassedNumber);}void TheFunc_ref(int &ThePassedNumber) {printf("Passed as ref: %i\n", ThePassedNumber);}... TheFunc_ptr(&MyArray[5]); TheFunc_ref(ElementFive); Quote from: qWord on December 16, 2013, 10:04:34 AMthe author explicit warns about invalid referencesHe should get a prize for the foggiest para of the year - and not a word on HeapReAlloc, the only relevant case ;-) I think the lesson is simply that references are much trickier than it seems. Pointers are more reliable - see my edit above, posted just a second before your last post. So realloc is old-fashioned. Would the C++ compiler update the reference to element 5 if you insert an element at position 2 into a vector of integers? Quote from: jj2007 on December 16, 2013, 10:58:09 AMWould the C++ compiler update the reference to element 5 if you insert an element at position 2 into a vector of integers?References are never "updated" - they always refer to the object they have been initialized with. Because std::vector is implemented as an array that is reallocated if required, all references, pointer and iterators are invalidated after insertion.
https://masm32.com/board/index.php?topic=2733.0
CC-MAIN-2022-27
refinedweb
790
59.09
Preface This article is based on a basic shopping cart demand, step by step, to give you a deep understanding of the pit and Optimization in React Hook You can learn from this article: A kind of Practice of writing business components with React Hook + TypeScript A kind of How to use React.memo to optimize performance A kind of How to avoid the closure trap brought by Hook A kind of How to abstract a simple and easy-to-use custom hook Preview address Code repository The code involved in this article has been sorted out into github warehouse, and a sample project has been built with cra. For the part of performance optimization, you can open the console to see the re rendering situation. Demand decomposition As a shopping cart demand, it must involve several demand points: 1. Check, select all and invert selection. 2. Calculate the total price according to the selected items. Requirement realization get data First of all, we request the shopping cart data. This is not the focus of this article. It can be realized through a custom request hook, or through a common useState + useEffect. const getCart = () => { return axios('/api/cart') } const { // Cart data cartData, // How to re request data refresh } = useRequest<CartResponse>(getCart) Check logic implementation We cons id er using an object as a mapping table to record all checked commodity IDS through the variable checkedMap: type CheckedMap = { [id: number]: boolean } // Commodity selection const [checkedMap, setCheckedMap] = useState<CheckedMap>({}) const onCheckedChange: OnCheckedChange = (cartItem, checked) => { const { id } = cartItem const newCheckedMap = Object.assign({}, checkedMap, { [id]: checked, }) setCheckedMap(newCheckedMap) } Calculate total check price Use reduce to realize a function of calculating the sum of prices // Sum of cartItems const sumPrice = (cartItems: CartItem[]) => { return cartItems.reduce((sum, cur) => sum + cur.price, 0) } Then you need a function to filter out all the selected products // Return all selected cartItems const filterChecked = () => { return ( Object.entries(checkedMap) // Filter out all items with checked status of true through this filter .filter(entries => Boolean(entries[1])) // Then map the selected list from cartData according to the id .map(([checkedId]) => cartData.find(({ id }) => id === Number(checkedId))) ) } Finally, combine these two functions and the price will come out: // Calculate gift points const calcPrice = () => { return sumPrice(filterChecked()) } Some people may wonder why a simple logic should extract such several functions. Here I want to explain that in order to ensure the readability of the article, I have simplified the real needs. In the real demand, the total price of different types of goods may be calculated separately, so the filterChecked function is indispensable. filterChecked can pass in an additional filter parameter to return a subset of the selected goods, which will not be discussed here. Select all and invert selection logic With the filterChecked function, we can easily calculate the derived state checkedAll. Select all or not: // All election const checkedAll = cartData.length !== 0 && filterChecked().length === cartData.length Write the functions of select all and anti select all: const onCheckedAllChange = newCheckedAll => { // Construct a new tick map let newCheckedMap: CheckedMap = {} // All election if (newCheckedAll) { cartData.forEach(cartItem => { newCheckedMap[cartItem.id] = true }) } // If you deselect all, you can directly assign the map as an empty object setCheckedMap(newCheckedMap) } If yes - select all, each item id of the checkedMap is assigned to true. -Invert selection to assign checkedMap as an empty object. Rendering product subcomponents {cartData.map(cartItem => { const { id } = cartItem const checked = checkedMap[id] return ( <ItemCard key={id} cartItem={cartItem} checked={checked} onCheckedChange={onCheckedChange} /> ) })} It can be seen that the logic of whether to check is passed to the sub components easily. Performance optimization of React.memo At this point, the basic shopping cart needs have been realized. But now we have new problems. This is a defect of React, which by default has almost no performance optimization. Let's take a look at the moving picture demonstration: At this time, there are 5 items in the shopping cart. When you look at the printing of the console, each time you click the checkbox, it will trigger the re rendering of all the sub components. If we have 50 items in the shopping cart, we change the checked status of one of them, which will also cause 50 sub components to re render. We think of an api: React.memo, which is basically equivalent to the shouldComponentUpdate in the class component. What if we use this api to make the subcomponent re render only when the checked changes? OK, let's go to the writing of subcomponents: // Optimization strategy of memo function areEqual(prevProps: Props, nextProps: Props) { return ( prevProps.checked === nextProps.checked ) } const ItemCard: FC<Props> = React.memo(props => { const { checked, onCheckedChange } = props return ( <div> <checkbox value={checked} onChange={(value) => onCheckedChange(cartItem, value)} /> <span>commodity</span> </div> ) }, areEqual) In this optimization strategy, we think that as long as the checked in the incoming props is equal in the two previous renderings, the sub components will not be re rendered. bug caused by old value of React Hook Is it finished here? Actually, there are bug s here. Let's take a look at bug recovery: If we first click the check of the first product, and then click the check of the second product, you will find that the check status of the first product is gone. After checking the first product, our latest checkedMap at this time is actually { 1: true } Because of our optimization strategy, the second product did not re render after the first product was checked, Note that the functional component of React is re executed every time it is rendered, resulting in a closure environment. Therefore, the onCheckedChange obtained by the second product is still in the function closure of the previous rendering shopping cart component, so the checkedMap is naturally the original empty object in the function closure of the last time. const onCheckedChange: OnCheckedChange = (cartItem, checked) => { const { id } = cartItem // Note that the checkedMap here is still the original empty object!! const newCheckedMap = Object.assign({}, checkedMap, { [id]: checked, }) setCheckedMap(newCheckedMap) } Therefore, after the second product is checked, the correct checkedMap is not calculated as expected { 1: true, 2: true } It's the wrong calculation { 2: true } This results in the first item being dropped. This is also a notorious stale value issue with React Hook closures. Then there is a simple solution. In the parent component, use React.useRef to pass the function to the child component through a reference. Because ref has only one reference in the whole life cycle of React component, the latest function value in the reference can always be accessed through current, and there will be no problem of stale value of closure. // You need to pass ref to the subcomponent so that the subcomponent can get the latest function reference without re rendering const onCheckedChangeRef = React.useRef(onCheckedChange) // Note that you should point the reference in ref to the latest function in each render. useEffect(() => { onCheckedChangeRef.current = onCheckedChange }) return ( <ItemCard key={id} cartItem={cartItem} checked={checked} + onCheckedChangeRef={onCheckedChangeRef} /> ) Sub components // Optimization strategy of memo function areEqual(prevProps: Props, nextProps: Props) { return ( prevProps.checked === nextProps.checked ) } const ItemCard: FC<Props> = React.memo(props => { const { checked, onCheckedChangeRef } = props return ( <div> <checkbox value={checked} onChange={(value) => onCheckedChangeRef.current(cartItem, value)} /> <span>commodity</span> </div> ) }, areEqual) At this point, our simple performance optimization is complete. Custom hook So in the next scenario, we will meet the similar demand of all selection and anti selection. Shall we repeat this? This is unacceptable. We use custom hook s to abstract these data and behaviors. And this time, we use useReducer to avoid the trap of closing the old value (dispatch keeps a unique reference in the component's life cycle, and can always operate to the latest value). import { useReducer, useEffect, useCallback } from 'react' interface Option { /** The id of the key used to record the check status in the map */ key?: string; } type CheckedMap = { [key: string]: boolean; } const CHECKED_CHANGE = 'CHECKED_CHANGE' const CHECKED_ALL_CHANGE = 'CHECKED_ALL_CHANGE' const SET_CHECKED_MAP = 'SET_CHECKED_MAP' type CheckedChange<T> = { type: typeof CHECKED_CHANGE; payload: { dataItem: T; checked: boolean; }; } type CheckedAllChange = { type: typeof CHECKED_ALL_CHANGE; payload: boolean; } type SetCheckedMap = { type: typeof SET_CHECKED_MAP; payload: CheckedMap; } type Action<T> = CheckedChange<T> | CheckedAllChange | SetCheckedMap export type OnCheckedChange<T> = (item: T, checked: boolean) => any /** * Functions such as check, select all and invert selection are provided * Function to filter the selected data * Automatically eliminate obsolete items when updating data */ export const useChecked = <T extends Record<string, any>>( dataSource: T[], { key = 'id' }: Option = {} ) => { const [checkedMap, dispatch] = useReducer( (checkedMapParam: CheckedMap, action: Action<T>) => { switch (action.type) { case CHECKED_CHANGE: { const { payload } = action const { dataItem, checked } = payload const { [key]: id } = dataItem return { ...checkedMapParam, [id]: checked, } } case CHECKED_ALL_CHANGE: { const { payload: newCheckedAll } = action const newCheckedMap: CheckedMap = {} // All election if (newCheckedAll) { dataSource.forEach(dataItem => { newCheckedMap[dataItem.id] = true }) } return newCheckedMap } case SET_CHECKED_MAP: { return action.payload } default: return checkedMapParam } }, {} ) /** Check status change */ const onCheckedChange: OnCheckedChange<T> = useCallback( (dataItem, checked) => { dispatch({ type: CHECKED_CHANGE, payload: { dataItem, checked, }, }) }, [] ) type FilterCheckedFunc = (item: T) => boolean /** After filtering out the check box, you can pass in the filter function to continue filtering */ const filterChecked = useCallback( (func: FilterCheckedFunc = () => true) => { return ( Object.entries(checkedMap) .filter(entries => Boolean(entries[1])) .map(([checkedId]) => dataSource.find(({ [key]: id }) => id === Number(checkedId)) ) // It's possible to delete the id directly after checking it. Although the id is in the checkedMap, the data source has no such data // First filter out the empty items to ensure that the external incoming func does not get undefined .filter(Boolean) .filter(func) ) }, [checkedMap, dataSource, key] ) /** Select all or not */ const checkedAll = dataSource.length !== 0 && filterChecked().length === dataSource.length /** Select all and invert function */ const onCheckedAllChange = (newCheckedAll: boolean) => { dispatch({ type: CHECKED_ALL_CHANGE, payload: newCheckedAll, }) } // When updating data, delete the checked data if it is no longer in the data useEffect(() => { filterChecked().forEach(checkedItem => { let changed = false if (!dataSource.find(dataItem => checkedItem.id === dataItem.id)) { delete checkedMap[checkedItem.id] changed = true } if (changed) { dispatch({ type: SET_CHECKED_MAP, payload: Object.assign({}, checkedMap), }) } }) // eslint-disable-next-line react-hooks/exhaustive-deps }, [dataSource]) return { checkedMap, dispatch, onCheckedChange, filterChecked, onCheckedAllChange, checkedAll, } } In this case, it is very simple to use in components: const { checkedAll, checkedMap, onCheckedAllChange, onCheckedChange, filterChecked, } = useChecked(cartData) We have done all the complicated business logic in the custom hook, including removing the invalid id after data update and so on. Go to promote it to the team's partners and let them get off work early. summary In this paper, a real shopping cart needs to be optimized step by step. In this process, we must have a further understanding of the advantages and disadvantages of React Hook. After using the custom hook to extract the general logic, the amount of code in our business components is greatly reduced, and other similar scenarios can be reused. React Hook brings a new development mode, but it also brings some pitfalls. It is a double-edged sword. If you can use it reasonably, it will bring you great power. Thank you for reading. I hope this article can inspire you.
https://programmer.group/5e75279065517.html
CC-MAIN-2020-24
refinedweb
1,821
51.38
SIN(3P) POSIX Programmer's Manual SIN(3P) This manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux. sin, sinf, sinl — sine function #include <math.h> double sin(double x); float sinf(float x); long double sinl(long double x); The functionality described on this reference page is aligned with the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of POSIX.1‐2008 defers to the ISO C standard. not returned, sin(), sinf(), and sinl() shall return an implementation-defined value no greater in magnitude than DBL_MIN, FLT_MIN, and LDBL_MIN, respectively. If x is ±Inf, a domain error shall occur, and a NaN shall be returned.. Taking the Sine of a 45-Degree Angle #include <math.h> ... double radians = 45.0 * M_PI / 180; double result; ... result = sin(radians);. None. None. asin SIN(3P) Pages that refer to this page: math.h(0p), asin(3p), cos(3p), sinl(3p)
http://man7.org/linux/man-pages/man3/sin.3p.html
CC-MAIN-2017-39
refinedweb
188
59.4
The Easy Way to Do Advanced Data Visualisation for Data Scientists Creating effective data visualisations is a core skill for data scientists. This tutorial will guide you through how to easily develop interactive visualisations using the Python library plotly. Creating effective data visualisations is one of the most valuable skills a Data Scientist can possess. More than just making fancy charts, visualisation is a way of communicating a dataset’s information in a way that’s easy for people to understand. With a good visualisation, one can most clearly see the patterns and information that often lie hidden within the data. In the early stages of a project, you’ll often be doing an Exploratory Data Analysis (EDA) to gain some insights into your data. Creating visualisations will help you along the way to speed up your analysis. Towards the end of your project, it’s important to be able to present your final results in a clear, concise, and compelling manner that your audience, who are often non-technical stakeholders, can understand. There’s no doubt: taking your visualisations to the next level will turbocharge your analysis — and help you knock your next presentation out of the park. This article will be a tutorial on how to create fancy, advanced data visualisations — easily! We’ll be using plotly, a Python library for creating interactive visualisations! Introducing plotly Plotly is an interactive, open-source, and browser-based graphing library for Python! It’s built on top of D3.js, making its visualisation capabilities much more far-ranging and flexible than the standard Matplotlib. There are two main advantages to using Plotly over other Python libraries capable of plotting such as Matplotlib, Seaborn, and Pandas. These are: (1) Ease of use — Creating interactive plots, 3D plots, and other complex graphics is just a few lines away. Doing the same thing in the other plotting libraries takes a lot more work. (2) More capabilities — Since Plotly is built from D3.js, its plotting capabilities are much greater than other plotting libraries. Sun burst charts, candlestick charts, maps, and more are all possible with Plotly. See a full list here. We can install Plotly with a single pip command: pip install plotly==4.0.0 For the rest of this tutorial, we’re going to be creating visualisations of the House Prices dataset which you can grab from Kaggle. Making Fancy Plots with Plotly We can create some pretty fancy plots with Plotly! To start, let’s import plotly and its internal graph objects component. We’ll also import pandas for loading up our dataset import plotly import plotly.graph_objs as go import pandas as pd Reading in our dataset is of course just a one-liner in pandas: data = pd.read_csv('train.csv') Scatter Plots For this exercise, we’re going to plot the SalesPrice vs. YearBuilt in a scatter plot. To do so, we’ll create a plotly Scatter graph object and put it into a trace. trace = go.Scatter( x = data['YearBuilt'], y = data['SalePrice'], mode = 'markers', showlegend = True ) plot_data = [trace] Then, plotting is just a single line away! plotly.offline.plot(plot_data, filename='basic-scatter') The above command will open a new tab in your browser with the plot. Nothing fancy yet…. but just you wait! Graph interactivity comes automatically built-in with Plotly. Check out the Jupyter Notebook to see what it can do! All of the commands are in the top-right of the browser: - Hovering over each point shows the point’s x-y coordinates - You can zoom in on a certain box of the data - You can select and highlight certain points, either with a box or with Lasso - You can pan around the entire plot to get a better look at things - You can download the plot as an image file! Box Plots This time we’ll do a box plot. The process is about the same. We’ll create a graph object, put it into a trace, and then plot it in the browser: import plotly import plotly.graph_objs as go import pandas as pd data = pd.read_csv('train.csv') trace = go.Box( x = data['YearBuilt'], y = data['SalePrice'], marker = {'color': 'green'}, showlegend = True, ) plot_data = [trace] plotly.offline.plot(plot_data, filename='basic-box') Check out the Jupyter Notebook to see some of the fancy Plotly features with box plots! By default, we get the same panning, zooming, and point selection. Since we now have a box plot, hovering over each box will show: - Median - 1st and 3rd quartiles - Min and Max values of the data range - The upper and / or lower fences if there are outliers Heat Maps Heat Maps are another powerful tool in any great Data Scientist’s toolbox. They’re especially effective for showing the relationships between multiple feature variables in one graph as well as the relative importance of each relationship. To really show how your Heat Maps can be enhanced by using Plotly, we’re going to plot the correlation matrix of the House Prices dataset as a heat map. Plotting the correlation matrix of a dataset is a quick and easy way to get an overview of how your feature variables are influencing the target. For plotly, we set the x and y to be the names of the columns, and the z to be the values in the matrix. Plotting it all in our browser is, once again, is a walk in the park. You can try running it yourself using this Jupyter Notebook. import plotly import plotly.graph_objs as go import pandas as pd data = pd.read_csv('train.csv') corrmat = data.corr() trace = go.Heatmap(z=corrmat, x=corrmat.columns.tolist(), y=corrmat.columns.tolist()) plot_data = [trace] plotly.offline.plot(plot_data, filename='basic-heatmap') Heatmaps in Matplotlib can be a bit tricky since you can’t see the exact value of each cell — you can only sort-of kind-of tell from the color. You could write code to make it interactive, but that’s quite the hassle in Matplotlib. Plotly gives us interactivity out of the box, so when we plot a heat map we get a nice intuitive overview, but also have the option to check exact values if needed. The pan-and-zoom functionality of Plotly is also super clean, allowing for an easy way to do more detailed exploration, all from a visual point of view! Related:
https://www.kdnuggets.com/2019/08/advanced-data-visualisation-data-scientists.html
CC-MAIN-2021-04
refinedweb
1,066
63.49
Use ASP.NET Core route-to-code for simple JSON APIs In this post, we explore how you can use route-to-code instead of controllers, and the benefits and drawbacks. When you need to write an API in ASP.NET Core, you’ve traditionally been forced to use ASP.NET Core MVC. While it’s very mature and full-featured, it also runs against the core principles of ASP.NET Core—it’s not lightweight or as efficient as other ASP.NET Core offerings. As a result you’re saddled with using all of a framework, even if you aren’t using a lot of its features. In most cases, you’re doing your logic somewhere else and the execution context (the CRUD actions over HTTP) deserves better. This doesn’t even include the pitfalls of using controllers and action methods. The MVC pattern invites you to abuse controllers with dependencies and bloat, as much as we preach to other developers about the importance of thin controllers. Microsoft is very aware. This week, in the ASP.NET Standup, architect David Fowler mentioned Project Houdini—an effort to help make APIs over MVC more lightweight and performant (more on this at the end of this post). We now have an alternative called “route-to-code.” You can now write ASP.NET Core APIs by connecting routing with your middleware. As a result, your code reads the request, writes the response, and you aren’t reliant on a heavy framework and its advanced configuration. It’s a wonderful pipe-to-pipe experience for simple JSON APIs. To be clear—and Microsoft will be the first to tell you this—it is for basic JSON APIs that don’t need things like model binding, content negotiation, and advanced validation. For those scenarios, ASP.NET Core MVC will always be available to you. Luckily for me, I just wrote a sample API in MVC to look at the HttpRepl tool. This is a great project to use to convert to route-to-code and show my experiences. This post contains the following content. - How does route-to-code work? - A quick tour of the route-to-code MVC project - Migrate our APIs from MVC to route-to-code - The path forward - Wrap up How does route-to-code work? In route-to-code, you specify the APIs in your project’s Startup.cs file. In this file (or even in another one), you define the routing and API logic in an application request’s pipeline in UseEndpoints. To use this, ASP.NET Core gives you three helper methods to use: - ReadFromJsonAsync - reads JSON from the request and deserializes it to a given type - WriteAsJsonAsync - writes a value as JSON to the response body (and also sets the response type to application/json). - HasJsonContentType - a boolean method that checks the Content-Typeheader for JSON Because route-to-code is for basic APIs only, it does not currently support: - Model binding or validation - OpenAPI (Swagger UI) - Constructor dependency injection - Content negotiation There are ways to work around this, as we’ll see, but if you find yourself writing a lot of repetitive code, it’s a good sign that you might be better off leveraging ASP.NET Core MVC. A quick tour of the route-to-code MVC project I’ve got the route-to-code project out on GitHub. I won’t go through all the setup code but will just link to the key parts if you care to explore further. In the sample app, I’ve wired up an in-memory Entity Framework database. I’m using a SampleContext class that uses Entity Framework Core’s DbContext. I’ve got a SeedData class that populates the database with a model using C# 9 records. In the ConfigureServices middleware in Startup.cs, I add the in-memory database to the container, then flip on the switch in Program.cs. Migrate our APIs from MVC to route-to-code In this post, I’ll look at the GET, GET (by id), POST, and DELETE methods in my MVC controller and see what it takes to migrate them to route-to-code. Before we do that, a quick note. In MVC, I’m using constructor injection to access my data from my SampleContext. Because context is a common term in route-to-code, I’ll be naming it repository in route-to-code. Anyway, here’s how the constructor injection looks in the ASP.NET Core MVC project: using HttpReplApi.Data; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using HttpReplApi.ApiModels; namespace HttpReplApi.Controllers { [Produces("application/json")] [Route("[controller]")] public class BandsController : ControllerBase { private readonly SampleContext _context; public BandsController(SampleContext context) { _context = context; } // action methods } } In the following sections, I’ll go through all the endpoints and see what it takes to move to route-to-code. The “get all items” endpoint For a “get all” endpoint, the MVC action method is pretty self-explanatory. Since I’ve injected the context and the data is ready for me to query, I just need to get it. [HttpGet] public ActionResult<IEnumerable<Band>> Get() => _context.Bands.ToList(); As mentioned earlier, all the endpoint routing and logic in route-to-code will be inside of app.UseEndpoints: app.UseEndpoints(endpoints => { // endpoints here }; Now, we can write a MapGet call to define and configure our endpoint. Take a look at this code and we’ll discuss after. endpoints.MapGet("/bands", async context => { var repository = context.RequestServices.GetService<SampleContext>(); var bands = await repository.Bands.ToListAsync(); await context.Response.WriteAsJsonAsync(bands); }); I’m requesting an HTTP GET endpoint with the /bands route template. In this case, the context is HttpContext, where I can request services, get query strings, and read and write JSON. I can’t use constructor-based dependency injection (DI) using route-to-code. Because there’s no framework to inject services into, we need to manually resolve these services. So, from HttpContext.RequestServices, I can call GetService to resolve my SampleContext. For any services with a transient or scoped lifetime, you need to use the RequestServices. For services with singleton scopes, like loggers, you can declare it from the service provider. In those cases, you can use those across different requests. But in our case, we’ll need to repeat the repository service discovery for every endpoint, which is a drag. Finally, I’ll send back the Bands collection as JSON using the Response.WriteAsJsonAsync method. The “get by id” endpoint What about the most common use case—getting an item by id? Here’s how we do it in an MVC controller: [HttpGet("{id}")] public async Task<ActionResult<Band>> GetById(int id) { var band = await _context.Bands.FindAsync(id); if (band is null) { return NotFound(); } return band; } In route-to-code, here’s how it looks: route matches a passed in id from the route. I need to fetch it by accessing it in Request.RouteValues. One note that isn’t in the documentation: because there’s no model binding, I need to manually convert the id string to an integer. After I figured that out, I was able to call FindAsync from my context, validate it, then write it in the WriteAsJsonAsync method. The post endpoint Here’s where things can get interesting—how can we post without model binding or validation? Here’s how the existing controller works in ASP.NET Core MVC. [HttpPost] public async Task<ActionResult<Band>> Create(Band band) { _context.Bands.Add(band); await _context.SaveChangesAsync(); return CreatedAtAction(nameof(GetById), new { id = band.Id }, band); } In route-to-code, here’s what I wrote:); }); As we saw earlier, we have a HasJsonContentType method at our disposal to see if I’m getting JSON. If not, I can set the appropriate status code and return. Since I have JSON (no validation or binding, just verification that it is JSON), I can read it in and save it to the database. Once I’m done, I can either WriteAsJsonAsync to give the caller back the new record, or do something like this: context.Response.StatusCode = StatusCodes.Status201Created; return; The WriteAsJsonAsync will return a 200, and only a 200. Remember, this needs to be done by hand because we don’t have a framework. The delete endpoint For our DELETE API, we’ll see it’s quite similar to POST (we’re just doing the opposite action). Here’s what we do in the traditional MVC controller: [HttpDelete("{id}")] public async Task<IActionResult> Delete(int id) { var band = await _context.Bands.FindAsync(id); if (band is null) { return NotFound(); } _context.Bands.Remove(band); await _context.SaveChangesAsync(); return NoContent(); } Here’s what I wrote in the route-to-code endpoint. endpoints.MapDelete("; } repository.Bands.Remove(band); await repository.SaveChangesAsync(); context.Response.StatusCode = StatusCodes.Status204NoContent; return; }); As you can see, there’s a lot of considerations to make even for ridiculously simple APIs like this one. It’s tough to work around dependency injection if you rely on it in your application. I wish the @aspnet core Map methods supported DI enabled requestDelegates 🥺— Khalid The Fungi 🍄 (@buhakmeh) December 3, 2020 Instead I have to program like a caveman pic.twitter.com/JtjSrkF6yI That’s the price you pay for using a no-framework solution like this one. In return you get simplicity and performance. It’s up to you to decide if you need all the bells and whistles or if you only need route-to-code. The path forward The use case for this is admittedly small, so here’s a thought: what if I could enjoy these benefits in MVC? That’s the impetus behind “Project Houdini”, which David Fowler discussed in this week’s ASP.NET Standup. This effort focuses on pushing MVC productivity features to the core of the stack with an eye on performance. Fowler showed off a way to generate these route-to-code APIs for you at compile time using source generation—allowing you to keep writing the traditional MVC code. Of course, when AOT comes with .NET 6, it’ll benefit from performance and treeshaking capabilities. Wrap up In this post, we discussed the route-to-code API style, and how it can help you write simpler APIs. We looked at how to migrate controller code to route-to-code, and also looked at the path forward.
https://www.daveabrock.com/2020/12/04/migrate-mvc-to-route-to-code/
CC-MAIN-2021-39
refinedweb
1,736
66.03
Using IntelliSense Perhaps one in all the foremost necessary options of Visual Studio is that the IntelliSense. IntelliSense is AN autocompletion tool additionally as a fast reference for categories, methods, and plenty of a lot of. I keep in mind victimisation AN previous IDE for C++ and that i got to learn the mandatory codes I actually have to use. With IntelliSense, I learn as I kind as a result of you really see a quick description of every elements describing the way to use them. IntelliSense is activated the instant you group A letter within the Code Editor. kind the subsequent code within the Main method of the program. System.Console.WriteLine("Welcome to Visual C# Tutorials!"); Typing the primary letter of the statement mechanically activates IntelliSense. IntelliSense offers you a listing of recommendations with the foremost relevant one on the primary of the list. you’ll be able to press tab to simply accept the chosen recommendation. typewriting a dot can bring you another list of recommendations that’s more filtered counting on what you antecedently written. it’s conjointly context-aware because it can solely show suggestions that ar valid within a specific code block. The list within the following example is predicated on all the parts that ar contained within the preceding namespace. If you continue the choice for a brief quantity of your time, the outline concerning the chosen item can show up. this enables you to be told what every item will while not getting to the total documentation. As you kind the code, the list is narrowed down. for instance, typewriting the letter W build IntelliSense to solely show things with W’s in it. Typing more letters will narrow the list even further. If IntelliSense cannot realize one thing that matches what you’re typewriting, then nothing are shown. you’ll be able to press Ctrl while a listing is shown to create the list clear. It’s helpful once the list box is obstructing a section of your code. When operating with strategies with multiple overloads (versions), you’ll be able to navigate victimisation the arrowheads to visualize all the attainable overloads of the tactic. You will conjointly see the various parameters needed by every technique overload and their individual descriptions. Methods, parameters, and technique overloading are going to be mentioned in a very later lesson. IntelliSense is such a magnificent element, and for each release of Visual Studio, IntelliSense turns out to be even a ton of savvy in recommending codes for you. it’s one in everything about efficient apparatuses Visual Studio offers and one in everything about most reasons why you should utilize Visual Studio.
https://compitionpoint.com/intellisense/
CC-MAIN-2021-31
refinedweb
447
54.52
Write a program in C++ to play a mind-reader game sometimes called "Russian Magic Square". Your interface will be text-driven using numbers and letters of the alphabet and will not use graphics. Running your program will look something like what is shown below, where user input is shown in bold: 99:h 98:K 97:b 96:I 95:h 94:z 93:U 92:A 91:C 90:d 89:G 88:h 87:W 86:t 85:C 84:v 83:K 82:h 81:h 80:d 79:O 78:p 77:f 76:x 75:h 74:W 73:Y 72:h 71:W 70:x 69:x 68:l 67:S 66:v 65:t 64:n 63:h 62:M 61:r 60:K 59:b 58:f 57:W 56:n 55:b 54:h 53:h 52:x 51:z 50:x 49:x 48:r 47:U 46:f 45:h 44:f 43:h 42:S 41:S 40:E 39:j 38:x 37:p 36:h 35:G 34:W 33:Q 32:z 31:O 30:z 29:t 28:j 27:h 26:M 25:A 24:A 23:t 22:j 21:n 20:v 19:t 18:h 17:S 16:t 15:r 14:l 13:S 12:O 11:M 10:h 9:h 8:v 7:Y 6:b 5:I 4:t 3:v 2:h 1:A 0:h: h Enter 'r' to repeat or 'x' to exit: r 99:z 98:n 97:d 96:O 95:h 94:K 93:x 92:G 91:C 90:d 89:E 88:p 87:f 86:W 85:Y 84:z 83:A 82:v 81:z 80:l 79:z 78:Q 77:E 76:S 75:W 74:l 73:U 72:z 71:z 70:K 69:K 68:x 67:I 66:W 65:r 64:G 63:z 62:l 61:d 60:I 59:n 58:x 57:W 56:O 55:Y 54:z 53:G 52:W 51:v 50:j 49:O 48:n 47:I 46:U 45:z 44:W 43:Q 42:I 41:S 40:Y 39:n 38:b 37:d 36:z 35:z 34:W 33:r 32:E 31:r 30:O 29:E 28:n 27:z 26:W 25:C 24:S 23:C 22:Q 21:f 20:z 19:z 18:z 17:G 16:C 15:j 14:t 13:n 12:M 11:G 10:C 9:z 8:Y 7:p 6:n 5:z 4:n 3:Q 2:d 1:K 0:z: z Enter 'r' to repeat or 'x' to exit: This was my first project for C++. Basically whenever you subtract any digit from itself (2 digits or more up to 81) it is a multiple of 9. For instance, if you picked 83 and then subtract 83 - 8 - 3 = 72 which is a multiple of 9. When you look at 72 in the first board, this program will 'guess' what you were thinking of. Things you need to know: looping, inputting, outputting, creating a table, and if/else or case/switch statements whichever you prefer. Looks like you're already preoccupied, but if I may be so bold, try a podcast ripper. What a podcast ripper teaches you: Sockets (i.e. network connections and transfers) XML Parsing Binary File Writing (In addition to whatever bells and whistles you add like a GUI interface via MFC, GTK+, Qt, wxWidgets, etc.) Sorry for the long response... here is my source code. Also this code was supposed to be done in C not C++. Good luck. #include <stdio.h> #include <stdlib.h> #include <time.h> int main() { int RandomNumber, TableGenerator, GoingLoopy; char RandomLetters, RetryExit, MindReadingLetter, Continue; srand(time(NULL)); //Seeds a random number using the system time /*Choosing to do a "do-while" loop so I can have at least one run-through before it reaches a condition. It will exit or retry depending on user input*/ do{ //Using 'for' loop to create the table for the numbers and letters for(TableGenerator = 99; TableGenerator >= 0; TableGenerator--) { /*RandomNumber will be getting a random number from 0-25 I will then be adding +1 to it to generate 1-26 I'll also be doing a check to see if it is even or odd to choose whether to generate a lowercase or uppercase ASCII character*/ RandomNumber = rand() % 26 + 1; if(RandomNumber % 2 == 0) RandomLetters = RandomNumber + 64; else if (RandomNumber % 2 == 1) RandomLetters = RandomNumber + 96; /*EXTRA CREDIT: Will be randomly selecting between two 'formulas' to decide which will be the 'mind-reading' letter*/ if(RandomNumber % 2 == 0){ if(TableGenerator / 9 == 11) MindReadingLetter = RandomLetters; } else if(RandomNumber % 2 == 1) if(TableGenerator == 99) MindReadingLetter = RandomLetters; /*This section of the code will print out the actual table and sexy it up if certain conditions aren't met*/ if(TableGenerator < 10) printf(" "); if(TableGenerator % 9 == 0) printf("%d:%c ", TableGenerator, MindReadingLetter); else printf("%d:%c ", TableGenerator, RandomLetters); if(TableGenerator % 10 == 0) printf("\n"); } printf("\n\n1. Choose any two-digit number in the table above (e.g. 73).\n"); printf("2. Subtract its two digits from itself (e.g. 73 - 7 - 3 = 63).\n"); printf("3. Find this new number (e.g. 63) and remember the letter next to it.\n"); printf("4. Now press 'r' and I'll read your mind... "); scanf(" %c", &Continue); /*Bonus part of the code that I had already added in before I was told this was not necessary... If the user does not press 'r' or 'R' he/she will be stuck in an endless oblivion aka loop.*/ if(Continue == 'r' || Continue == 'R') GoingLoopy = 1; else GoingLoopy = 0; while(GoingLoopy == 0){ printf("\nDude...... I said PRESS 'r'... "); scanf(" %c", &Continue); if(Continue == 'r' || Continue == 'R') GoingLoopy = 1; else GoingLoopy = 0; } //The "mind-reading" letter output printf("\n\nI sense you are thinking of: %c\n", MindReadingLetter); printf("Enter 'r' to repeat or 'x' to exit... "); scanf(" %c", &RetryExit); /*Another bonus part of the code that I had already added in before I was told this was not necessary... If the user does not press 'r', 'R', 'x', or 'X' he/she will be stuck in an endless oblivion aka loop */ if(RetryExit == 'r' || RetryExit == 'R' || RetryExit == 'X' || RetryExit == 'x') GoingLoopy = 1; else GoingLoopy = 0; while(GoingLoopy == 0){ printf("\nDude... I said press 'r' to repeat or 'x' to exit... "); scanf(" %c", &RetryExit); if(RetryExit == 'r' || RetryExit == 'R' || RetryExit == 'X' || RetryExit == 'x') GoingLoopy = 1; else GoingLoopy = 0; } printf("\n\n"); }while(RetryExit == 'r' || RetryExit == 'R'); printf("Thanks for playing!!!\n"); return(0); } While it is certainl;y more an intermediate to advanced level project, you might consider going through the Scheme from Scratch process. It not only is a nicely incremental project, meaning that at no one point should you get overwhelmed by it, but it also exposes you to a radically different language which you can compare to C (which always gives some degree of enlightenment).
https://www.daniweb.com/programming/software-development/threads/437220/looking-for-a-project-to-work-on
CC-MAIN-2016-50
refinedweb
1,195
60.69
Hi, On Tue, 25 Sep 2001, F. GEIGER wrote: > I wanted to play around with unittest. I wanted to do that within WingIDE of > course but had to see, that the test cases are not executed in this case: > "Ran 0 tests in 0.000s". If I run the script of question from the console it > tells me "Ran 1 test in...". So what's the difference? Can I configure > WingIDE somehow to "cooperate" with unittest? The problem is that __main__ is not really the same when you run within the Wing debugger, because the wrapper call wingdb.py is __main__. We try to hide this from the debug process but you've uncovered a bug in Wing 1.1b7-2 and earlier where our import hook is not returning the faked __main__ upon __import__('__main__') (which is what unittest.py is doing). There are two ways to work around this for now: 1) Write a small substitute main entry point for your test instead of using the "if __name__ == '__main__'" clause. So in a seperate file you would have: import unittest unittest.main('mytestclasses') or: import unittest import mytestclasses unittest.main(mytestclasses) In this case you are explicitely giving the test modules so you don't run into the __main__ problem. 2) Use wingdbstub and launch the process from the command line. In this case __main__ is correct because there is no difference in what you're launching from the non-debug case. The __import__('__main__') bug should be fixed in the next release. Thanks for reporting this! - Stephan
http://wingware.com/pipermail/wingide-users/2001-September/000839.html
CC-MAIN-2018-05
refinedweb
260
83.86
a few bug fixes, doc changes,1996,1996: Gforth also provides the words @code{?dup-if} and @code{?dup-0=-if}, so 1145: you can avoid using @code{?dup}. Using these alternatives is also more 1146: efficient than using @code{?dup}. Definitions in plain standard Forth 1147: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in 1148: @file{compat/control.fs}. 1149: 1150: @example 1151: @var{n} 1152: CASE 1153: @var{n1} OF @var{code1} ENDOF 1154: @var{n2} OF @var{code2} ENDOF 1155: @dots{} 1156: ENDCASE 1157: @end example 1158: 1159: Executes the first @var{codei}, where the @var{ni} is equal to 1160: @var{n}. A default case can be added by simply writing the code after 1161: the last @code{ENDOF}. It may use @var{n}, which is on top of the stack, 1162: but must not consume it. 1163: 1164: @node Simple Loops, Counted Loops, Selection, Control Structures 1165: @subsection Simple Loops 1166: 1167: @example 1168: BEGIN 1169: @var{code1} 1170: @var{flag} 1171: WHILE 1172: @var{code2} 1173: REPEAT 1174: @end example 1175: 1176: @var{code1} is executed and @var{flag} is computed. If it is true, 1177: @var{code2} is executed and the loop is restarted; If @var{flag} is false, execution continues after the @code{REPEAT}. 1178: 1179: @example 1180: BEGIN 1181: @var{code} 1182: @var{flag} 1183: UNTIL 1184: @end example 1185: 1186: @var{code} is executed. The loop is restarted if @code{flag} is false. 1187: 1188: @example 1189: BEGIN 1190: @var{code} 1191: AGAIN 1192: @end example 1193: 1194: This is an endless loop. 1195: 1196: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures 1197: @subsection Counted Loops 1198: 1199: The basic counted loop is: 1200: @example 1201: @var{limit} @var{start} 1202: ?DO 1203: @var{body} 1204: LOOP 1205: @end example 1206: 1207: This performs one iteration for every integer, starting from @var{start} 1208: and up to, but excluding @var{limit}. The counter, aka index, can be 1209: accessed with @code{i}. E.g., the loop 1210: @example 1211: 10 0 ?DO 1212: i . 1213: LOOP 1214: @end example 1215: prints 1216: @example 1217: 0 1 2 3 4 5 6 7 8 9 1218: @end example 1219: The index of the innermost loop can be accessed with @code{i}, the index 1220: of the next loop with @code{j}, and the index of the third loop with 1221: @code{k}. 1222: 1223: The loop control data are kept on the return stack, so there are some 1224: restrictions on mixing return stack accesses and counted loop 1225: words. E.g., if you put values on the return stack outside the loop, you 1226: cannot read them inside the loop. If you put values on the return stack 1227: within a loop, you have to remove them before the end of the loop and 1228: before accessing the index of the loop. 1229: 1230: There are several variations on the counted loop: 1231: 1232: @code{LEAVE} leaves the innermost counted loop immediately. 1233: 1234: If @var{start} is greater than @var{limit}, a @code{?DO} loop is entered 1235: (and @code{LOOP} iterates until they become equal by wrap-around 1236: arithmetic). This behaviour is usually not what you want. Therefore, 1237: Gforth offers @code{+DO} and @code{U+DO} (as replacements for 1238: @code{?DO}), which do not enter the loop if @var{start} is greater than 1239: @var{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for 1240: unsigned loop parameters. 1241: 1242: @code{LOOP} can be replaced with @code{@var{n} +LOOP}; this updates the 1243: index by @var{n} instead of by 1. The loop is terminated when the border 1244: between @var{limit-1} and @var{limit} is crossed. E.g.: 1245: 1246: @code{4 0 +DO i . 2 +LOOP} prints @code{0 2} 1247: 1248: @code{4 1 +DO i . 2 +LOOP} prints @code{1 3} 1249: 1250: The behaviour of @code{@var{n} +LOOP} is peculiar when @var{n} is negative: 1251: 1252: @code{-1 0 ?DO i . -1 +LOOP} prints @code{0 -1} 1253: 1254: @code{ 0 0 ?DO i . -1 +LOOP} prints nothing 1255: 1256: Therefore we recommend avoiding @code{@var{n} +LOOP} with negative 1257: @var{n}. One alternative is @code{@var{u} -LOOP}, which reduces the 1258: index by @var{u} each iteration. The loop is terminated when the border 1259: between @var{limit+1} and @var{limit} is crossed. Gforth also provides 1260: @code{-DO} and @code{U-DO} for down-counting loops. E.g.: 1261: 1262: @code{-2 0 -DO i . 1 -LOOP} prints @code{0 -1} 1263: 1264: @code{-1 0 -DO i . 1 -LOOP} prints @code{0} 1265: 1266: @code{ 0 0 -DO i . 1 -LOOP} prints nothing 1267: 1268: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and 1269: @code{-LOOP} are not in the ANS Forth standard. However, an 1270: implementation for these words that uses only standard words is provided 1271: in @file{compat/loops.fs}. 1272: 1273: @code{?DO} can also be replaced by @code{DO}. @code{DO} always enters 1274: the loop, independent of the loop parameters. Do not use @code{DO}, even 1275: if you know that the loop is entered in any case. Such knowledge tends 1276: to become invalid during maintenance of a program, and then the 1277: @code{DO} will make trouble. 1278: 1279: @code{UNLOOP} is used to prepare for an abnormal loop exit, e.g., via 1280: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the 1281: return stack so @code{EXIT} can get to its return address. 1282: 1283: Another counted loop is 1284: @example 1285: @var{n} 1286: FOR 1287: @var{body} 1288: NEXT 1289: @end example 1290: This is the preferred loop of native code compiler writers who are too 1291: lazy to optimize @code{?DO} loops properly. In Gforth, this loop 1292: iterates @var{n+1} times; @code{i} produces values starting with @var{n} 1293: and ending with 0. Other Forth systems may behave differently, even if 1294: they support @code{FOR} loops. To avoid problems, don't use @code{FOR} 1295: loops. 1296: 1297: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures 1298: @subsection Arbitrary control structures 1299: 1300: ANS Forth permits and supports using control structures in a non-nested 1301: way. Information about incomplete control structures is stored on the 1302: control-flow stack. This stack may be implemented on the Forth data 1303: stack, and this is what we have done in Gforth. 1304: 1305: An @i{orig} entry represents an unresolved forward branch, a @i{dest} 1306: entry represents a backward branch target. A few words are the basis for 1307: building any control structure possible (except control structures that 1308: need storage, like calls, coroutines, and backtracking). 1309: 1310: doc-if 1311: doc-ahead 1312: doc-then 1313: doc-begin 1314: doc-until 1315: doc-again 1316: doc-cs-pick 1317: doc-cs-roll 1318: 1319: On many systems control-flow stack items take one word, in Gforth they 1320: currently take three (this may change in the future). Therefore it is a 1321: really good idea to manipulate the control flow stack with 1322: @code{cs-pick} and @code{cs-roll}, not with data stack manipulation 1323: words. 1324: 1325: Some standard control structure words are built from these words: 1326: 1327: doc-else 1328: doc-while 1329: doc-repeat 1330: 1331: Gforth adds some more control-structure words: 1332: 1333: doc-endif 1334: doc-?dup-if 1335: doc-?dup-0=-if 1336: 1337: Counted loop words constitute a separate group of words: 1338: 1339: doc-?do 1340: doc-+do 1341: doc-u+do 1342: doc--do 1343: doc-u-do 1344: doc-do 1345: doc-for 1346: doc-loop 1347: doc-+loop 1348: doc--loop 1349: doc-next 1350: doc-leave 1351: doc-?leave 1352: doc-unloop 1353: doc-done 1354: 1355: The standard does not allow using @code{cs-pick} and @code{cs-roll} on 1356: @i{do-sys}. Our system allows it, but it's your job to ensure that for 1357: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path 1358: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the 1359: fall-through path). Also, you have to ensure that all @code{LEAVE}s are 1360: resolved (by using one of the loop-ending words or @code{DONE}). 1361: 1362: Another group of control structure words are 1363: 1364: doc-case 1365: doc-endcase 1366: doc-of 1367: doc-endof 1368: 1369: @i{case-sys} and @i{of-sys} cannot be processed using @code{cs-pick} and 1370: @code{cs-roll}. 1371: 1372: @subsubsection Programming Style 1373: 1374: In order to ensure readability we recommend that you do not create 1375: arbitrary control structures directly, but define new control structure 1376: words for the control structure you want and use these words in your 1377: program. 1378: 1379: E.g., instead of writing 1380: 1381: @example 1382: begin 1383: ... 1384: if [ 1 cs-roll ] 1385: ... 1386: again then 1387: @end example 1388: 1389: we recommend defining control structure words, e.g., 1390: 1391: @example 1392: : while ( dest -- orig dest ) 1393: POSTPONE if 1394: 1 cs-roll ; immediate 1395: 1396: : repeat ( orig dest -- ) 1397: POSTPONE again 1398: POSTPONE then ; immediate 1399: @end example 1400: 1401: and then using these to create the control structure: 1402: 1403: @example 1404: begin 1405: ... 1406: while 1407: ... 1408: repeat 1409: @end example 1410: 1411: That's much easier to read, isn't it? Of course, @code{REPEAT} and 1412: @code{WHILE} are predefined, so in this example it would not be 1413: necessary to define them. 1414: 1415: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures 1416: @subsection Calls and returns 1417: 1418: A definition can be called simply be writing the name of the 1419: definition. When the end of the definition is reached, it returns. An 1420: earlier return can be forced using 1421: 1422: doc-exit 1423: 1424: Don't forget to clean up the return stack and @code{UNLOOP} any 1425: outstanding @code{?DO}...@code{LOOP}s before @code{EXIT}ing. The 1426: primitive compiled by @code{EXIT} is 1427: 1428: doc-;s 1429: 1430: @node Exception Handling, , Calls and returns, Control Structures 1431: @subsection Exception Handling 1432: 1433: doc-catch 1434: doc-throw 1435: 1436: @node Locals, Defining Words, Control Structures, Words 1437: @section Locals 1438: 1439: Local variables can make Forth programming more enjoyable and Forth 1440: programs easier to read. Unfortunately, the locals of ANS Forth are 1441: laden with restrictions. Therefore, we provide not only the ANS Forth 1442: locals wordset, but also our own, more powerful locals wordset (we 1443: implemented the ANS Forth locals wordset through our locals wordset). 1444: 1445: The ideas in this section have also been published in the paper 1446: @cite{Automatic Scoping of Local Variables} by M. Anton Ertl, presented 1447: at EuroForth '94; it is available at 1448: @*@file{}. 1449: 1450: @menu 1451: * Gforth locals:: 1452: * ANS Forth locals:: 1453: @end menu 1454: 1455: @node Gforth locals, ANS Forth locals, Locals, Locals 1456: @subsection Gforth locals 1457: 1458: Locals can be defined with 1459: 1460: @example 1461: @{ local1 local2 ... -- comment @} 1462: @end example 1463: or 1464: @example 1465: @{ local1 local2 ... @} 1466: @end example 1467: 1468: E.g., 1469: @example 1470: : max @{ n1 n2 -- n3 @} 1471: n1 n2 > if 1472: n1 1473: else 1474: n2 1475: endif ; 1476: @end example 1477: 1478: The similarity of locals definitions with stack comments is intended. A 1479: locals definition often replaces the stack comment of a word. The order 1480: of the locals corresponds to the order in a stack comment and everything 1481: after the @code{--} is really a comment. 1482: 1483: This similarity has one disadvantage: It is too easy to confuse locals 1484: declarations with stack comments, causing bugs and making them hard to 1485: find. However, this problem can be avoided by appropriate coding 1486: conventions: Do not use both notations in the same program. If you do, 1487: they should be distinguished using additional means, e.g. by position. 1488: 1489: The name of the local may be preceded by a type specifier, e.g., 1490: @code{F:} for a floating point value: 1491: 1492: @example 1493: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @} 1494: \ complex multiplication 1495: Ar Br f* Ai Bi f* f- 1496: Ar Bi f* Ai Br f* f+ ; 1497: @end example 1498: 1499: Gforth currently supports cells (@code{W:}, @code{W^}), doubles 1500: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters 1501: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined 1502: with @code{W:}, @code{D:} etc.) produces its value and can be changed 1503: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.) 1504: produces its address (which becomes invalid when the variable's scope is 1505: left). E.g., the standard word @code{emit} can be defined in therms of 1506: @code{type} like this: 1507: 1508: @example 1509: : emit @{ C^ char* -- @} 1510: char* 1 type ; 1511: @end example 1512: 1513: A local without type specifier is a @code{W:} local. Both flavours of 1514: locals are initialized with values from the data or FP stack. 1515: 1516: Currently there is no way to define locals with user-defined data 1517: structures, but we are working on it. 1518: 1519: Gforth allows defining locals everywhere in a colon definition. This 1520: poses the following questions: 1521: 1522: @menu 1523: * Where are locals visible by name?:: 1524: * How long do locals live?:: 1525: * Programming Style:: 1526: * Implementation:: 1527: @end menu 1528: 1529: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals 1530: @subsubsection Where are locals visible by name? 1531: 1532: Basically, the answer is that locals are visible where you would expect 1533: it in block-structured languages, and sometimes a little longer. If you 1534: want to restrict the scope of a local, enclose its definition in 1535: @code{SCOPE}...@code{ENDSCOPE}. 1536: 1537: doc-scope 1538: doc-endscope 1539: 1540: These words behave like control structure words, so you can use them 1541: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in 1542: arbitrary ways. 1543: 1544: If you want a more exact answer to the visibility question, here's the 1545: basic principle: A local is visible in all places that can only be 1546: reached through the definition of the local@footnote{In compiler 1547: construction terminology, all places dominated by the definition of the 1548: local.}. In other words, it is not visible in places that can be reached 1549: without going through the definition of the local. E.g., locals defined 1550: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals 1551: defined in @code{BEGIN}...@code{UNTIL} are visible after the 1552: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}). 1553: 1554: The reasoning behind this solution is: We want to have the locals 1555: visible as long as it is meaningful. The user can always make the 1556: visibility shorter by using explicit scoping. In a place that can 1557: only be reached through the definition of a local, the meaning of a 1558: local name is clear. In other places it is not: How is the local 1559: initialized at the control flow path that does not contain the 1560: definition? Which local is meant, if the same name is defined twice in 1561: two independent control flow paths? 1562: 1563: This should be enough detail for nearly all users, so you can skip the 1564: rest of this section. If you relly must know all the gory details and 1565: options, read on. 1566: 1567: In order to implement this rule, the compiler has to know which places 1568: are unreachable. It knows this automatically after @code{AHEAD}, 1569: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after 1570: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the 1571: compiler that the control flow never reaches that place. If 1572: @code{UNREACHABLE} is not used where it could, the only consequence is 1573: that the visibility of some locals is more limited than the rule above 1574: says. If @code{UNREACHABLE} is used where it should not (i.e., if you 1575: lie to the compiler), buggy code will be produced. 1576: 1577: Another problem with this rule is that at @code{BEGIN}, the compiler 1578: does not know which locals will be visible on the incoming 1579: back-edge. All problems discussed in the following are due to this 1580: ignorance of the compiler (we discuss the problems using @code{BEGIN} 1581: loops as examples; the discussion also applies to @code{?DO} and other 1582: loops). Perhaps the most insidious example is: 1583: @example 1584: AHEAD 1585: BEGIN 1586: x 1587: [ 1 CS-ROLL ] THEN 1588: @{ x @} 1589: ... 1590: UNTIL 1591: @end example 1592: 1593: This should be legal according to the visibility rule. The use of 1594: @code{x} can only be reached through the definition; but that appears 1595: textually below the use. 1596: 1597: From this example it is clear that the visibility rules cannot be fully 1598: implemented without major headaches. Our implementation treats common 1599: cases as advertised and the exceptions are treated in a safe way: The 1600: compiler makes a reasonable guess about the locals visible after a 1601: @code{BEGIN}; if it is too pessimistic, the 1602: user will get a spurious error about the local not being defined; if the 1603: compiler is too optimistic, it will notice this later and issue a 1604: warning. In the case above the compiler would complain about @code{x} 1605: being undefined at its use. You can see from the obscure examples in 1606: this section that it takes quite unusual control structures to get the 1607: compiler into trouble, and even then it will often do fine. 1608: 1609: If the @code{BEGIN} is reachable from above, the most optimistic guess 1610: is that all locals visible before the @code{BEGIN} will also be 1611: visible after the @code{BEGIN}. This guess is valid for all loops that 1612: are entered only through the @code{BEGIN}, in particular, for normal 1613: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and 1614: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our 1615: compiler. When the branch to the @code{BEGIN} is finally generated by 1616: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and 1617: warns the user if it was too optimisitic: 1618: @example 1619: IF 1620: @{ x @} 1621: BEGIN 1622: \ x ? 1623: [ 1 cs-roll ] THEN 1624: ... 1625: UNTIL 1626: @end example 1627: 1628: Here, @code{x} lives only until the @code{BEGIN}, but the compiler 1629: optimistically assumes that it lives until the @code{THEN}. It notices 1630: this difference when it compiles the @code{UNTIL} and issues a 1631: warning. The user can avoid the warning, and make sure that @code{x} 1632: is not used in the wrong area by using explicit scoping: 1633: @example 1634: IF 1635: SCOPE 1636: @{ x @} 1637: ENDSCOPE 1638: BEGIN 1639: [ 1 cs-roll ] THEN 1640: ... 1641: UNTIL 1642: @end example 1643: 1644: Since the guess is optimistic, there will be no spurious error messages 1645: about undefined locals. 1646: 1647: If the @code{BEGIN} is not reachable from above (e.g., after 1648: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an 1649: optimistic guess, as the locals visible after the @code{BEGIN} may be 1650: defined later. Therefore, the compiler assumes that no locals are 1651: visible after the @code{BEGIN}. However, the user can use 1652: @code{ASSUME-LIVE} to make the compiler assume that the same locals are 1653: visible at the BEGIN as at the point where the top control-flow stack 1654: item was created. 1655: 1656: doc-assume-live 1657: 1658: E.g., 1659: @example 1660: @{ x @} 1661: AHEAD 1662: ASSUME-LIVE 1663: BEGIN 1664: x 1665: [ 1 CS-ROLL ] THEN 1666: ... 1667: UNTIL 1668: @end example 1669: 1670: Other cases where the locals are defined before the @code{BEGIN} can be 1671: handled by inserting an appropriate @code{CS-ROLL} before the 1672: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation 1673: behind the @code{ASSUME-LIVE}). 1674: 1675: Cases where locals are defined after the @code{BEGIN} (but should be 1676: visible immediately after the @code{BEGIN}) can only be handled by 1677: rearranging the loop. E.g., the ``most insidious'' example above can be 1678: arranged into: 1679: @example 1680: BEGIN 1681: @{ x @} 1682: ... 0= 1683: WHILE 1684: x 1685: REPEAT 1686: @end example 1687: 1688: @node How long do locals live?, Programming Style, Where are locals visible by name?, Gforth locals 1689: @subsubsection How long do locals live? 1690: 1691: The right answer for the lifetime question would be: A local lives at 1692: least as long as it can be accessed. For a value-flavoured local this 1693: means: until the end of its visibility. However, a variable-flavoured 1694: local could be accessed through its address far beyond its visibility 1695: scope. Ultimately, this would mean that such locals would have to be 1696: garbage collected. Since this entails un-Forth-like implementation 1697: complexities, I adopted the same cowardly solution as some other 1698: languages (e.g., C): The local lives only as long as it is visible; 1699: afterwards its address is invalid (and programs that access it 1700: afterwards are erroneous). 1701: 1702: @node Programming Style, Implementation, How long do locals live?, Gforth locals 1703: @subsubsection Programming Style 1704: 1705: The freedom to define locals anywhere has the potential to change 1706: programming styles dramatically. In particular, the need to use the 1707: return stack for intermediate storage vanishes. Moreover, all stack 1708: manipulations (except @code{PICK}s and @code{ROLL}s with run-time 1709: determined arguments) can be eliminated: If the stack items are in the 1710: wrong order, just write a locals definition for all of them; then 1711: write the items in the order you want. 1712: 1713: This seems a little far-fetched and eliminating stack manipulations is 1714: unlikely to become a conscious programming objective. Still, the number 1715: of stack manipulations will be reduced dramatically if local variables 1716: are used liberally (e.g., compare @code{max} in @ref{Gforth locals} with 1717: a traditional implementation of @code{max}). 1718: 1719: This shows one potential benefit of locals: making Forth programs more 1720: readable. Of course, this benefit will only be realized if the 1721: programmers continue to honour the principle of factoring instead of 1722: using the added latitude to make the words longer. 1723: 1724: Using @code{TO} can and should be avoided. Without @code{TO}, 1725: every value-flavoured local has only a single assignment and many 1726: advantages of functional languages apply to Forth. I.e., programs are 1727: easier to analyse, to optimize and to read: It is clear from the 1728: definition what the local stands for, it does not turn into something 1729: different later. 1730: 1731: E.g., a definition using @code{TO} might look like this: 1732: @example 1733: : strcmp @{ addr1 u1 addr2 u2 -- n @} 1734: u1 u2 min 0 1735: ?do 1736: addr1 c@ addr2 c@ - 1737: ?dup-if 1738: unloop exit 1739: then 1740: addr1 char+ TO addr1 1741: addr2 char+ TO addr2 1742: loop 1743: u1 u2 - ; 1744: @end example 1745: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at 1746: every loop iteration. @code{strcmp} is a typical example of the 1747: readability problems of using @code{TO}. When you start reading 1748: @code{strcmp}, you think that @code{addr1} refers to the start of the 1749: string. Only near the end of the loop you realize that it is something 1750: else. 1751: 1752: This can be avoided by defining two locals at the start of the loop that 1753: are initialized with the right value for the current iteration. 1754: @example 1755: : strcmp @{ addr1 u1 addr2 u2 -- n @} 1756: addr1 addr2 1757: u1 u2 min 0 1758: ?do @{ s1 s2 @} 1759: s1 c@ s2 c@ - 1760: ?dup-if 1761: unloop exit 1762: then 1763: s1 char+ s2 char+ 1764: loop 1765: 2drop 1766: u1 u2 - ; 1767: @end example 1768: Here it is clear from the start that @code{s1} has a different value 1769: in every loop iteration. 1770: 1771: @node Implementation, , Programming Style, Gforth locals 1772: @subsubsection Implementation 1773: 1774: Gforth uses an extra locals stack. The most compelling reason for 1775: this is that the return stack is not float-aligned; using an extra stack 1776: also eliminates the problems and restrictions of using the return stack 1777: as locals stack. Like the other stacks, the locals stack grows toward 1778: lower addresses. A few primitives allow an efficient implementation: 1779: 1780: doc-@local# 1781: doc-f@local# 1782: doc-laddr# 1783: doc-lp+!# 1784: doc-lp! 1785: doc->l 1786: doc-f>l 1787: 1788: In addition to these primitives, some specializations of these 1789: primitives for commonly occurring inline arguments are provided for 1790: efficiency reasons, e.g., @code{@@local0} as specialization of 1791: @code{@@local#} for the inline argument 0. The following compiling words 1792: compile the right specialized version, or the general version, as 1793: appropriate: 1794: 1795: doc-compile-@local 1796: doc-compile-f@local 1797: doc-compile-lp+! 1798: 1799: Combinations of conditional branches and @code{lp+!#} like 1800: @code{?branch-lp+!#} (the locals pointer is only changed if the branch 1801: is taken) are provided for efficiency and correctness in loops. 1802: 1803: A special area in the dictionary space is reserved for keeping the 1804: local variable names. @code{@{} switches the dictionary pointer to this 1805: area and @code{@}} switches it back and generates the locals 1806: initializing code. @code{W:} etc.@ are normal defining words. This 1807: special area is cleared at the start of every colon definition. 1808: 1809: A special feature of Gforth's dictionary is used to implement the 1810: definition of locals without type specifiers: every wordlist (aka 1811: vocabulary) has its own methods for searching 1812: etc. (@pxref{Wordlists}). For the present purpose we defined a wordlist 1813: with a special search method: When it is searched for a word, it 1814: actually creates that word using @code{W:}. @code{@{} changes the search 1815: order to first search the wordlist containing @code{@}}, @code{W:} etc., 1816: and then the wordlist for defining locals without type specifiers. 1817: 1818: The lifetime rules support a stack discipline within a colon 1819: definition: The lifetime of a local is either nested with other locals 1820: lifetimes or it does not overlap them. 1821: 1822: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack 1823: pointer manipulation is generated. Between control structure words 1824: locals definitions can push locals onto the locals stack. @code{AGAIN} 1825: is the simplest of the other three control flow words. It has to 1826: restore the locals stack depth of the corresponding @code{BEGIN} 1827: before branching. The code looks like this: 1828: @format 1829: @code{lp+!#} current-locals-size @minus{} dest-locals-size 1830: @code{branch} <begin> 1831: @end format 1832: 1833: @code{UNTIL} is a little more complicated: If it branches back, it 1834: must adjust the stack just like @code{AGAIN}. But if it falls through, 1835: the locals stack must not be changed. The compiler generates the 1836: following code: 1837: @format 1838: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size 1839: @end format 1840: The locals stack pointer is only adjusted if the branch is taken. 1841: 1842: @code{THEN} can produce somewhat inefficient code: 1843: @format 1844: @code{lp+!#} current-locals-size @minus{} orig-locals-size 1845: <orig target>: 1846: @code{lp+!#} orig-locals-size @minus{} new-locals-size 1847: @end format 1848: The second @code{lp+!#} adjusts the locals stack pointer from the 1849: level at the @var{orig} point to the level after the @code{THEN}. The 1850: first @code{lp+!#} adjusts the locals stack pointer from the current 1851: level to the level at the orig point, so the complete effect is an 1852: adjustment from the current level to the right level after the 1853: @code{THEN}. 1854: 1855: In a conventional Forth implementation a dest control-flow stack entry 1856: is just the target address and an orig entry is just the address to be 1857: patched. Our locals implementation adds a wordlist to every orig or dest 1858: item. It is the list of locals visible (or assumed visible) at the point 1859: described by the entry. Our implementation also adds a tag to identify 1860: the kind of entry, in particular to differentiate between live and dead 1861: (reachable and unreachable) orig entries. 1862: 1863: A few unusual operations have to be performed on locals wordlists: 1864: 1865: doc-common-list 1866: doc-sub-list? 1867: doc-list-size 1868: 1869: Several features of our locals wordlist implementation make these 1870: operations easy to implement: The locals wordlists are organised as 1871: linked lists; the tails of these lists are shared, if the lists 1872: contain some of the same locals; and the address of a name is greater 1873: than the address of the names behind it in the list. 1874: 1875: Another important implementation detail is the variable 1876: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to 1877: determine if they can be reached directly or only through the branch 1878: that they resolve. @code{dead-code} is set by @code{UNREACHABLE}, 1879: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon 1880: definition, by @code{BEGIN} and usually by @code{THEN}. 1881: 1882: Counted loops are similar to other loops in most respects, but 1883: @code{LEAVE} requires special attention: It performs basically the same 1884: service as @code{AHEAD}, but it does not create a control-flow stack 1885: entry. Therefore the information has to be stored elsewhere; 1886: traditionally, the information was stored in the target fields of the 1887: branches created by the @code{LEAVE}s, by organizing these fields into a 1888: linked list. Unfortunately, this clever trick does not provide enough 1889: space for storing our extended control flow information. Therefore, we 1890: introduce another stack, the leave stack. It contains the control-flow 1891: stack entries for all unresolved @code{LEAVE}s. 1892: 1893: Local names are kept until the end of the colon definition, even if 1894: they are no longer visible in any control-flow path. In a few cases 1895: this may lead to increased space needs for the locals name area, but 1896: usually less than reclaiming this space would cost in code size. 1897: 1898: 1899: @node ANS Forth locals, , Gforth locals, Locals 1900: @subsection ANS Forth locals 1901: 1902: The ANS Forth locals wordset does not define a syntax for locals, but 1903: words that make it possible to define various syntaxes. One of the 1904: possible syntaxes is a subset of the syntax we used in the Gforth locals 1905: wordset, i.e.: 1906: 1907: @example 1908: @{ local1 local2 ... -- comment @} 1909: @end example 1910: or 1911: @example 1912: @{ local1 local2 ... @} 1913: @end example 1914: 1915: The order of the locals corresponds to the order in a stack comment. The 1916: restrictions are: 1917: 1918: @itemize @bullet 1919: @item 1920: Locals can only be cell-sized values (no type specifiers are allowed). 1921: @item 1922: Locals can be defined only outside control structures. 1923: @item 1924: Locals can interfere with explicit usage of the return stack. For the 1925: exact (and long) rules, see the standard. If you don't use return stack 1926: accessing words in a definition using locals, you will be all right. The 1927: purpose of this rule is to make locals implementation on the return 1928: stack easier. 1929: @item 1930: The whole definition must be in one line. 1931: @end itemize 1932: 1933: Locals defined in this way behave like @code{VALUE}s 1934: (@xref{Values}). I.e., they are initialized from the stack. Using their 1935: name produces their value. Their value can be changed using @code{TO}. 1936: 1937: Since this syntax is supported by Gforth directly, you need not do 1938: anything to use it. If you want to port a program using this syntax to 1939: another ANS Forth system, use @file{compat/anslocal.fs} to implement the 1940: syntax on the other system. 1941: 1942: Note that a syntax shown in the standard, section A.13 looks 1943: similar, but is quite different in having the order of locals 1944: reversed. Beware! 1945: 1946: The ANS Forth locals wordset itself consists of the following word 1947: 1948: doc-(local) 1949: 1950: The ANS Forth locals extension wordset defines a syntax, but it is so 1951: awful that we strongly recommend not to use it. We have implemented this 1952: syntax to make porting to Gforth easy, but do not document it here. The 1953: problem with this syntax is that the locals are defined in an order 1954: reversed with respect to the standard stack comment notation, making 1955: programs harder to read, and easier to misread and miswrite. The only 1956: merit of this syntax is that it is easy to implement using the ANS Forth 1957: locals wordset. 1958: 1959: @node Defining Words, Wordlists, Locals, Words 1960: @section Defining Words 1961: 1962: @menu 1963: * Values:: 1964: @end menu 1965: 1966: @node Values, , Defining Words, Defining Words 1967: @subsection Values 1968: 1969: @node Wordlists, Files, Defining Words, Words 1970: @section Wordlists 1971: 1972: @node Files, Blocks, Wordlists, Words 1973: @section Files 1974: 1975: @node Blocks, Other I/O, Files, Words 1976: @section Blocks 1977: 1978: @node Other I/O, Programming Tools, Blocks, Words 1979: @section Other I/O 1980: 1981: @node Programming Tools, Assembler and Code words, Other I/O, Words 1982: @section Programming Tools 1983: 1984: @menu 1985: * Debugging:: Simple and quick. 1986: * Assertions:: Making your programs self-checking. 1987: @end menu 1988: 1989: @node Debugging, Assertions, Programming Tools, Programming Tools 1990: @subsection Debugging 1991: 1992: The simple debugging aids provided in @file{debugging.fs} 1993: are meant to support a different style of debugging than the 1994: tracing/stepping debuggers used in languages with long turn-around 1995: times. 1996: 1997: A much better (faster) way in fast-compilig languages is to add 1998: printing code at well-selected places, let the program run, look at 1999: the output, see where things went wrong, add more printing code, etc., 2000: until the bug is found. 2001: 2002: The word @code{~~} is easy to insert. It just prints debugging 2003: information (by default the source location and the stack contents). It 2004: is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to 2005: query-replace them with nothing). The deferred words 2006: @code{printdebugdata} and @code{printdebugline} control the output of 2007: @code{~~}. The default source location output format works well with 2008: Emacs' compilation mode, so you can step through the program at the 2009: source level using @kbd{C-x `} (the advantage over a stepping debugger 2010: is that you can step in any direction and you know where the crash has 2011: happened or where the strange data has occurred). 2012: 2013: Note that the default actions clobber the contents of the pictured 2014: numeric output string, so you should not use @code{~~}, e.g., between 2015: @code{<#} and @code{#>}. 2016: 2017: doc-~~ 2018: doc-printdebugdata 2019: doc-printdebugline 2020: 2021: @node Assertions, , Debugging, Programming Tools 2022: @subsection Assertions 2023: 2024: It is a good idea to make your programs self-checking, in particular, if 2025: you use an assumption (e.g., that a certain field of a data structure is 2026: never zero) that may become wrong during maintenance. Gforth supports 2027: assertions for this purpose. They are used like this: 2028: 2029: @example 2030: assert( @var{flag} ) 2031: @end example 2032: 2033: The code between @code{assert(} and @code{)} should compute a flag, that 2034: should be true if everything is alright and false otherwise. It should 2035: not change anything else on the stack. The overall stack effect of the 2036: assertion is @code{( -- )}. E.g. 2037: 2038: @example 2039: assert( 1 1 + 2 = ) \ what we learn in school 2040: assert( dup 0<> ) \ assert that the top of stack is not zero 2041: assert( false ) \ this code should not be reached 2042: @end example 2043: 2044: The need for assertions is different at different times. During 2045: debugging, we want more checking, in production we sometimes care more 2046: for speed. Therefore, assertions can be turned off, i.e., the assertion 2047: becomes a comment. Depending on the importance of an assertion and the 2048: time it takes to check it, you may want to turn off some assertions and 2049: keep others turned on. Gforth provides several levels of assertions for 2050: this purpose: 2051: 2052: doc-assert0( 2053: doc-assert1( 2054: doc-assert2( 2055: doc-assert3( 2056: doc-assert( 2057: doc-) 2058: 2059: @code{Assert(} is the same as @code{assert1(}. The variable 2060: @code{assert-level} specifies the highest assertions that are turned 2061: on. I.e., at the default @code{assert-level} of one, @code{assert0(} and 2062: @code{assert1(} assertions perform checking, while @code{assert2(} and 2063: @code{assert3(} assertions are treated as comments. 2064: 2065: Note that the @code{assert-level} is evaluated at compile-time, not at 2066: run-time. I.e., you cannot turn assertions on or off at run-time, you 2067: have to set the @code{assert-level} appropriately before compiling a 2068: piece of code. You can compile several pieces of code at several 2069: @code{assert-level}s (e.g., a trusted library at level 1 and newly 2070: written code at level 3). 2071: 2072: doc-assert-level 2073: 2074: If an assertion fails, a message compatible with Emacs' compilation mode 2075: is produced and the execution is aborted (currently with @code{ABORT"}. 2076: If there is interest, we will introduce a special throw code. But if you 2077: intend to @code{catch} a specific condition, using @code{throw} is 2078: probably more appropriate than an assertion). 2079: 2080: @node Assembler and Code words, Threading Words, Programming Tools, Words 2081: @section Assembler and Code words 2082: 2083: Gforth provides some words for defining primitives (words written in 2084: machine code), and for defining the the machine-code equivalent of 2085: @code{DOES>}-based defining words. However, the machine-independent 2086: nature of Gforth poses a few problems: First of all. Gforth runs on 2087: several architectures, so it can provide no standard assembler. What's 2088: worse is that the register allocation not only depends on the processor, 2089: but also on the @code{gcc} version and options used. 2090: 2091: The words that Gforth offers encapsulate some system dependences (e.g., the 2092: header structure), so a system-independent assembler may be used in 2093: Gforth. If you do not have an assembler, you can compile machine code 2094: directly with @code{,} and @code{c,}. 2095: 2096: doc-assembler 2097: doc-code 2098: doc-end-code 2099: doc-;code 2100: doc-flush-icache 2101: 2102: If @code{flush-icache} does not work correctly, @code{code} words 2103: etc. will not work (reliably), either. 2104: 2105: These words are rarely used. Therefore they reside in @code{code.fs}, 2106: which is usually not loaded (except @code{flush-icache}, which is always 2107: present). You can load them with @code{require code.fs}. 2108: 2109: In the assembly code you will want to refer to the inner interpreter's 2110: registers (e.g., the data stack pointer) and you may want to use other 2111: registers for temporary storage. Unfortunately, the register allocation 2112: is installation-dependent. 2113: 2114: The easiest solution is to use explicit register declarations 2115: (@pxref{Explicit Reg Vars, , Variables in Specified Registers, gcc.info, 2116: GNU C Manual}) for all of the inner interpreter's registers: You have to 2117: compile Gforth with @code{-DFORCE_REG} (configure option 2118: @code{--enable-force-reg}) and the appropriate declarations must be 2119: present in the @code{machine.h} file (see @code{mips.h} for an example; 2120: you can find a full list of all declarable register symbols with 2121: @code{grep register engine.c}). If you give explicit registers to all 2122: variables that are declared at the beginning of @code{engine()}, you 2123: should be able to use the other caller-saved registers for temporary 2124: storage. Alternatively, you can use the @code{gcc} option 2125: @code{-ffixed-REG} (@pxref{Code Gen Options, , Options for Code 2126: Generation Conventions, gcc.info, GNU C Manual}) to reserve a register 2127: (however, this restriction on register allocation may slow Gforth 2128: significantly). 2129: 2130: If this solution is not viable (e.g., because @code{gcc} does not allow 2131: you to explicitly declare all the registers you need), you have to find 2132: out by looking at the code where the inner interpreter's registers 2133: reside and which registers can be used for temporary storage. You can 2134: get an assembly listing of the engine's code with @code{make engine.s}. 2135: 2136: In any case, it is good practice to abstract your assembly code from the 2137: actual register allocation. E.g., if the data stack pointer resides in 2138: register @code{$17}, create an alias for this register called @code{sp}, 2139: and use that in your assembly code. 2140: 2141: Another option for implementing normal and defining words efficiently 2142: is: adding the wanted functionality to the source of Gforth. For normal 2143: words you just have to edit @file{primitives}, defining words (for fast 2144: defined words) may require changes in @file{engine.c}, 2145: @file{kernal.fs}, @file{prims2x.fs}, and possibly @file{cross.fs}. 2146: 2147: 2148: @node Threading Words, , Assembler and Code words, Words 2149: @section Threading Words 2150: 2151: These words provide access to code addresses and other threading stuff 2152: in Gforth (and, possibly, other interpretive Forths). It more or less 2153: abstracts away the differences between direct and indirect threading 2154: (and, for direct threading, the machine dependences). However, at 2155: present this wordset is still inclomplete. It is also pretty low-level; 2156: some day it will hopefully be made unnecessary by an internals words set 2157: that abstracts implementation details away completely. 2158: 2159: doc->code-address 2160: doc->does-code 2161: doc-code-address! 2162: doc-does-code! 2163: doc-does-handler! 2164: doc-/does-handler 2165: 2166: The code addresses produced by various defining words are produced by 2167: the following words: 2168: 2169: doc-docol: 2170: doc-docon: 2171: doc-dovar: 2172: doc-douser: 2173: doc-dodefer: 2174: doc-dofield: 2175: 2176: Currently there is no installation-independent way for recogizing words 2177: defined by a @code{CREATE}...@code{DOES>} word; however, once you know 2178: that a word is defined by a @code{CREATE}...@code{DOES>} word, you can 2179: use @code{>DOES-CODE}. 2180: 2181: @node ANS conformance, Model, Words, Top 2182: @chapter ANS conformance 2183: 2184: To the best of our knowledge, Gforth is an 2185: 2186: ANS Forth System 2187: @itemize 2188: @item providing the Core Extensions word set 2189: @item providing the Block word set 2190: @item providing the Block Extensions word set 2191: @item providing the Double-Number word set 2192: @item providing the Double-Number Extensions word set 2193: @item providing the Exception word set 2194: @item providing the Exception Extensions word set 2195: @item providing the Facility word set 2196: @item providing @code{MS} and @code{TIME&DATE} from the Facility Extensions word set 2197: @item providing the File Access word set 2198: @item providing the File Access Extensions word set 2199: @item providing the Floating-Point word set 2200: @item providing the Floating-Point Extensions word set 2201: @item providing the Locals word set 2202: @item providing the Locals Extensions word set 2203: @item providing the Memory-Allocation word set 2204: @item providing the Memory-Allocation Extensions word set (that one's easy) 2205: @item providing the Programming-Tools word set 2206: @item providing @code{;code}, @code{AHEAD}, @code{ASSEMBLER}, @code{BYE}, @code{CODE}, @code{CS-PICK}, @code{CS-ROLL}, @code{STATE}, @code{[ELSE]}, @code{[IF]}, @code{[THEN]} from the Programming-Tools Extensions word set 2207: @item providing the Search-Order word set 2208: @item providing the Search-Order Extensions word set 2209: @item providing the String word set 2210: @item providing the String Extensions word set (another easy one) 2211: @end itemize 2212: 2213: In addition, ANS Forth systems are required to document certain 2214: implementation choices. This chapter tries to meet these 2215: requirements. In many cases it gives a way to ask the system for the 2216: information instead of providing the information directly, in 2217: particular, if the information depends on the processor, the operating 2218: system or the installation options chosen, or if they are likely to 2219: change during the maintenance of Gforth. 2220: 2221: @comment The framework for the rest has been taken from pfe. 2222: 2223: @menu 2224: * The Core Words:: 2225: * The optional Block word set:: 2226: * The optional Double Number word set:: 2227: * The optional Exception word set:: 2228: * The optional Facility word set:: 2229: * The optional File-Access word set:: 2230: * The optional Floating-Point word set:: 2231: * The optional Locals word set:: 2232: * The optional Memory-Allocation word set:: 2233: * The optional Programming-Tools word set:: 2234: * The optional Search-Order word set:: 2235: @end menu 2236: 2237: 2238: @c ===================================================================== 2239: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance 2240: @comment node-name, next, previous, up 2241: @section The Core Words 2242: @c ===================================================================== 2243: 2244: @menu 2245: * core-idef:: Implementation Defined Options 2246: * core-ambcond:: Ambiguous Conditions 2247: * core-other:: Other System Documentation 2248: @end menu 2249: 2250: @c --------------------------------------------------------------------- 2251: @node core-idef, core-ambcond, The Core Words, The Core Words 2252: @subsection Implementation Defined Options 2253: @c --------------------------------------------------------------------- 2254: 2255: @table @i 2256: 2257: @item (Cell) aligned addresses: 2258: processor-dependent. Gforth's alignment words perform natural alignment 2259: (e.g., an address aligned for a datum of size 8 is divisible by 2260: 8). Unaligned accesses usually result in a @code{-23 THROW}. 2261: 2262: @item @code{EMIT} and non-graphic characters: 2263: The character is output using the C library function (actually, macro) 2264: @code{putchar}. 2265: 2266: @item character editing of @code{ACCEPT} and @code{EXPECT}: 2267: This is modeled on the GNU readline library (@pxref{Readline 2268: Interaction, , Command Line Editing, readline, The GNU Readline 2269: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by 2270: producing a full word completion every time you type it (instead of 2271: producing the common prefix of all completions). 2272: 2273: @item character set: 2274: The character set of your computer and display device. Gforth is 2275: 8-bit-clean (but some other component in your system may make trouble). 2276: 2277: @item Character-aligned address requirements: 2278: installation-dependent. Currently a character is represented by a C 2279: @code{unsigned char}; in the future we might switch to @code{wchar_t} 2280: (Comments on that requested). 2281: 2282: @item character-set extensions and matching of names: 2283: Any character except the ASCII NUL charcter can be used in a 2284: name. Matching is case-insensitive. The matching is performed using the 2285: C function @code{strncasecmp}, whose function is probably influenced by 2286: the locale. E.g., the @code{C} locale does not know about accents and 2287: umlauts, so they are matched case-sensitively in that locale. For 2288: portability reasons it is best to write programs such that they work in 2289: the @code{C} locale. Then one can use libraries written by a Polish 2290: programmer (who might use words containing ISO Latin-2 encoded 2291: characters) and by a French programmer (ISO Latin-1) in the same program 2292: (of course, @code{WORDS} will produce funny results for some of the 2293: words (which ones, depends on the font you are using)). Also, the locale 2294: you prefer may not be available in other operating systems. Hopefully, 2295: Unicode will solve these problems one day. 2296: 2297: @item conditions under which control characters match a space delimiter: 2298: If @code{WORD} is called with the space character as a delimiter, all 2299: white-space characters (as identified by the C macro @code{isspace()}) 2300: are delimiters. @code{PARSE}, on the other hand, treats space like other 2301: delimiters. @code{PARSE-WORD} treats space like @code{WORD}, but behaves 2302: like @code{PARSE} otherwise. @code{(NAME)}, which is used by the outer 2303: interpreter (aka text interpreter) by default, treats all white-space 2304: characters as delimiters. 2305: 2306: @item format of the control flow stack: 2307: The data stack is used as control flow stack. The size of a control flow 2308: stack item in cells is given by the constant @code{cs-item-size}. At the 2309: time of this writing, an item consists of a (pointer to a) locals list 2310: (third), an address in the code (second), and a tag for identifying the 2311: item (TOS). The following tags are used: @code{defstart}, 2312: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest}, 2313: @code{scopestart}. 2314: 2315: @item conversion of digits > 35 2316: The characters @code{[\]^_'} are the digits with the decimal value 2317: 36@minus{}41. There is no way to input many of the larger digits. 2318: 2319: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}: 2320: The cursor is moved to the end of the entered string. If the input is 2321: terminated using the @kbd{Return} key, a space is typed. 2322: 2323: @item exception abort sequence of @code{ABORT"}: 2324: The error string is stored into the variable @code{"error} and a 2325: @code{-2 throw} is performed. 2326: 2327: @item input line terminator: 2328: For interactive input, @kbd{C-m} and @kbd{C-j} terminate lines. One of 2329: these characters is typically produced when you type the @kbd{Enter} or 2330: @kbd{Return} key. 2331: 2332: @item maximum size of a counted string: 2333: @code{s" /counted-string" environment? drop .}. Currently 255 characters 2334: on all ports, but this may change. 2335: 2336: @item maximum size of a parsed string: 2337: Given by the constant @code{/line}. Currently 255 characters. 2338: 2339: @item maximum size of a definition name, in characters: 2340: 31 2341: 2342: @item maximum string length for @code{ENVIRONMENT?}, in characters: 2343: 31 2344: 2345: @item method of selecting the user input device: 2346: The user input device is the standard input. There is currently no way to 2347: change it from within Gforth. However, the input can typically be 2348: redirected in the command line that starts Gforth. 2349: 2350: @item method of selecting the user output device: 2351: The user output device is the standard output. It cannot be redirected 2352: from within Gforth, but typically from the command line that starts 2353: Gforth. Gforth uses buffered output, so output on a terminal does not 2354: become visible before the next newline or buffer overflow. Output on 2355: non-terminals is invisible until the buffer overflows. 2356: 2357: @item methods of dictionary compilation: 2358: What are we expected to document here? 2359: 2360: @item number of bits in one address unit: 2361: @code{s" address-units-bits" environment? drop .}. 8 in all current 2362: ports. 2363: 2364: @item number representation and arithmetic: 2365: Processor-dependent. Binary two's complement on all current ports. 2366: 2367: @item ranges for integer types: 2368: Installation-dependent. Make environmental queries for @code{MAX-N}, 2369: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for 2370: unsigned (and positive) types is 0. The lower bound for signed types on 2371: two's complement and one's complement machines machines can be computed 2372: by adding 1 to the upper bound. 2373: 2374: @item read-only data space regions: 2375: The whole Forth data space is writable. 2376: 2377: @item size of buffer at @code{WORD}: 2378: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is 2379: shared with the pictured numeric output string. If overwriting 2380: @code{PAD} is acceptable, it is as large as the remaining dictionary 2381: space, although only as much can be sensibly used as fits in a counted 2382: string. 2383: 2384: @item size of one cell in address units: 2385: @code{1 cells .}. 2386: 2387: @item size of one character in address units: 2388: @code{1 chars .}. 1 on all current ports. 2389: 2390: @item size of the keyboard terminal buffer: 2391: Varies. You can determine the size at a specific time using @code{lp@ 2392: tib - .}. It is shared with the locals stack and TIBs of files that 2393: include the current file. You can change the amount of space for TIBs 2394: and locals stack at Gforth startup with the command line option 2395: @code{-l}. 2396: 2397: @item size of the pictured numeric output buffer: 2398: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is 2399: shared with @code{WORD}. 2400: 2401: @item size of the scratch area returned by @code{PAD}: 2402: The remainder of dictionary space. You can even use the unused part of 2403: the data stack space. The current size can be computed with @code{sp@ 2404: pad - .}. 2405: 2406: @item system case-sensitivity characteristics: 2407: Dictionary searches are case insensitive. However, as explained above 2408: under @i{character-set extensions}, the matching for non-ASCII 2409: characters is determined by the locale you are using. In the default 2410: @code{C} locale all non-ASCII characters are matched case-sensitively. 2411: 2412: @item system prompt: 2413: @code{ ok} in interpret state, @code{ compiled} in compile state. 2414: 2415: @item division rounding: 2416: installation dependent. @code{s" floored" environment? drop .}. We leave 2417: the choice to @code{gcc} (what to use for @code{/}) and to you (whether to use 2418: @code{fm/mod}, @code{sm/rem} or simply @code{/}). 2419: 2420: @item values of @code{STATE} when true: 2421: -1. 2422: 2423: @item values returned after arithmetic overflow: 2424: On two's complement machines, arithmetic is performed modulo 2425: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double 2426: arithmetic (with appropriate mapping for signed types). Division by zero 2427: typically results in a @code{-55 throw} (floatingpoint unidentified 2428: fault), although a @code{-10 throw} (divide by zero) would be more 2429: appropriate. 2430: 2431: @item whether the current definition can be found after @t{DOES>}: 2432: No. 2433: 2434: @end table 2435: 2436: @c --------------------------------------------------------------------- 2437: @node core-ambcond, core-other, core-idef, The Core Words 2438: @subsection Ambiguous conditions 2439: @c --------------------------------------------------------------------- 2440: 2441: @table @i 2442: 2443: @item a name is neither a word nor a number: 2444: @code{-13 throw} (Undefined word) 2445: 2446: @item a definition name exceeds the maximum length allowed: 2447: @code{-19 throw} (Word name too long) 2448: 2449: @item addressing a region not inside the various data spaces of the forth system: 2450: The stacks, code space and name space are accessible. Machine code space is 2451: typically readable. Accessing other addresses gives results dependent on 2452: the operating system. On decent systems: @code{-9 throw} (Invalid memory 2453: address). 2454: 2455: @item argument type incompatible with parameter: 2456: This is usually not caught. Some words perform checks, e.g., the control 2457: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type 2458: mismatch). 2459: 2460: @item attempting to obtain the execution token of a word with undefined execution semantics: 2461: You get an execution token representing the compilation semantics 2462: instead. 2463: 2464: @item dividing by zero: 2465: typically results in a @code{-55 throw} (floating point unidentified 2466: fault), although a @code{-10 throw} (divide by zero) would be more 2467: appropriate. 2468: 2469: @item insufficient data stack or return stack space: 2470: Not checked. This typically results in mysterious illegal memory 2471: accesses, producing @code{-9 throw} (Invalid memory address) or 2472: @code{-23 throw} (Address alignment exception). 2473: 2474: @item insufficient space for loop control parameters: 2475: like other return stack overflows. 2476: 2477: @item insufficient space in the dictionary: 2478: Not checked. Similar results as stack overflows. However, typically the 2479: error appears at a different place when one inserts or removes code. 2480: 2481: @item interpreting a word with undefined interpretation semantics: 2482: For some words, we defined interpretation semantics. For the others: 2483: @code{-14 throw} (Interpreting a compile-only word). Note that this is 2484: checked only by the outer (aka text) interpreter; if the word is 2485: @code{execute}d in some other way, it will typically perform it's 2486: compilation semantics even in interpret state. (We could change @code{'} 2487: and relatives not to give the xt of such words, but we think that would 2488: be too restrictive). 2489: 2490: @item modifying the contents of the input buffer or a string literal: 2491: These are located in writable memory and can be modified. 2492: 2493: @item overflow of the pictured numeric output string: 2494: Not checked. 2495: 2496: @item parsed string overflow: 2497: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow. 2498: 2499: @item producing a result out of range: 2500: On two's complement machines, arithmetic is performed modulo 2501: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double 2502: arithmetic (with appropriate mapping for signed types). Division by zero 2503: typically results in a @code{-55 throw} (floatingpoint unidentified 2504: fault), although a @code{-10 throw} (divide by zero) would be more 2505: appropriate. @code{convert} and @code{>number} currently overflow 2506: silently. 2507: 2508: @item reading from an empty data or return stack: 2509: The data stack is checked by the outer (aka text) interpreter after 2510: every word executed. If it has underflowed, a @code{-4 throw} (Stack 2511: underflow) is performed. Apart from that, the stacks are not checked and 2512: underflows can result in similar behaviour as overflows (of adjacent 2513: stacks). 2514: 2515: @item unexepected end of the input buffer, resulting in an attempt to use a zero-length string as a name: 2516: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to 2517: use zero-length string as a name). Words like @code{'} probably will not 2518: find what they search. Note that it is possible to create zero-length 2519: names with @code{nextname} (should it not?). 2520: 2521: @item @code{>IN} greater than input buffer: 2522: The next invocation of a parsing word returns a string wih length 0. 2523: 2524: @item @code{RECURSE} appears after @code{DOES>}: 2525: Compiles a recursive call to the defining word not to the defined word. 2526: 2527: @item argument input source different than current input source for @code{RESTORE-INPUT}: 2528: @code{-12 THROW}. Note that, once an input file is closed (e.g., because 2529: the end of the file was reached), its source-id may be 2530: reused. Therefore, restoring an input source specification referencing a 2531: closed file may lead to unpredictable results instead of a @code{-12 2532: THROW}. 2533: 2534: In the future, Gforth may be able to retore input source specifications 2535: from other than the current input soruce. 2536: 2537: @item data space containing definitions gets de-allocated: 2538: Deallocation with @code{allot} is not checked. This typically resuls in 2539: memory access faults or execution of illegal instructions. 2540: 2541: @item data space read/write with incorrect alignment: 2542: Processor-dependent. Typically results in a @code{-23 throw} (Address 2543: alignment exception). Under Linux on a 486 or later processor with 2544: alignment turned on, incorrect alignment results in a @code{-9 throw} 2545: (Invalid memory address). There are reportedly some processors with 2546: alignment restrictions that do not report them. 2547: 2548: @item data space pointer not properly aligned, @code{,}, @code{C,}: 2549: Like other alignment errors. 2550: 2551: @item less than u+2 stack items (@code{PICK} and @code{ROLL}): 2552: Not checked. May cause an illegal memory access. 2553: 2554: @item loop control parameters not available: 2555: Not checked. The counted loop words simply assume that the top of return 2556: stack items are loop control parameters and behave accordingly. 2557: 2558: @item most recent definition does not have a name (@code{IMMEDIATE}): 2559: @code{abort" last word was headerless"}. 2560: 2561: @item name not defined by @code{VALUE} used by @code{TO}: 2562: @code{-32 throw} (Invalid name argument) 2563: 2564: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}): 2565: @code{-13 throw} (Undefined word) 2566: 2567: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}): 2568: Gforth behaves as if they were of the same type. I.e., you can predict 2569: the behaviour by interpreting all parameters as, e.g., signed. 2570: 2571: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}: 2572: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} is equivalent to 2573: @code{TO}. 2574: 2575: @item String longer than a counted string returned by @code{WORD}: 2576: Not checked. The string will be ok, but the count will, of course, 2577: contain only the least significant bits of the length. 2578: 2579: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}): 2580: Processor-dependent. Typical behaviours are returning 0 and using only 2581: the low bits of the shift count. 2582: 2583: @item word not defined via @code{CREATE}: 2584: @code{>BODY} produces the PFA of the word no matter how it was defined. 2585: 2586: @code{DOES>} changes the execution semantics of the last defined word no 2587: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to 2588: @code{CREATE , DOES>}. 2589: 2590: @item words improperly used outside @code{<#} and @code{#>}: 2591: Not checked. As usual, you can expect memory faults. 2592: 2593: @end table 2594: 2595: 2596: @c --------------------------------------------------------------------- 2597: @node core-other, , core-ambcond, The Core Words 2598: @subsection Other system documentation 2599: @c --------------------------------------------------------------------- 2600: 2601: @table @i 2602: 2603: @item nonstandard words using @code{PAD}: 2604: None. 2605: 2606: @item operator's terminal facilities available: 2607: After processing the command line, Gforth goes into interactive mode, 2608: and you can give commands to Gforth interactively. The actual facilities 2609: available depend on how you invoke Gforth. 2610: 2611: @item program data space available: 2612: @code{sp@ here - .} gives the space remaining for dictionary and data 2613: stack together. 2614: 2615: @item return stack space available: 2616: By default 16 KBytes. The default can be overridden with the @code{-r} 2617: switch (@pxref{Invocation}) when Gforth starts up. 2618: 2619: @item stack space available: 2620: @code{sp@ here - .} gives the space remaining for dictionary and data 2621: stack together. 2622: 2623: @item system dictionary space required, in address units: 2624: Type @code{here forthstart - .} after startup. At the time of this 2625: writing, this gives 70108 (bytes) on a 32-bit system. 2626: @end table 2627: 2628: 2629: @c ===================================================================== 2630: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance 2631: @section The optional Block word set 2632: @c ===================================================================== 2633: 2634: @menu 2635: * block-idef:: Implementation Defined Options 2636: * block-ambcond:: Ambiguous Conditions 2637: * block-other:: Other System Documentation 2638: @end menu 2639: 2640: 2641: @c --------------------------------------------------------------------- 2642: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set 2643: @subsection Implementation Defined Options 2644: @c --------------------------------------------------------------------- 2645: 2646: @table @i 2647: 2648: @item the format for display by @code{LIST}: 2649: First the screen number is displayed, then 16 lines of 64 characters, 2650: each line preceded by the line number. 2651: 2652: @item the length of a line affected by @code{\}: 2653: 64 characters. 2654: @end table 2655: 2656: 2657: @c --------------------------------------------------------------------- 2658: @node block-ambcond, block-other, block-idef, The optional Block word set 2659: @subsection Ambiguous conditions 2660: @c --------------------------------------------------------------------- 2661: 2662: @table @i 2663: 2664: @item correct block read was not possible: 2665: Typically results in a @code{throw} of some OS-derived value (between 2666: -512 and -2048). If the blocks file was just not long enough, blanks are 2667: supplied for the missing portion. 2668: 2669: @item I/O exception in block transfer: 2670: Typically results in a @code{throw} of some OS-derived value (between 2671: -512 and -2048). 2672: 2673: @item invalid block number: 2674: @code{-35 throw} (Invalid block number) 2675: 2676: @item a program directly alters the contents of @code{BLK}: 2677: The input stream is switched to that other block, at the same 2678: position. If the storing to @code{BLK} happens when interpreting 2679: non-block input, the system will get quite confused when the block ends. 2680: 2681: @item no current block buffer for @code{UPDATE}: 2682: @code{UPDATE} has no effect. 2683: 2684: @end table 2685: 2686: 2687: @c --------------------------------------------------------------------- 2688: @node block-other, , block-ambcond, The optional Block word set 2689: @subsection Other system documentation 2690: @c --------------------------------------------------------------------- 2691: 2692: @table @i 2693: 2694: @item any restrictions a multiprogramming system places on the use of buffer addresses: 2695: No restrictions (yet). 2696: 2697: @item the number of blocks available for source and data: 2698: depends on your disk space. 2699: 2700: @end table 2701: 2702: 2703: @c ===================================================================== 2704: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance 2705: @section The optional Double Number word set 2706: @c ===================================================================== 2707: 2708: @menu 2709: * double-ambcond:: Ambiguous Conditions 2710: @end menu 2711: 2712: 2713: @c --------------------------------------------------------------------- 2714: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set 2715: @subsection Ambiguous conditions 2716: @c --------------------------------------------------------------------- 2717: 2718: @table @i 2719: 2720: @item @var{d} outside of range of @var{n} in @code{D>S}: 2721: The least significant cell of @var{d} is produced. 2722: 2723: @end table 2724: 2725: 2726: @c ===================================================================== 2727: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance 2728: @section The optional Exception word set 2729: @c ===================================================================== 2730: 2731: @menu 2732: * exception-idef:: Implementation Defined Options 2733: @end menu 2734: 2735: 2736: @c --------------------------------------------------------------------- 2737: @node exception-idef, , The optional Exception word set, The optional Exception word set 2738: @subsection Implementation Defined Options 2739: @c --------------------------------------------------------------------- 2740: 2741: @table @i 2742: @item @code{THROW}-codes used in the system: 2743: The codes -256@minus{}-511 are used for reporting signals (see 2744: @file{errore.fs}). The codes -512@minus{}-2047 are used for OS errors 2745: (for file and memory allocation operations). The mapping from OS error 2746: numbers to throw code is -512@minus{}@var{errno}. One side effect of 2747: this mapping is that undefined OS errors produce a message with a 2748: strange number; e.g., @code{-1000 THROW} results in @code{Unknown error 2749: 488} on my system. 2750: @end table 2751: 2752: @c ===================================================================== 2753: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance 2754: @section The optional Facility word set 2755: @c ===================================================================== 2756: 2757: @menu 2758: * facility-idef:: Implementation Defined Options 2759: * facility-ambcond:: Ambiguous Conditions 2760: @end menu 2761: 2762: 2763: @c --------------------------------------------------------------------- 2764: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set 2765: @subsection Implementation Defined Options 2766: @c --------------------------------------------------------------------- 2767: 2768: @table @i 2769: 2770: @item encoding of keyboard events (@code{EKEY}): 2771: Not yet implemeted. 2772: 2773: @item duration of a system clock tick 2774: System dependent. With respect to @code{MS}, the time is specified in 2775: microseconds. How well the OS and the hardware implement this, is 2776: another question. 2777: 2778: @item repeatability to be expected from the execution of @code{MS}: 2779: System dependent. On Unix, a lot depends on load. If the system is 2780: lightly loaded, and the delay is short enough that Gforth does not get 2781: swapped out, the performance should be acceptable. Under MS-DOS and 2782: other single-tasking systems, it should be good. 2783: 2784: @end table 2785: 2786: 2787: @c --------------------------------------------------------------------- 2788: @node facility-ambcond, , facility-idef, The optional Facility word set 2789: @subsection Ambiguous conditions 2790: @c --------------------------------------------------------------------- 2791: 2792: @table @i 2793: 2794: @item @code{AT-XY} can't be performed on user output device: 2795: Largely terminal dependant. No range checks are done on the arguments. 2796: No errors are reported. You may see some garbage appearing, you may see 2797: simply nothing happen. 2798: 2799: @end table 2800: 2801: 2802: @c ===================================================================== 2803: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance 2804: @section The optional File-Access word set 2805: @c ===================================================================== 2806: 2807: @menu 2808: * file-idef:: Implementation Defined Options 2809: * file-ambcond:: Ambiguous Conditions 2810: @end menu 2811: 2812: 2813: @c --------------------------------------------------------------------- 2814: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set 2815: @subsection Implementation Defined Options 2816: @c --------------------------------------------------------------------- 2817: 2818: @table @i 2819: 2820: @item File access methods used: 2821: @code{R/O}, @code{R/W} and @code{BIN} work as you would 2822: expect. @code{W/O} translates into the C file opening mode @code{w} (or 2823: @code{wb}): The file is cleared, if it exists, and created, if it does 2824: not (both with @code{open-file} and @code{create-file}). Under Unix 2825: @code{create-file} creates a file with 666 permissions modified by your 2826: umask. 2827: 2828: @item file exceptions: 2829: The file words do not raise exceptions (except, perhaps, memory access 2830: faults when you pass illegal addresses or file-ids). 2831: 2832: @item file line terminator: 2833: System-dependent. Gforth uses C's newline character as line 2834: terminator. What the actual character code(s) of this are is 2835: system-dependent. 2836: 2837: @item file name format 2838: System dependent. Gforth just uses the file name format of your OS. 2839: 2840: @item information returned by @code{FILE-STATUS}: 2841: @code{FILE-STATUS} returns the most powerful file access mode allowed 2842: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file 2843: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable 2844: along with the retured mode. 2845: 2846: @item input file state after an exception when including source: 2847: All files that are left via the exception are closed. 2848: 2849: @item @var{ior} values and meaning: 2850: The @var{ior}s returned by the file and memory allocation words are 2851: intended as throw codes. They typically are in the range 2852: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to 2853: @var{ior}s is -512@minus{}@var{errno}. 2854: 2855: @item maximum depth of file input nesting: 2856: limited by the amount of return stack, locals/TIB stack, and the number 2857: of open files available. This should not give you troubles. 2858: 2859: @item maximum size of input line: 2860: @code{/line}. Currently 255. 2861: 2862: @item methods of mapping block ranges to files: 2863: Currently, the block words automatically access the file 2864: @file{blocks.fb} in the currend working directory. More sophisticated 2865: methods could be implemented if there is demand (and a volunteer). 2866: 2867: @item number of string buffers provided by @code{S"}: 2868: 1 2869: 2870: @item size of string buffer used by @code{S"}: 2871: @code{/line}. currently 255. 2872: 2873: @end table 2874: 2875: @c --------------------------------------------------------------------- 2876: @node file-ambcond, , file-idef, The optional File-Access word set 2877: @subsection Ambiguous conditions 2878: @c --------------------------------------------------------------------- 2879: 2880: @table @i 2881: 2882: @item attempting to position a file outside it's boundaries: 2883: @code{REPOSITION-FILE} is performed as usual: Afterwards, 2884: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}. 2885: 2886: @item attempting to read from file positions not yet written: 2887: End-of-file, i.e., zero characters are read and no error is reported. 2888: 2889: @item @var{file-id} is invalid (@code{INCLUDE-FILE}): 2890: An appropriate exception may be thrown, but a memory fault or other 2891: problem is more probable. 2892: 2893: @item I/O exception reading or closing @var{file-id} (@code{include-file}, @code{included}): 2894: The @var{ior} produced by the operation, that discovered the problem, is 2895: thrown. 2896: 2897: @item named file cannot be opened (@code{included}): 2898: The @var{ior} produced by @code{open-file} is thrown. 2899: 2900: @item requesting an unmapped block number: 2901: There are no unmapped legal block numbers. On some operating systems, 2902: writing a block with a large number may overflow the file system and 2903: have an error message as consequence. 2904: 2905: @item using @code{source-id} when @code{blk} is non-zero: 2906: @code{source-id} performs its function. Typically it will give the id of 2907: the source which loaded the block. (Better ideas?) 2908: 2909: @end table 2910: 2911: 2912: @c ===================================================================== 2913: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance 2914: @section The optional Floating-Point word set 2915: @c ===================================================================== 2916: 2917: @menu 2918: * floating-idef:: Implementation Defined Options 2919: * floating-ambcond:: Ambiguous Conditions 2920: @end menu 2921: 2922: 2923: @c --------------------------------------------------------------------- 2924: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set 2925: @subsection Implementation Defined Options 2926: @c --------------------------------------------------------------------- 2927: 2928: @table @i 2929: 2930: @item format and range of floating point numbers: 2931: System-dependent; the @code{double} type of C. 2932: 2933: @item results of @code{REPRESENT} when @var{float} is out of range: 2934: System dependent; @code{REPRESENT} is implemented using the C library 2935: function @code{ecvt()} and inherits its behaviour in this respect. 2936: 2937: @item rounding or truncation of floating-point numbers: 2938: System dependent; the rounding behaviour is inherited from the hosting C 2939: compiler. IEEE-FP-based (i.e., most) systems by default round to 2940: nearest, and break ties by rounding to even (i.e., such that the last 2941: bit of the mantissa is 0). 2942: 2943: @item size of floating-point stack: 2944: @code{s" FLOATING-STACK" environment? drop .}. Can be changed at startup 2945: with the command-line option @code{-f}. 2946: 2947: @item width of floating-point stack: 2948: @code{1 floats}. 2949: 2950: @end table 2951: 2952: 2953: @c --------------------------------------------------------------------- 2954: @node floating-ambcond, , floating-idef, The optional Floating-Point word set 2955: @subsection Ambiguous conditions 2956: @c --------------------------------------------------------------------- 2957: 2958: @table @i 2959: 2960: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned: 2961: System-dependent. Typically results in an alignment fault like other 2962: alignment violations. 2963: 2964: @item @code{f@@} or @code{f!} used with an address that is not float aligned: 2965: System-dependent. Typically results in an alignment fault like other 2966: alignment violations. 2967: 2968: @item Floating-point result out of range: 2969: System-dependent. Can result in a @code{-55 THROW} (Floating-point 2970: unidentified fault), or can produce a special value representing, e.g., 2971: Infinity. 2972: 2973: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned: 2974: System-dependent. Typically results in an alignment fault like other 2975: alignment violations. 2976: 2977: @item BASE is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}): 2978: The floating-point number is converted into decimal nonetheless. 2979: 2980: @item Both arguments are equal to zero (@code{FATAN2}): 2981: System-dependent. @code{FATAN2} is implemented using the C library 2982: function @code{atan2()}. 2983: 2984: @item Using ftan on an argument @var{r1} where cos(@var{r1}) is zero: 2985: System-dependent. Anyway, typically the cos of @var{r1} will not be zero 2986: because of small errors and the tan will be a very large (or very small) 2987: but finite number. 2988: 2989: @item @var{d} cannot be presented precisely as a float in @code{D>F}: 2990: The result is rounded to the nearest float. 2991: 2992: @item dividing by zero: 2993: @code{-55 throw} (Floating-point unidentified fault) 2994: 2995: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}): 2996: System dependent. On IEEE-FP based systems the number is converted into 2997: an infinity. 2998: 2999: @item @var{float}<1 (@code{facosh}): 3000: @code{-55 throw} (Floating-point unidentified fault) 3001: 3002: @item @var{float}=<-1 (@code{flnp1}): 3003: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems 3004: negative infinity is typically produced for @var{float}=-1. 3005: 3006: @item @var{float}=<0 (@code{fln}, @code{flog}): 3007: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems 3008: negative infinity is typically produced for @var{float}=0. 3009: 3010: @item @var{float}<0 (@code{fasinh}, @code{fsqrt}): 3011: @code{-55 throw} (Floating-point unidentified fault). @code{fasinh} 3012: produces values for these inputs on my Linux box (Bug in the C library?) 3013: 3014: @item |@var{float}|>1 (@code{facos}, @code{fasin}, @code{fatanh}): 3015: @code{-55 throw} (Floating-point unidentified fault). 3016: 3017: @item integer part of float cannot be represented by @var{d} in @code{f>d}: 3018: @code{-55 throw} (Floating-point unidentified fault). 3019: 3020: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}): 3021: This does not happen. 3022: @end table 3023: 3024: 3025: 3026: @c ===================================================================== 3027: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance 3028: @section The optional Locals word set 3029: @c ===================================================================== 3030: 3031: @menu 3032: * locals-idef:: Implementation Defined Options 3033: * locals-ambcond:: Ambiguous Conditions 3034: @end menu 3035: 3036: 3037: @c --------------------------------------------------------------------- 3038: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set 3039: @subsection Implementation Defined Options 3040: @c --------------------------------------------------------------------- 3041: 3042: @table @i 3043: 3044: @item maximum number of locals in a definition: 3045: @code{s" #locals" environment? drop .}. Currently 15. This is a lower 3046: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8 3047: characters. The number of locals in a definition is bounded by the size 3048: of locals-buffer, which contains the names of the locals. 3049: 3050: @end table 3051: 3052: 3053: @c --------------------------------------------------------------------- 3054: @node locals-ambcond, , locals-idef, The optional Locals word set 3055: @subsection Ambiguous conditions 3056: @c --------------------------------------------------------------------- 3057: 3058: @table @i 3059: 3060: @item executing a named local in interpretation state: 3061: @code{-14 throw} (Interpreting a compile-only word). 3062: 3063: @item @var{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}): 3064: @code{-32 throw} (Invalid name argument) 3065: 3066: @end table 3067: 3068: 3069: @c ===================================================================== 3070: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance 3071: @section The optional Memory-Allocation word set 3072: @c ===================================================================== 3073: 3074: @menu 3075: * memory-idef:: Implementation Defined Options 3076: @end menu 3077: 3078: 3079: @c --------------------------------------------------------------------- 3080: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set 3081: @subsection Implementation Defined Options 3082: @c --------------------------------------------------------------------- 3083: 3084: @table @i 3085: 3086: @item values and meaning of @var{ior}: 3087: The @var{ior}s returned by the file and memory allocation words are 3088: intended as throw codes. They typically are in the range 3089: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to 3090: @var{ior}s is -512@minus{}@var{errno}. 3091: 3092: @end table 3093: 3094: @c ===================================================================== 3095: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance 3096: @section The optional Programming-Tools word set 3097: @c ===================================================================== 3098: 3099: @menu 3100: * programming-idef:: Implementation Defined Options 3101: * programming-ambcond:: Ambiguous Conditions 3102: @end menu 3103: 3104: 3105: @c --------------------------------------------------------------------- 3106: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set 3107: @subsection Implementation Defined Options 3108: @c --------------------------------------------------------------------- 3109: 3110: @table @i 3111: 3112: @item ending sequence for input following @code{;code} and @code{code}: 3113: Not implemented (yet). 3114: 3115: @item manner of processing input following @code{;code} and @code{code}: 3116: Not implemented (yet). 3117: 3118: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}: 3119: Not implemented (yet). If they were implemented, they would use the 3120: search order wordset. 3121: 3122: @item source and format of display by @code{SEE}: 3123: The source for @code{see} is the intermediate code used by the inner 3124: interpreter. The current @code{see} tries to output Forth source code 3125: as well as possible. 3126: 3127: @end table 3128: 3129: @c --------------------------------------------------------------------- 3130: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set 3131: @subsection Ambiguous conditions 3132: @c --------------------------------------------------------------------- 3133: 3134: @table @i 3135: 3136: @item deleting the compilation wordlist (@code{FORGET}): 3137: Not implemented (yet). 3138: 3139: @item fewer than @var{u}+1 items on the control flow stack (@code{CS-PICK}, @code{CS-ROLL}): 3140: This typically results in an @code{abort"} with a descriptive error 3141: message (may change into a @code{-22 throw} (Control structure mismatch) 3142: in the future). You may also get a memory access error. If you are 3143: unlucky, this ambiguous condition is not caught. 3144: 3145: @item @var{name} can't be found (@code{forget}): 3146: Not implemented (yet). 3147: 3148: @item @var{name} not defined via @code{CREATE}: 3149: @code{;code} is not implemented (yet). If it were, it would behave like 3150: @code{DOES>} in this respect, i.e., change the execution semantics of 3151: the last defined word no matter how it was defined. 3152: 3153: @item @code{POSTPONE} applied to @code{[IF]}: 3154: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is 3155: equivalent to @code{[IF]}. 3156: 3157: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}: 3158: Continue in the same state of conditional compilation in the next outer 3159: input source. Currently there is no warning to the user about this. 3160: 3161: @item removing a needed definition (@code{FORGET}): 3162: Not implemented (yet). 3163: 3164: @end table 3165: 3166: 3167: @c ===================================================================== 3168: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance 3169: @section The optional Search-Order word set 3170: @c ===================================================================== 3171: 3172: @menu 3173: * search-idef:: Implementation Defined Options 3174: * search-ambcond:: Ambiguous Conditions 3175: @end menu 3176: 3177: 3178: @c --------------------------------------------------------------------- 3179: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set 3180: @subsection Implementation Defined Options 3181: @c --------------------------------------------------------------------- 3182: 3183: @table @i 3184: 3185: @item maximum number of word lists in search order: 3186: @code{s" wordlists" environment? drop .}. Currently 16. 3187: 3188: @item minimum search order: 3189: @code{root root}. 3190: 3191: @end table 3192: 3193: @c --------------------------------------------------------------------- 3194: @node search-ambcond, , search-idef, The optional Search-Order word set 3195: @subsection Ambiguous conditions 3196: @c --------------------------------------------------------------------- 3197: 3198: @table @i 3199: 3200: @item changing the compilation wordlist (during compilation): 3201: The definition is put into the wordlist that is the compilation wordlist 3202: when @code{REVEAL} is executed (by @code{;}, @code{DOES>}, 3203: @code{RECURSIVE}, etc.). 3204: 3205: @item search order empty (@code{previous}): 3206: @code{abort" Vocstack empty"}. 3207: 3208: @item too many word lists in search order (@code{also}): 3209: @code{abort" Vocstack full"}. 3210: 3211: @end table 3212: 3213: 3214: @node Model, Emacs and Gforth, ANS conformance, Top 3215: @chapter Model 3216: 3217: @node Emacs and Gforth, Internals, Model, Top 3218: @chapter Emacs and Gforth 3219: 3220: Gforth comes with @file{gforth.el}, an improved version of 3221: @file{forth.el} by Goran Rydqvist (icluded in the TILE package). The 3222: improvements are a better (but still not perfect) handling of 3223: indentation. I have also added comment paragraph filling (@kbd{M-q}), 3224: commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) regions and 3225: removing debugging tracers (@kbd{C-x ~}, @pxref{Debugging}). I left the 3226: stuff I do not use alone, even though some of it only makes sense for 3227: TILE. To get a description of these features, enter Forth mode and type 3228: @kbd{C-h m}. 3229: 3230: In addition, Gforth supports Emacs quite well: The source code locations 3231: given in error messages, debugging output (from @code{~~}) and failed 3232: assertion messages are in the right format for Emacs' compilation mode 3233: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs 3234: Manual}) so the source location corresponding to an error or other 3235: message is only a few keystrokes away (@kbd{C-x `} for the next error, 3236: @kbd{C-c C-c} for the error under the cursor). 3237: 3238: Also, if you @code{include} @file{etags.fs}, a new @file{TAGS} file 3239: (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) will be produced that 3240: contains the definitions of all words defined afterwards. You can then 3241: find the source for a word using @kbd{M-.}. Note that emacs can use 3242: several tags files at the same time (e.g., one for the Gforth sources 3243: and one for your program, @pxref{Select Tags Table,,Selecting a Tags 3244: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is 3245: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g., 3246: @file{/usr/local/share/gforth/0.2/TAGS}).: 3256: @node Internals, Bugs, Emacs and Gforth, Top 3257: @chapter Internals 3258: 3259: Reading this section is not necessary for programming with Gforth. It 3260: should be helpful for finding your way in the Gforth sources. 3261:: 3268: @menu 3269: * Portability:: 3270: * Threading:: 3271: * Primitives:: 3272: * System Architecture:: 3273: * Performance:: 3274: @end menu 3275: 3276: @node Portability, Threading, Internals, Internals@footnote{Unfortunately, long longs are not implemented 3303: properly on all machines (e.g., on alpha-osf1, long longs are only 64 3304: bits, the same size as longs (and pointers), but they should be twice as 3305: long according to @ref{Long Long, , Double-Word Integers, gcc.info, GNU 3306: C Manual}). So, we had to implement doubles in C after all. Still, on 3307: most machines we can use long longs and achieve better performance than 3308: with the emulation package.}. GNU C is available for free on all 3309: important (and many unimportant) UNIX machines, VMS, 80386s running 3310: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run 3311: on all these machines. 3312: 3313: Writing in a portable language has the reputation of producing code that 3314: is slower than assembly. For our Forth engine we repeatedly looked at 3315: the code produced by the compiler and eliminated most compiler-induced 3316: inefficiencies by appropriate changes in the source-code. 3317: 3318: However, register allocation cannot be portably influenced by the 3319: programmer, leading to some inefficiencies on register-starved 3320: machines. We use explicit register declarations (@pxref{Explicit Reg 3321: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to 3322: improve the speed on some machines. They are turned on by using the 3323: @code{gcc} switch @code{-DFORCE_REG}. Unfortunately, this feature not 3324: only depends on the machine, but also on the compiler version: On some 3325: machines some compiler versions produce incorrect code when certain 3326: explicit register declarations are used. So by default 3327: @code{-DFORCE_REG} is not used. 3328: 3329: @node Threading, Primitives, Portability, Internals 3330: @section Threading 3331: 3332: GNU C's labels as values extension (available since @code{gcc-2.0}, 3333: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual}) 3334: makes it possible to take the address of @var{label} by writing 3335: @code{&&@var{label}}. This address can then be used in a statement like 3336: @code{goto *@var{address}}. I.e., @code{goto *&&x} is the same as 3337: @code{goto x}. 3338: 3339: With this feature an indirect threaded NEXT looks like: 3340: @example 3341: cfa = *ip++; 3342: ca = *cfa; 3343: goto *ca; 3344: @end example 3345: For those unfamiliar with the names: @code{ip} is the Forth instruction 3346: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths 3347: execution token and points to the code field of the next word to be 3348: executed; The @code{ca} (code address) fetched from there points to some 3349: executable code, e.g., a primitive or the colon definition handler 3350: @code{docol}. 3351: 3352: Direct threading is even simpler: 3353: @example 3354: ca = *ip++; 3355: goto *ca; 3356: @end example 3357: 3358: Of course we have packaged the whole thing neatly in macros called 3359: @code{NEXT} and @code{NEXT1} (the part of NEXT after fetching the cfa). 3360: 3361: @menu 3362: * Scheduling:: 3363: * Direct or Indirect Threaded?:: 3364: * DOES>:: 3365: @end menu 3366: 3367: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading 3368: @subsection Scheduling 3369: 3370: There is a little complication: Pipelined and superscalar processors, 3371: i.e., RISC and some modern CISC machines can process independent 3372: instructions while waiting for the results of an instruction. The 3373: compiler usually reorders (schedules) the instructions in a way that 3374: achieves good usage of these delay slots. However, on our first tries 3375: the compiler did not do well on scheduling primitives. E.g., for 3376: @code{+} implemented as 3377: @example 3378: n=sp[0]+sp[1]; 3379: sp++; 3380: sp[0]=n; 3381: NEXT; 3382: @end example 3383: the NEXT comes strictly after the other code, i.e., there is nearly no 3384: scheduling. After a little thought the problem becomes clear: The 3385: compiler cannot know that sp and ip point to different addresses (and 3386: the version of @code{gcc} we used would not know it even if it was 3387: possible), so it could not move the load of the cfa above the store to 3388: the TOS. Indeed the pointers could be the same, if code on or very near 3389: the top of stack were executed. In the interest of speed we chose to 3390: forbid this probably unused ``feature'' and helped the compiler in 3391: scheduling: NEXT is divided into the loading part (@code{NEXT_P1}) and 3392: the goto part (@code{NEXT_P2}). @code{+} now looks like: 3393: @example 3394: n=sp[0]+sp[1]; 3395: sp++; 3396: NEXT_P1; 3397: sp[0]=n; 3398: NEXT_P2; 3399: @end example 3400: This can be scheduled optimally by the compiler. 3401: 3402: This division can be turned off with the switch @code{-DCISC_NEXT}. This 3403: switch is on by default on machines that do not profit from scheduling 3404: (e.g., the 80386), in order to preserve registers. 3405: 3406: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading 3407: @subsection Direct or Indirect Threaded? 3408: 3409: Both! After packaging the nasty details in macro definitions we 3410: realized that we could switch between direct and indirect threading by 3411: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and 3412: defining a few machine-specific macros for the direct-threading case. 3413: On the Forth level we also offer access words that hide the 3414: differences between the threading methods (@pxref{Threading Words}). 3415: 3416: Indirect threading is implemented completely 3417: machine-independently. Direct threading needs routines for creating 3418: jumps to the executable code (e.g. to docol or dodoes). These routines 3419: are inherently machine-dependent, but they do not amount to many source 3420: lines. I.e., even porting direct threading to a new machine is a small 3421: effort. 3422: 3423: @node DOES>, , Direct or Indirect Threaded?, Threading 3424: @subsection DOES> 3425: One of the most complex parts of a Forth engine is @code{dodoes}, i.e., 3426: the chunk of code executed by every word defined by a 3427: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find 3428: the Forth code to be executed, i.e. the code after the @code{DOES>} (the 3429: DOES-code)? There are two solutions: 3430: 3431: In fig-Forth the code field points directly to the dodoes and the 3432: DOES-code address is stored in the cell after the code address 3433: (i.e. at cfa cell+). It may seem that this solution is illegal in the 3434: Forth-79 and all later standards, because in fig-Forth this address 3435: lies in the body (which is illegal in these standards). However, by 3436: making the code field larger for all words this solution becomes legal 3437: again. We use this approach for the indirect threaded version. Leaving 3438: a cell unused in most words is a bit wasteful, but on the machines we 3439: are targetting this is hardly a problem. The other reason for having a 3440: code field size of two cells is to avoid having different image files 3441: for direct and indirect threaded systems (@pxref{System Architecture}). 3442: 3443: The other approach is that the code field points or jumps to the cell 3444: after @code{DOES}. In this variant there is a jump to @code{dodoes} at 3445: this address. @code{dodoes} can then get the DOES-code address by 3446: computing the code address, i.e., the address of the jump to dodoes, 3447: and add the length of that jump field. A variant of this is to have a 3448: call to @code{dodoes} after the @code{DOES>}; then the return address 3449: (which can be found in the return register on RISCs) is the DOES-code 3450: address. Since the two cells available in the code field are usually 3451: used up by the jump to the code address in direct threading, we use 3452: this approach for direct threading. We did not want to add another 3453: cell to the code field. 3454: 3455: @node Primitives, System Architecture, Threading, Internals 3456: @section Primitives 3457: 3458: @menu 3459: * Automatic Generation:: 3460: * TOS Optimization:: 3461: * Produced code:: 3462: @end menu 3463: 3464: @node Automatic Generation, TOS Optimization, Primitives, Primitives 3465: @subsection Automatic Generation 3466: 3467: Since the primitives are implemented in a portable language, there is no 3468: longer any need to minimize the number of primitives. On the contrary, 3469: having many primitives is an advantage: speed. In order to reduce the 3470: number of errors in primitives and to make programming them easier, we 3471: provide a tool, the primitive generator (@file{prims2x.fs}), that 3472: automatically generates most (and sometimes all) of the C code for a 3473: primitive from the stack effect notation. The source for a primitive 3474: has the following form: 3475: 3476: @format 3477: @var{Forth-name} @var{stack-effect} @var{category} [@var{pronounc.}] 3478: [@code{""}@var{glossary entry}@code{""}] 3479: @var{C code} 3480: [@code{:} 3481: @var{Forth code}] 3482: @end format 3483: 3484: The items in brackets are optional. The category and glossary fields 3485: are there for generating the documentation, the Forth code is there 3486: for manual implementations on machines without GNU C. E.g., the source 3487: for the primitive @code{+} is: 3488: @example 3489: + n1 n2 -- n core plus 3490: n = n1+n2; 3491: @end example 3492: 3493: This looks like a specification, but in fact @code{n = n1+n2} is C 3494: code. Our primitive generation tool extracts a lot of information from 3495: the stack effect notations@footnote{We use a one-stack notation, even 3496: though we have separate data and floating-point stacks; The separate 3497: notation can be generated easily from the unified notation.}: The number 3498: of items popped from and pushed on the stack, their type, and by what 3499: name they are referred to in the C code. It then generates a C code 3500: prelude and postlude for each primitive. The final C code for @code{+} 3501: looks like this: 3502: 3503: @example 3504: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */ 3505: /* */ /* documentation */ 3506: @{ 3507: DEF_CA /* definition of variable ca (indirect threading) */ 3508: Cell n1; /* definitions of variables */ 3509: Cell n2; 3510: Cell n; 3511: n1 = (Cell) sp[1]; /* input */ 3512: n2 = (Cell) TOS; 3513: sp += 1; /* stack adjustment */ 3514: NAME("+") /* debugging output (with -DDEBUG) */ 3515: @{ 3516: n = n1+n2; /* C code taken from the source */ 3517: @} 3518: NEXT_P1; /* NEXT part 1 */ 3519: TOS = (Cell)n; /* output */ 3520: NEXT_P2; /* NEXT part 2 */ 3521: @} 3522: @end example 3523: 3524: This looks long and inefficient, but the GNU C compiler optimizes quite 3525: well and produces optimal code for @code{+} on, e.g., the R3000 and the 3526: HP RISC machines: Defining the @code{n}s does not produce any code, and 3527: using them as intermediate storage also adds no cost. 3528: 3529: There are also other optimizations, that are not illustrated by this 3530: example: Assignments between simple variables are usually for free (copy 3531: propagation). If one of the stack items is not used by the primitive 3532: (e.g. in @code{drop}), the compiler eliminates the load from the stack 3533: (dead code elimination). On the other hand, there are some things that 3534: the compiler does not do, therefore they are performed by 3535: @file{prims2x.fs}: The compiler does not optimize code away that stores 3536: a stack item to the place where it just came from (e.g., @code{over}). 3537: 3538: While programming a primitive is usually easy, there are a few cases 3539: where the programmer has to take the actions of the generator into 3540: account, most notably @code{?dup}, but also words that do not (always) 3541: fall through to NEXT. 3542: 3543: @node TOS Optimization, Produced code, Automatic Generation, Primitives 3544: @subsection TOS Optimization 3545: 3546: An important optimization for stack machine emulators, e.g., Forth 3547: engines, is keeping one or more of the top stack items in 3548: registers. If a word has the stack effect @var{in1}...@var{inx} @code{--} 3549: @var{out1}...@var{outy}, keeping the top @var{n} items in registers 3550: @itemize 3551: @item 3552: is better than keeping @var{n-1} items, if @var{x>=n} and @var{y>=n}, 3553: due to fewer loads from and stores to the stack. 3554: @item is slower than keeping @var{n-1} items, if @var{x<>y} and @var{x<n} and 3555: @var{y<n}, due to additional moves between registers. 3556: @end itemize 3557: 3558: In particular, keeping one item in a register is never a disadvantage, 3559: if there are enough registers. Keeping two items in registers is a 3560: disadvantage for frequent words like @code{?branch}, constants, 3561: variables, literals and @code{i}. Therefore our generator only produces 3562: code that keeps zero or one items in registers. The generated C code 3563: covers both cases; the selection between these alternatives is made at 3564: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C 3565: code for @code{+} is just a simple variable name in the one-item case, 3566: otherwise it is a macro that expands into @code{sp[0]}. Note that the 3567: GNU C compiler tries to keep simple variables like @code{TOS} in 3568: registers, and it usually succeeds, if there are enough registers. 3569: 3570: The primitive generator performs the TOS optimization for the 3571: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point 3572: operations the benefit of this optimization is even larger: 3573: floating-point operations take quite long on most processors, but can be 3574: performed in parallel with other operations as long as their results are 3575: not used. If the FP-TOS is kept in a register, this works. If 3576: it is kept on the stack, i.e., in memory, the store into memory has to 3577: wait for the result of the floating-point operation, lengthening the 3578: execution time of the primitive considerably. 3579: 3580: The TOS optimization makes the automatic generation of primitives a 3581: bit more complicated. Just replacing all occurrences of @code{sp[0]} by 3582: @code{TOS} is not sufficient. There are some special cases to 3583: consider: 3584: @itemize 3585: @item In the case of @code{dup ( w -- w w )} the generator must not 3586: eliminate the store to the original location of the item on the stack, 3587: if the TOS optimization is turned on. 3588: @item Primitives with stack effects of the form @code{--} 3589: @var{out1}...@var{outy} must store the TOS to the stack at the start. 3590: Likewise, primitives with the stack effect @var{in1}...@var{inx} @code{--} 3591: must load the TOS from the stack at the end. But for the null stack 3592: effect @code{--} no stores or loads should be generated. 3593: @end itemize 3594: 3595: @node Produced code, , TOS Optimization, Primitives 3596: @subsection Produced code 3597: 3598: To see what assembly code is produced for the primitives on your machine 3599: with your compiler and your flag settings, type @code{make engine.s} and 3600: look at the resulting file @file{engine.s}. 3601: 3602: @node System Architecture, Performance, Primitives, Internals 3603: @section System Architecture 3604: 3605: Our Forth system consists not only of primitives, but also of 3606: definitions written in Forth. Since the Forth compiler itself belongs 3607: to those definitions, it is not possible to start the system with the 3608: primitives and the Forth source alone. Therefore we provide the Forth 3609: code as an image file in nearly executable form. At the start of the 3610: system a C routine loads the image file into memory, sets up the 3611: memory (stacks etc.) according to information in the image file, and 3612: starts executing Forth code. 3613: 3614: The image file format is a compromise between the goals of making it 3615: easy to generate image files and making them portable. The easiest way 3616: to generate an image file is to just generate a memory dump. However, 3617: this kind of image file cannot be used on a different machine, or on 3618: the next version of the engine on the same machine, it even might not 3619: work with the same engine compiled by a different version of the C 3620: compiler. We would like to have as few versions of the image file as 3621: possible, because we do not want to distribute many versions of the 3622: same image file, and to make it easy for the users to use their image 3623: files on many machines. We currently need to create a different image 3624: file for machines with different cell sizes and different byte order 3625: (little- or big-endian)@footnote{We are considering adding information to the 3626: image file that enables the loader to change the byte order.}. 3627: 3628: Forth code that is going to end up in a portable image file has to 3629: comply to some restrictions: addresses have to be stored in memory with 3630: special words (@code{A!}, @code{A,}, etc.) in order to make the code 3631: relocatable. Cells, floats, etc., have to be stored at the natural 3632: alignment boundaries@footnote{E.g., store floats (8 bytes) at an address 3633: dividable by~8. This happens automatically in our system when you use 3634: the ANS Forth alignment words.}, in order to avoid alignment faults on 3635: machines with stricter alignment. The image file is produced by a 3636: metacompiler (@file{cross.fs}). 3637: 3638: So, unlike the image file of Mitch Bradleys @code{cforth}, our image 3639: file is not directly executable, but has to undergo some manipulations 3640: during loading. Address relocation is performed at image load-time, not 3641: at run-time. The loader also has to replace tokens standing for 3642: primitive calls with the appropriate code-field addresses (or code 3643: addresses in the case of direct threading). 3644: 3645: @node Performance, , System Architecture, Internals 3646: @section Performance 3647: 3648: On RISCs the Gforth engine is very close to optimal; i.e., it is usually 3649: impossible to write a significantly faster engine. 3650: 3651: On register-starved machines like the 386 architecture processors 3652: improvements are possible, because @code{gcc} does not utilize the 3653: registers as well as a human, even with explicit register declarations; 3654: e.g., Bernd Beuster wrote a Forth system fragment in assembly language 3655: and hand-tuned it for the 486; this system is 1.19 times faster on the 3656: Sieve benchmark on a 486DX2/66 than Gforth compiled with 3657: @code{gcc-2.6.3} with @code{-DFORCE_REG}. 3658: 3659: However, this potential advantage of assembly language implementations 3660: is not necessarily realized in complete Forth systems: We compared 3661: Gforth (direct threaded, compiled with @code{gcc-2.6.3} and 3662: @code{-DFORCE_REG}) with Win32Forth 1.2093, LMI's NT Forth (Beta, May 3663: 1994) and Eforth (with and without peephole (aka pinhole) optimization 3664: of the threaded code); all these systems were written in assembly 3665: language. We also compared Gforth with three systems written in C: 3666: PFE-0.9.14 (compiled with @code{gcc-2.6.3} with the default 3667: configuration for Linux: @code{-O2 -fomit-frame-pointer -DUSE_REGS 3668: -DUNROLL_NEXT}), ThisForth Beta (compiled with gcc-2.6.3 -O3 3669: -fomit-frame-pointer; ThisForth employs peephole optimization of the 3670: threaded code) and TILE (compiled with @code{make opt}). We benchmarked 3671: Gforth, PFE, ThisForth and TILE on a 486DX2/66 under Linux. Kenneth 3672: O'Heskin kindly provided the results for Win32Forth and NT Forth on a 3673: 486DX2/66 with similar memory performance under Windows NT. Marcel 3674: Hendrix ported Eforth to Linux, then extended it to run the benchmarks, 3675: added the peephole optimizer, ran the benchmarks and reported the 3676: results. 3677: 3678: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and 3679: matrix multiplication come from the Stanford integer benchmarks and have 3680: been translated into Forth by Martin Fraeman; we used the versions 3681: included in the TILE Forth package, but with bigger data set sizes; and 3682: a recursive Fibonacci number computation for benchmarking calling 3683: performance. The following table shows the time taken for the benchmarks 3684: scaled by the time taken by Gforth (in other words, it shows the speedup 3685: factor that Gforth achieved over the other systems). 3686: 3687: @example 3688: relative Win32- NT eforth This- 3689: time Gforth Forth Forth eforth +opt PFE Forth TILE 3690: sieve 1.00 1.39 1.14 1.39 0.85 1.58 3.18 8.58 3691: bubble 1.00 1.31 1.41 1.48 0.88 1.50 3.88 3692: matmul 1.00 1.47 1.35 1.46 1.16 1.58 4.09 3693: fib 1.00 1.52 1.34 1.22 1.13 1.74 2.99 4.30 3694: @end example 3695: 3696: You may find the good performance of Gforth compared with the systems 3697: written in assembly language quite surprising. One important reason for 3698: the disappointing performance of these systems is probably that they are 3699: not written optimally for the 486 (e.g., they use the @code{lods} 3700: instruction). In addition, Win32Forth uses a comfortable, but costly 3701: method for relocating the Forth image: like @code{cforth}, it computes 3702: the actual addresses at run time, resulting in two address computations 3703: per NEXT (@pxref{System Architecture}). 3704: 3705: Only Eforth with the peephole optimizer performs comparable to 3706: Gforth. The speedups achieved with peephole optimization of threaded 3707: code are quite remarkable. Adding a peephole optimizer to Gforth should 3708: cause similar speedups. 3709: 3710: The speedup of Gforth over PFE, ThisForth and TILE can be easily 3711: explained with the self-imposed restriction to standard C, which makes 3712: efficient threading impossible (however, the measured implementation of 3713: PFE uses a GNU C extension: @ref{Global Reg Vars, , Defining Global 3714: Register Variables, gcc.info, GNU C Manual}). Moreover, current C 3715: compilers have a hard time optimizing other aspects of the ThisForth 3716: and the TILE source. 3717: 3718: Note that the performance of Gforth on 386 architecture processors 3719: varies widely with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} 3720: failed to allocate any of the virtual machine registers into real 3721: machine registers by itself and would not work correctly with explicit 3722: register declarations, giving a 1.3 times slower engine (on a 486DX2/66 3723: running the Sieve) than the one measured above. 3724: 3725: In @cite{Translating Forth to Efficient C} by M. Anton Ertl and Martin 3726: Maierhofer (presented at EuroForth '95), an indirect threaded version of 3727: Gforth is compared with Win32Forth, NT Forth, PFE, and ThisForth; that 3728: version of Gforth is 2\%@minus{}8\% slower on a 486 than the version 3729: used here. The paper available at 3730: @*@file{}; 3731: it also contains numbers for some native code systems. You can find 3732: numbers for Gforth on various machines in @file{Benchres}. 3733: 3734: @node Bugs, Origin, Internals, Top 3735: @chapter Bugs 3736: 3737: Known bugs are described in the file BUGS in the Gforth distribution. 3738: 3739: If you find a bug, please send a bug report to 3740: @code{bug-gforth@@gnu.ai.mit.edu}. A bug report should 3741: describe the Gforth version used (it is announced at the start of an 3742: interactive Gforth session), the machine and operating system (on Unix 3743: systems you can use @code{uname -a} to produce this information), the 3744: installation options (send the @code{config.status} file), and a 3745: complete list of changes you (or your installer) have made to the Gforth 3746: sources (if any); it should contain a program (or a sequence of keyboard 3747: commands) that reproduces the bug and a description of what you think 3748: constitutes the buggy behaviour. 3749: 3750: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How 3751: to Report Bugs, gcc.info, GNU C Manual}. 3752: 3753: 3754: @node Origin, Word Index, Bugs, Top 3755: @chapter Authors and Ancestors of Gforth 3756: 3757: @section Authors and Contributors 3758: 3759: The Gforth project was started in mid-1992 by Bernd Paysan and Anton 3760: Ertl. The third major author was Jens Wilke. Lennart Benschop (who was 3761: one of Gforth's first users, in mid-1993) and Stuart Ramsden inspired us 3762: with their continuous feedback. Lennart Benshop contributed 3763: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic 3764: support for calling C libraries. Helpful comments also came from Paul 3765: Kleinrubatscher, Christian Pirker, Dirk Zoller and Marcel Hendrix. 3766: 3767: Gforth also owes a lot to the authors of the tools we used (GCC, CVS, 3768: and autoconf, among others), and to the creators of the Internet: Gforth 3769: was developed across the Internet, and its authors have not met 3770: physically yet. 3771: 3772: @section Pedigree 3773: 3774: Gforth descends from BigForth (1993) and fig-Forth. Gforth and PFE (by 3775: Dirk Zoller) will cross-fertilize each other. Of course, a significant 3776: part of the design of Gforth was prescribed by ANS Forth. 3777: 3778: Bernd Paysan wrote BigForth, a descendent from TurboForth, an unreleased 3779: 32 bit native code version of VolksForth for the Atari ST, written 3780: mostly by Dietrich Weineck. 3781: 3782: VolksForth descends from F83. It was written by Klaus Schleisiek, Bernd 3783: Pennemann, Georg Rehfeld and Dietrich Weineck for the C64 (called 3784: UltraForth there) in the mid-80s and ported to the Atari ST in 1986. 3785: 3786: Hennry Laxen and Mike Perry wrote F83 as a model implementation of the 3787: Forth-83 standard. !! Pedigree? When? 3788: 3789: A team led by Bill Ragsdale implemented fig-Forth on many processors in 3790: 1979. Robert Selzer and Bill Ragsdale developed the original 3791: implementation of fig-Forth for the 6502 based on microForth. 3792: 3793: The principal architect of microForth was Dean Sanderson. microForth was 3794: FORTH, Inc.'s first off-the-shelf product. It was developped in 1976 for 3795: the 1802, and subsequently implemented on the 8080, the 6800 and the 3796: Z80. 3797: 3798: All earlier Forth systems were custom-made, usually by Charles Moore, 3799: who discovered (as he puts it) Forth during the late 60s. The first full 3800: Forth existed in 1971. 3801: 3802: A part of the information in this section comes from @cite{The Evolution 3803: of Forth} by Elizabeth D. Rather, Donald R. Colburn and Charles 3804: H. Moore, presented at the HOPL-II conference and preprinted in SIGPLAN 3805: Notices 28(3), 1993. You can find more historical and genealogical 3806: information about Forth there. 3807: 3808: @node Word Index, Node Index, Origin, Top 3809: @chapter Word Index 3810: 3811: This index is as incomplete as the manual. Each word is listed with 3812: stack effect and wordset. 3813: 3814: @printindex fn 3815: 3816: @node Node Index, , Word Index, Top 3817: @chapter Node Index 3818: 3819: This index is even less complete than the manual. 3820: 3821: @contents 3822: @bye 3823:
http://www.complang.tuwien.ac.at/cvsweb/cgi-bin/cvsweb/gforth/Attic/gforth.ds?sortby=log;f=h;only_with_tag=MAIN;ln=1;content-type=text%2Fx-cvsweb-markup;rev=1.32
CC-MAIN-2021-17
refinedweb
19,098
59.53
I hearth BerkeleyPosted: April 10, 2010 Filed under: C++, Grumpy Leave a comment error: cannot convert ‘Db**’ to ‘DB**’ for argument ‘1’ to ‘int db_create(DB**, DB_ENV*, u_int32_t)’ Thank you very much, Oracle Berkeley, for having a type named Db and another one named DB, and for never using namespaces. It makes my work a much more interesting challenge (*). (*) Yeah, I know, Db is for the C++ wrapper and DB is for the plain C API (**). So what, I hate you all anyway. (**) I’m working on a project with Berekley DB and it has enough WTF moments for a complete blog… I may post some of them, as a catharsis method. (***) (***) Or because it has some interesting stuff too… who knows. Recursive note FTW (**). I think I have already done that, haven’t I? Advertisements
https://monoinfinito.wordpress.com/2010/04/10/657/
CC-MAIN-2017-39
refinedweb
136
80.01
Related Tutorial React.PropTypes Is Dead, Long Live PropTypes of React v15.5 PropTypes are deprecated in the React package and have been given a package of their own. Change is an inevitable part of life. The upshot is twofold. 1) If you use another type-checking mechanism, you don’t have to worry about shipping unnecessary bulk to your end users. Omit the import and bank the weight loss. 2) Your PropType declarations are going to be more svelte than you ever thought possible. The downside is that if you’ve been ignoring deprecation warnings about calling PropTypes directly since v15.3 (no judgement), that chicken has come home to roost. Let’s get into it, but first you’ll need to install the package in your project. - npm install prop-types --save Or, you know, do the Yarn thing. Either way here’s your old simple component with validation: import React from 'react'; function Detail ({caption, style}) { return <p style={style}>{caption}</p> } Detail.propTypes = { caption: React.PropTypes.string.isRequired, style: React.PropTypes.objectOf( React.PropTypes.string ), } export default Detail; And here it is the new way: import React from 'react'; import PropTypes from 'prop-types'; function Detail ({caption, style}) { return <p style={style}>{caption}</p> } Detail.propTypes = { caption: PropTypes.string.isRequired, style: PropTypes.objectOf( PropTypes.string ), } export default Detail; Actually, scratch that. We promised svelte; so give it a destructured spin like so: import React from 'react'; import {string, objectOf} from 'prop-types'; function Detail ({caption, style}) { return <p style={style}>{caption}</p> } Detail.propTypes = { caption: string.isRequired, style: objectOf( string ), } export default Detail; That, dear friends, is pretty as a picture, and the good news is it all works precisely like you’re used to. Warnings in development. Silence in production. The only notable exception is the one we mentioned above: directly invoked PropTypes. Those checks will automatically call the following block in production: var productionTypeChecker = function () { invariant(false, 'React.PropTypes type checking code is stripped in production.'); }; Throwing an error and breaking stuff. You’ll have to refactor those invocations in your code or work out your own fork of prop-types to keep them on the upgrade train. Whatever you do, don’t sweat this change. It’s a net gain with a mild inconvenience tax.
https://www.digitalocean.com/community/tutorials/react-the-new-proptypes
CC-MAIN-2020-34
refinedweb
382
60.41
IRC log of tagmem on 2002-04-15 Timestamps are in UTC. 14:03:56 [RRSAgent] RRSAgent has joined #tagmem 14:04:00 [Zakim] Zakim has joined #tagmem 14:04:33 [Ian] Ian has changed the topic to: TAG agenda: 14:09:12 [connolly] connolly has joined #tagmem 14:17:26 [Stuart] Stuart has joined #tagmem 14:22:39 [DanC] AAAAAAARGH! net problems. 14:23:47 [DanC] my ssh tunnel seems hosed. 14:26:59 [Stuart] Stuart has joined #tagmem 14:27:06 [Norm] Norm has joined #tagmem 14:29:39 [DanC] Zakim, this is tag 14:29:41 [Zakim] ok, DanC 14:30:29 [Zakim] +DanC 14:30:34 [Roy] Roy has joined #tagmem 14:31:18 [Zakim] +Ian 14:33:39 [Zakim] + +1.604.873.aaaa 14:33:52 [Ian] zakim, aaaa is TimBray 14:33:53 [Zakim] +TimBray; got it 14:34:22 [Ian] Missing so far: Chris, David, TimBL 14:34:51 [Zakim] +DOrchard 14:35:00 [Zakim] -TimBray 14:35:14 [Zakim] +TimBray 14:35:26 [Ian] PC: I will need to leave at some point during this meeting. 14:36:24 [Zakim] -Ian 14:36:39 [Dave] Dave has joined #tagmem 14:40:05 [Norm] Oh, the agenda will only help a little, Dan, but thanks 14:40:16 [Zakim] +Ian 14:41:27 [Ian] SW to Chair. 14:41:43 [Ian] ----------------- 14:41:46 [Ian] Minutes of previous meeting. 14:41:50 [Ian] SW: Accepted 14:41:55 [Dave] fine progress stu.. 14:42:02 [Ian] Agenda additions: None. 14:42:09 [Ian] Action item review: 14:42:11 [Dave] racing through the agenda... 14:42:16 [Zakim] +TimBL 14:42:35 [Ian] agenda+ Meetings without TimBL 14:43:05 [Ian] DO: Write text about "Web as information space", to be integrated by IJ 14:43:26 [tim-home] tim-home has joined #tagmem 14:43:52 [Ian] DO: Some stuff is controversial. 14:43:55 [Ian] IJ: then please continue 14:44:08 [Ian] Action IJ: Integrate/combine one-page summaries. 14:44:30 [Ian] IJ: Very slow progress on this. 14:44:56 [Ian] agenda+ One-page summary 14:45:43 [Ian] Action TBL: Write draft on when URI variants are considered equivalent 14:45:45 [Ian] Done, see www-tag 14:45:51 [DanC] done: 14:46:01 [DanC] $Id: Axioms.html,v 1.25 2002/04/08 18:05:07 timbl Exp $ 14:46:10 [Ian] Actino TBL: draft comments on RDF+HTML for namespace documents. 14:46:22 [Ian] TBL: there is a thread on this in www-tag. Would be good to capture this material. 14:46:34 [Ian] TBL: I started drafting something, discussion continued on www-tag. 14:46:49 [DanC] sounds like "some progress; continued" 14:47:01 [DanC] Stuart, pls move along 14:47:26 [Ian] Action DC: Write up summary of resolution for whenToUseGet-7 by showing support for RFC2616 section 9.1.1. 14:47:32 [Ian] see: 14:47:43 [DanC] my action: done: 14:48:18 [Dave] brb 14:48:20 [Ian] RF: Write up discussion of RFC3205 based on www-tag input. 14:48:22 [tim-home] is attempt to draft a resolution about HTML and RDF, but outstanding issue of fragid meaning is still left in discussion on ww-tag 14:48:37 [Ian] RF - pending. 14:48:47 [Ian] Action IJ: Create a separate page with links to TAG (accepted) findings. Done 14:48:59 [Ian] Action SW: Amend uriMediaType-9 finding according to approved text. 14:49:07 [Ian] Done. 14:49:11 [DanC] $Date: 2002/04/12 18:12:54 $ 14:49:16 [Ian] Action TBL: Take uriMediaType-9 finding to IETF. 14:49:23 [Ian] SW: Note that IANA is mentioned prominently. 14:49:29 [Ian] ...should take to their attention as well. 14:50:00 [Ian] TBL: I've brought up the IETF topic to Philipp Hoschka; next IETF teleconf not for another three months. 14:50:11 [Ian] ...maybe we should have an architectural get-together with the IETF> 14:50:31 [Ian] DC: Mail relevant parties (e.g., D. Eastlake). 14:50:44 [Dave] back 14:50:46 [Ian] TBL: Yes: IESG, W3C-IETF list, ... 14:50:58 [Ian] SW: What about Larry Masinter? 14:51:18 [DanC] I'd suggest uri@w3.org , Eastlake as next step for TimBL's action. 14:51:21 [Ian] TBL: LM asked for discussion to be carried out on "xml in ietf list" 14:51:31 [Ian] TBL, TB: That's problematic. 14:51:40 [DanC] er... there's supposed to be a URI CG in W3C sometime soon, btw. (oops) 14:52:07 [Ian] TBL: I will respond to LM about this; we'd like this discussion on www-tag since we don't have anyone to follow it on IETF list. 14:52:14 [Roy] what is a CG? 14:52:16 [DanC] "about this" <- about which? 14:52:34 [Ian] About moving discussion to IETF list. 14:52:39 [Ian] ---------------- 14:52:41 [DanC] CG = coordination group. in the case of URI, a group to say "who should do that? ok; I'll do it." 14:52:44 [Ian] www-tag mailing list policy 14:52:58 [Ian] TB: Post agenda to www-tag and ask people to focus on these issues. Let's try that for a while. 14:53:19 [Ian] SW: Also, we should prioritize issues. 14:53:45 [Ian] (see SW email to tag list) 14:54:06 [Ian] TBL: TOC of arch doc was to be clustering. 14:54:14 [Ian] DC: Sounds like SW's clustering and the TOC line up. 14:55:18 [DanC] pls put some issue names/numbers in the subject line when you send agendas to www-tag 14:55:32 [tim-tag] q? 14:55:35 [Ian] DO: I'm not sure that this will prevent loquacious people from saying what they want to say. 14:55:59 [Ian] TBL: I think we should do what TB said, but also respect www-tag as a place where people raise issues. 14:56:28 [Ian] ...I hear SW saying "let's spend more time on dispensing with issues" but let's not close ears to new ones. 14:56:43 [DanC] "loquacious"? did DO really use that word? what does it mean? 14:56:57 [Ian] TBL: I hear SW proposing more organized stacking of agenda items. 14:57:15 [Ian] PC: One reason we're getting flooded with mail is that we're doing technical design. 14:57:26 [Ian] (e.g., on the nature of a namespace document) 14:57:52 [Ian] ...after enough pointers from people, I thought that this was starting to feel like a technical working group. 14:58:10 [Ian] ...but I think that writing principles has a higher priority. 14:58:27 [Ian] ...we might ask w3c to assign job of implementing to appropriate WGs. 14:58:52 [Stuart] q? 14:58:53 [Ian] DC: I am of two minds on this: On the one hand, I don't know that we need to cross all the t's, but if we don't, people will keep asking us for it. 14:59:30 [Ian] TBL: We have gotten a few principles along the way, even in discussing nature of namespace docs. 14:59:40 [Ian] PC: I don't think we have as much agreement as TBL things. 14:59:44 [Ian] NW, DO: I agree with PC. 14:59:54 [Ian] TB: I'm surprised, I thought we were converging on this. 15:00:10 [DanC] if we're not agreed (that you should put *something* there, at the end of a namespace pointer), I'm willing to spend whatever time it takes to get agreement. 15:00:38 [Ian] PC: I would prefer if TAG stayed at requirements level rather than design level. 15:02:12 [Dave] My requirement is that the xhtml must be human-writable 15:02:24 [Ian] PC: I agree that many of us agree that there could be a namespace doc at end of namespace, some votes are conditional on the nature of the document. 15:02:26 [Dave] q+ 15:02:37 [Ian] PC: I'm suggseting that the TAG doesn't need necessarily to resolve that. 15:03:14 [Ian] TB: I think that at our level of operation, distinction between arch and design goes away. I don't believe in the model where we do principles and hand off design to others. 15:03:56 [Ian] DO: I am sensitive to PC's point - if we act as a WG, we will get less done on principles. But I agree that in this case (namespace docs) my final view depends on syntax. 15:04:36 [Ian] DO: I'm not decided on whether we should do this work. 15:04:41 [Zakim] -??P27 15:05:13 [Ian] DO: This issue of the namespace is helping us figure out our process. 15:05:18 [Ian] q? 15:05:21 [tim-tag] q+ 15:05:22 [Ian] ack Dave 15:05:36 [Zakim] +??P43 15:05:55 [Ian] zakim, ??P43 is Paul 15:05:56 [Zakim] +Paul; got it 15:05:59 [Ian] ------------------------] 15:06:06 [Ian] DC: I wrote something on when to use get 15:06:23 [Ian] ------------------ 15:06:39 [Ian] Back to issue (briefly) of how to organize meetings when TBL not here. 15:06:46 [Ian] TB: I nominate SW as backup chair. 15:07:13 [Dave] lol 15:07:15 [Ian] SW: If I'm here, I'm willing to Chair. 15:07:20 [Norm] lol 15:07:37 [DanC] DRAFT Findings on Safe Methods 15:07:54 [Ian] [Back to tech] 15:09:16 [Ian] DC reads first couple of paragraphs. 15:09:23 [Ian] DC: How close to agreement on first couple of paragraphs? 15:09:29 [Ian] "A very important principle when designing Web applications is: 15:09:30 [Ian] * safe methods (GET/HEAD) should be used for safe operations: read, query, view, ask, lookup 15:09:30 [Ian] * safe methods must not be used for unsafe operations: write, update, modify, tell, buy, agree 15:09:30 [Ian] " 15:09:42 [Ian] DO: I have a concern about the word "should" instead of "may" in first bullet. 15:10:05 [Ian] ...how does this relate to Web services world and the use of POST with SOAP messages. 15:10:09 [Ian] DC: Don't do that is my answer. 15:10:21 [Stuart] q? 15:10:43 [Ian] DO: In the Web services world, it's a well-documented "fact" that most uses of SOAP messages are through POST. E.g., classic get stock quote is done through POST. 15:10:55 [Ian] ...POST is used to navigate shared something space. 15:11:16 [DanC] the use of POST for "get stock quote" is wrong. 15:11:26 [Ian] RF: Yes, it's wrong. 15:11:41 [Ian] TB: People have been using POST for years due to large lists of arguments. But you can't bookmark as a result. 15:11:53 [Ian] ...when you can do it with GET, you should do so, and that adds to the utility of it. 15:12:03 [Ian] ...utility of Web services would be increased by use of GET. 15:12:19 [Ian] ack Tim-tag 15:12:54 [Ian] TBL: I propose we ask DO to take this message back to the Web services community: tools creating services need to help designer make choice that end up with proper implementation. 15:13:06 [Ian] DO: I don't agree that the way that Web services work is the wrong way to do it. 15:13:10 [Ian] q? 15:13:13 [Ian] q+ 15:13:47 [Ian] PC to TBL: One of the problems with this sort of design is that it presupposes that you know what kind of message you will be sending. 15:13:56 [Ian] ...in SOAP 1.2, one doesn't know about the messages. 15:14:10 [Ian] TBL: We're talking about changing the situation, not just observing the current state of the spec and software. 15:14:32 [Ian] PC: Are specs factored correctly for one to be able to carry out this chore. 15:15:00 [Stuart] q? 15:15:00 [Ian] TBL: If WSDL does not capture whether there's a safe method, that's a bug. 15:15:02 [Dave] q+ 15:15:21 [Roy] q+ 15:15:26 [Ian] PC: SOAP 1.2 has been written without knowing that WSDL exists. 15:15:35 [Ian] TBL: Then it needs to go into SOAP and possibly other things. 15:15:42 [Ian] PC: What does HTTP binding use today in SOAP? 15:15:44 [Ian] DO: POST> 15:15:47 [DanC] hmm... how would it go into the SOAP 1.2 spec? 15:16:09 [Dave] DanC, the SOAP HTTP binding in part 2 uses POST 15:16:20 [Ian] IJ: What are DO's objections to using GET in the Web services context? 15:16:43 [TBray] TBray has joined #tagmem 15:16:52 [Stuart] q? 15:16:54 [Ian] DO: I do not believe that the way that Web services groups are moving forward is incorrect. 15:17:08 [Ian] DO: ...I'm not prepared to go to them and say that what they are doing is wrong. 15:17:22 [DanC] DaveO, pls answer Ian's question: what's wrong with the principle that "* safe methods (GET/HEAD) should be used for safe operations: read, query, view, ask, lookup"? 15:17:36 [Ian] DO: I don't think that idempotency has come up in web services activity. The way to move forward is to have a mtg with the web services arch wg. 15:18:03 [Ian] DO: I'm suggesting that this is a bigger issue than DC's one line. 15:18:11 [Ian] DC: But in what way do you disagree? 15:18:29 [Ian] DO: It gets into the shared information space. If you're dealing with the shared information space, you care whether the info is idempotent or not. 15:18:42 [Ian] ...when you are doing things from a service perspective, or shared processing space, that feature becomes less important. 15:18:52 [tim-tag] q+ 15:19:05 [Ian] DO: ...I would argue that from a web services developer perspective, it's unduly complicated. 15:19:06 [Ian] ack Ian 15:19:07 [Ian] ack Dave 15:19:08 [Dave] q- 15:19:43 [Ian] RF: The way that web services is designed, there is no generic interface. So there is no concern about safe or unsafe methods. In general they don't have methods in the web services space. 15:20:04 [Ian] RF: SOAP should not be tunneled over HTTP. 15:20:09 [TBray] q+ 15:21:26 [Ian] RF: The point is that web services space doesn't deal with methods at all at this point because when you're operating via a web service, both sides know the semnatics of the service, or they don't interoperate at all. Whether GET/HEAD/POST is only relevant for the HTTP transfer mechanism (for tunneling of web services) and this is not HTTP-compliant to begin with and should not be done. 15:21:36 [Ian] RF: So this is a non-issue whether you take this to Web services groups or not. 15:21:42 [Ian] q? 15:21:46 [Ian] ack Roy 15:22:17 [Ian] TBL: When there is an object that is a service that is in HTTP space, POST is there to submit things to it. To submit an operation to is it reasonable. 15:22:24 [Ian] ..there is a loss when the operation is just a read of the space. 15:22:33 [Ian] ...I see this loss all the time when I interact with my bank. 15:22:49 [Ian] ...I can't use the back button since the browser keeps warning me that I"m resubmitting the post. 15:22:54 [Ian] ..it's more work on the bank server as well. 15:23:09 [Ian] ...it's inefficient from everyone's point of view (user, network, server). 15:23:23 [Ian] ..that mistake is being transferred into web services. 15:23:32 [Ian] ...web services are still young; the effect on the web has not been seen. 15:23:48 [Dave] q+ 15:24:16 [Ian] TBL; ..I disagree with RF that you should never submit information to a service with POST. But I think we need to encourage web services to split information into safe and unsafe bits. 15:24:43 [Ian] TBL: I think we should go to the Web services community and get a change. 15:24:55 [Ian] RF: I don't think we disagree, TBL. 15:25:19 [Ian] TBL: The web services people can keep the web services model, but the bindings should be safe when they can be. 15:25:25 [Ian] ...use the underlying/existing caches, etc. 15:25:38 [Ian] TB: RF said that you shouldn't run SOAP over HTTP. Well, they're going to. 15:25:50 [Ian] RF: Intermediaries will break when it happens. 15:26:00 [Ian] TB: So it's appropriate for us to make architectural assertions about this. 15:26:07 [Stuart] ack tim-tag 15:26:11 [Ian] TB: I agree with TBL that there's a right way and wrong way to do this. 15:26:15 [Ian] TB: I think that: 15:26:19 [Stuart] ack tbray 15:26:27 [Ian] TB: 1) It's appropriate to say you should use GET. 15:26:42 [Ian] TB: 2) It's also appropriate for wsa people to consider this. 15:27:27 [Ian] TB: I look forward to a future where one can put a URI to a web service in a web page. If GET is never used, we may not have this much more interesting web. 15:27:47 [Ian] TB: So I support "Should use get" and work with Web services community to take advantage of what web offers. 15:28:01 [Ian] DO: I could live with "GET should be used for browser-centric sort of things." 15:28:03 [tim-tag] q+ 15:28:11 [Ian] DO: I take issue with "GET should be used in all areas". 15:28:14 [Ian] ack Dave 15:28:16 [DanC] Norm, "brower centric" is beside the point. 15:28:20 [DanC] s/norm,/no,/ 15:28:43 [TBray] My point 3: Web Services people may feel they don't have an issue here because it's all machine-to-machine, and the "client" program will know what's going on. 15:29:08 [Ian] TBL to DO: Would you be willing to lead a charge in the web services community to set up the job about what would need to be changed, and who would need to be involved, to introduce the idea of binding SOAP to GET. 15:29:34 [TBray] But I disagree - in a future with a much more programmable brower, I think it would be interesting and good to have a pointer from a human-readable web page to a web service. 15:29:41 [Ian] DO: I disagree with the position, but will be happy to organize a liaison. 15:29:42 [TBray] And in that mode, GET is definitely the way to go. 15:30:02 [Ian] PC: One way to execute what TBL would like is to have the TAG review the SOAP 1.2 spec. 15:30:07 [Ian] (last call imminent?) 15:30:42 [Ian] TB: What's current status of SOAP 1.0? 15:30:53 [Stuart] q+ 15:30:56 [Ian] DO: We're a couple of weeks from going to last call. 15:31:12 [Ian] PC: Yes, a couple of weeks from last call. 15:31:13 [Ian] q? 15:31:17 [Ian] ack Tim-tag 15:31:20 [DanC] I can see how to put this into the WSDL spec, but not so much the SOAP spec. 15:32:04 [Ian] SW: I have been wrestling internally with these issues. I can see the merit of GETs for safe operations. 15:32:25 [Ian] SW: I can see that when you are uncertain, POST may not be a bad choice. [SW acks thinking on the fly here...] 15:32:50 [Ian] SW: There has been a tension since creation of WG between SOAP having character of thing it's bound to, or thing with character of its own. 15:33:02 [Ian] SW: I've been wrestling with tunneling issues. 15:33:19 [Ian] SW: I can see a view that "SOAP is just a content format [that you can use with HTTP]" 15:33:27 [Ian] q? 15:33:33 [Ian] ack Stuart 15:33:48 [Stuart] q- 15:34:00 [Ian] RF: We should tease out the principles in the findings. What TBL wants is an indication of the semantics of the action visible to all participants before the action is made. 15:34:28 [tim-tag] q+ 15:34:30 [Ian] RF: A client may need to know whether an operation is safe in order to execute the action. Same with proxy. 15:34:45 [Ian] RF: That's independent of HTTP (or HTTP method used). 15:34:58 [Ian] TBL: I want to push back on the idea that HTTP GET only applies to browsers. 15:35:07 [Ian] TBL: ...it applies even more to an agent. 15:35:19 [Ian] TBL: When a piece of software will click on a link, will be done without the user's oversight. 15:36:02 [Ian] TBL: The way that web services is working (services between different companies across trust boundaries) is different from rpc; you want to keep a record of transactions. 15:36:17 [Zakim] -Paul 15:36:29 [Ian] TBL: I think that this principle applies absolutely to clients acting on a user's behalf. 15:37:05 [Ian] TB: I think we should send a message to web services that we have a concern here. 15:37:05 [DanC] where to go next: I suggest actions be assigned to anybody who disagrees with "* safe methods (GET/HEAD) should be used for safe operations: read, query, view, ask, lookup" 15:38:00 [Ian] DC: I heard a majority in favor of "should/must not". I suggest that whoever disagrees has the ball to follow up. 15:38:46 [Ian] TB: I suggest to post DC's finding to www-tag with "should/must not". 15:39:06 [DanC] why spell-check it? wouldn't that give the impression that it's more done than it is? 15:40:11 [Ian] SW: I think we should wait a week, and get some more discussion, before trying to get consensus around this. 15:40:19 [Ian] DC: Then I shouldn't say to www-tag that "most people agree with this"? 15:41:48 [Ian] TBL: Let the meeting record show that we do not have consensus on DC's proposal. 15:42:02 [Ian] agenda? 15:42:30 [Ian] --------------------------- 15:42:51 [Ian] Postponed: * IETF best practices draft requiring URNs for XML namespaces in IETF documents. Action to take? 15:43:12 [Ian] --------------- 15:43:30 [Ian] Postponed: 1. Discuss issue of scope of TAG/W3C/Web Architecture (@@see TB Action below@@). 15:43:31 [Ian] ----------------- 15:43:34 [Ian] 1. Discussion of integration of 5 one-page summaries: 15:43:38 [Ian] 15:44:05 [Ian] TBL: Plese do homework on postponed items. 15:44:19 [Ian] Action IJ: Ensure that TAG has links to these items. 15:44:34 [Ian] TB on IJ style: Good but too much of it. 15:44:43 [Ian] q+ 15:44:52 [DanC] btw... last week's record had my whenToUseGet action due today, 15 Apr; I did it by 15Apr, but it didn't seem to be in time. I'd suggest actions be due weds or maybe Thu 15:44:53 [Ian] TB: There's a sweet spot in-between. 15:45:37 [DanC] Bray, I don't think Ian has written anything newer than what you've seend. 15:45:52 [DanC] (er... I haven't seen anything newer, that is) 15:46:20 [Ian] IJ: Expect fuzziness at first, then some will be pared away. 15:46:33 [Ian] TB: Each word carries serious normative weight. Keep the verbiage down. 15:46:43 [Norm] q+ 15:48:24 [Ian] q- 15:48:29 [Ian] ack Tim-tag 15:48:45 [Ian] NW: I think that TB's point is well-taken. Words will be scrutinized. 15:49:46 [DanC] re appendix: pls no. pls let's find whatever balance is the right balance 15:50:09 [Ian] IJ: By the way, I support TB's point as well. Working towards it. 15:50:37 [Ian] TBL: The doc consists of the four areas of web arch with a prepending introduction. 15:51:01 [Ian] No worries, NW! 15:51:01 [Ian] :) 15:51:18 [TBray] I think something like what Ian's written needs to be written... I'm just not sure this is the right place for it. 15:51:25 [Norm] lol 15:51:41 [DanC] draft on whenToUseGet is now sent to www-tag 15:52:24 [Ian] RF: I think that this doc will ultimately have different outline than four chapters we have now. I'm happy to start this way. 15:52:51 [Ian] IJ: But I'm writing the intro based on these chapters... 15:53:54 [Ian] TBL: I thought that 3 wasn't about summarizing REST. But more about how the protocols implement the information space. Role of chapter 4 is to talk about the services as such. 15:54:00 [DanC] er... the chapters 1-4 are completely empty in $Date: 2002/04/01 14:33:41 $ 15:54:11 [TBray] Sorry... gotta run. 15:54:28 [Ian] RF: I thought 3 would describe the application state of portraying the hypertext view of the world. 15:54:31 [Ian] DC: I agree. 15:54:34 [Zakim] -TimBray 15:54:51 [Ian] RF: I have a hard time speaking to the four chapters. 15:55:02 [Ian] RF: I'm not entirely sure that docs come second. 15:55:13 [Ian] RF: I'm sure that we'll talk about properties we want out of a web arch. That's not there now. 15:55:32 [Ian] RF, DC: Put the stuff in and see what happens. 15:55:48 [Ian] DC: Anything less than words we agree to won't get us what we want. 15:56:00 [Stuart] q? 15:56:22 [Ian] TBL: I don't think that section 3 as elaborated will fulfill the role I have in mind. 15:56:28 [Ian] RF: I agree with TBL. It doesn't fit. 15:56:56 [Norm] q- 15:59:33 [Ian] [IJ, RF, TBL will try to meet to get direction on Ch. 3] 16:00:43 [Ian] ADJOURNED 16:00:54 [Zakim] -??P29 16:00:55 [Zakim] -??P28 16:00:57 [Ian] RRSAgent, stop
http://www.w3.org/2002/04/15-tagmem-irc
CC-MAIN-2015-06
refinedweb
4,584
81.93
User account creation filtered due to spam. Created attachment 29823 [details] Use the D format specifie for ashqs second arg The documentation for VAX operand formatting codes says: D 64-bit immediate operand and: /* The purpose of D is to get around a quirk or bug in vax assembler whereby -1 in a 64-bit immediate operand means 0x00000000ffffffff, which is not a 64-bit minus one. */ However, the ashq instruction patters do not use this properly. This small test program triggers it: #include <stdio.h> #include <inttypes.h> int main(int argc, char **argv) { size_t i; uint64_t v, nv; for (i = 0; i < 16; i++) { v = ~(uint64_t)0 << i; nv = ~v; printf("%zu: mask %08llx not %08llx\n", i, v, nv); } return 0; } The relevant line from assembly: ashq %r6,$-1,%r2 which is misinterpreted by the assembler, so dissasembly is: 10637: 79 56 8f ff ashq r6,$0x00000000ffffffff,r2 1063b: ff ff ff 00 1063f: 00 00 00 52 The attached patch fixes it. The `gas' bug seems to only show up on 32bit host platform. Creating a cross-gas on a amd64 systems seems to always result in "correct" VAX binary output, even for old 2.21 releases. (Will further check this.) I tend to not fix GCC in this regard. Its output is correct, though doing hex output instead of negative decimals would work-around gas's bug. However, I think we'd better fix gas and possibly add a version check to gcc? This is gas's tc-vax.c: 3158 if ((is_absolute) && (expP->X_op != O_big)) 3159 { 3160 /* If nbytes > 4, then we are scrod. We 3161 don't know if the high order bytes 3162 are to be 0xFF or 0x00. BSD4.2 & RMS 3163 say use 0x00. OK --- but this 3164 assembler needs ANOTHER rewrite to 3165 cope properly with this bug. */ 3166 md_number_to_chars (p + 1, this_add_number, 3167 min (sizeof (valueT), 3168 (size_t) nbytes)); 3169 if ((size_t) nbytes > sizeof (valueT)) 3170 memset (p + 1 + sizeof (valueT), 3171 '\0', nbytes - sizeof (valueT)); 3172 } [...] This is for "small" values (ie. "-1" fitting in a 32bit valueT) and it doesn't properly sign-extend in this case. Taking into account the next couple lines (not shown here), this part of the code needs to rethought. A workaround would be to actually place an all-hex value (through GCC) here, but that wouldn't fix gas for any hand-written assembler. Of course I do not mind fixing gas, but the whole point of the "D" formatting code is to work around this assembler bug, and while this might be mostly irrelevant nowadays, isn't gcc supposed to work with other assemblers (like the VMS one) as well? Gas seems to be "bug-compatible" here. Overall, especially since this change is trivial, wouldn't it be best/easiest to apply it anyway? You're quite right, Martin! It's a simple fix on the GCC side working around a buggy gas, and it would also work with a fixed gas. However, gas isn't too simple to fix, at least not with a well-architected fix. Created attachment 30872 [details] Updated patch including testcase. Author: jbglaw Date: Fri Sep 20 19:00:02 2013 New Revision: 202796 URL: Log: Work around buggy gas not properly sign-extending a 64bit value on a 32bit host PR target/56875 2013-09-20 Martin Husemann <martin@NetBSD.org> Jan-Benedict Glaw <jbglaw@lug-owl.de> gcc/ * config/vax/vax.c (vax_output_int_move): Use D format specifier. * config/vax/vax.md (ashldi3, <unnamed>): Ditto. gcc/testsuite/ * gcc.target/vax/vax.exp: New. * gcc.target/vax/pr56875.c: Ditto. Added: trunk/gcc/testsuite/gcc.target/vax/ trunk/gcc/testsuite/gcc.target/vax/pr56875.c trunk/gcc/testsuite/gcc.target/vax/vax.exp Modified: trunk/gcc/ChangeLog trunk/gcc/config/vax/vax.c trunk/gcc/config/vax/vax.md trunk/gcc/testsuite/ChangeLog fixed on trunk
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=56875
CC-MAIN-2017-04
refinedweb
652
64.71
GET STARTED DEVELOPING FOR WINDOWS 8 WINDOWS PHONE AZURE WITH APP BUILDER Many. Setting up your environment requires a number of steps. Bob Familiar has done an excellent job documenting the setup of the environment in this blog post – [ ]. After completing the steps documented you should have a new template available in Visual Studio 2012 for a MonoGame Metro Application.. using Microsoft.Xna.Framework.Audio; LOADCONTENT(); } } Hit F5 / Debug go and run the app to the local machine or the simulator. The boxes should bounce off the walls and make a ding when they cross. Stop the debugger when you wish to stop the app, or hit Alt-F4.?
http://blogs.msdn.com/b/devfish/archive/2012/09/15/how-to-create-your-first-xna-monogame-framework-application-for-windows-8-metro-ported.aspx
CC-MAIN-2014-10
refinedweb
109
64.71
Soon after I announced the release of gupnp-tools/av, someone pointed out that libsoup-2.4 is already out and therefore gssdp and gupnp needs to be ported to the new API. I am already done with the porting of gssdp and most of the gupnp (thanks to Dan Winship for being so helpful) but then came the shock: the SOAP support has suddenly been dropped from libsoup. I blamed my ignorance on me not being subscribed to libsoup ML so I started to dig into the archives but failed to find any mention of this change. I know how to solve this issue and I am sure Dan will help me out in this one as well but IMO APIs should be deprecated first and then removed in the next major release. 5 comments: I had exactly the same. I was using the libsoup SOAP support in a yet unannounced project when it was suddenly dropped. To fix it, I wrote a very small SOAP client myself that could do the things I needed. It's just a bunch of headers (so no full blown library), but they are C++. Ping me if you want to have a look at them, then I'll release those. - uwog This is from the porting guide: SOAP SOAP support has been removed; the existing methods covered only a teeny tiny subset of SOAP, which was really only useful to a single application. (The code that was formerly in libsoup has been moved to that application.). If you were using this code, you can resurrect a libsoup-2.4-compatible version of it from revision 1016 of libsoup svn. Thanks but i had already read that before writing this blog entry, in fact thats where i came to know of this. I truely appreciate it that they put it in the docs but: 1. "only useful to a single application" part is not true at all (GUPnP relying on it and uwog's comment is enough proof against it) and I don't see any attempt of to finding out how many projects rely on it from the developers. 2. My main point was that the API should first have been deprecated and then removed. It's true that I didn't discuss/announce this anywhere, but I did google around a lot (looking both for people talking about it, and using Google code search to try to find people actually using it), and I didn't find anything. (I guess google code search is not very reliable; it still doesn't turn up gupnp when searching for "soup_soap_message_new".) Compare this to google code-searching for "soup_xmlrpc_message_new", which gets hits in several different projects despite the fact that the libsoup SOAP API had been around for 4 years and the XML-RPC API only 1.5 years. This seemed to back up my feeling that the existing API was "only useful to a single application" (and even then, evolution-groupwise had a whole set of additional SOAP helper utilities built on top of libsoup's, because libsoup's were too low-level). As for deprecating it, there didn't seem to be any point, since AFAICT, it was only being used by evolution-groupwise, and as Olafur pointed out, if you really want the old code, you can just copy and paste it into your new app (and then make whatever customizations would actually make it more useful to you). And there isn't likely to be another ABI break any time soon, so "deprecate and then remove" would basically have turned into "deprecate and then keep forever anyway". Whereas taking advantage of the 2.4 ABI break to get rid of the old SOAP API opens up the soup_soap_* namespace, leaving open the possibility of adding a better SOAP API in the future (if that's useful to libsoup's users). (BTW, the other reason there wasn't much public discussion of libsoup 2.4 before it happened was because I assumed I wasn't actually going to finish it... :-) I'd been trying to find the time to do this stuff since GNOME 2.14, and it kept not happening.) Thanks for the explanation Dan and I understand why you decided to drop the API rather than deprecating it. However, I wouldn't rely on google search to see which projects are using a particular API of my library. To very least, an announcement on mailing-list would been a good idea, although it wouldn't have made any difference for me but i think Jorn is subscribed to it.
http://zee-nix.blogspot.com/2008/04/soap-dropped-from-libsoup.html
CC-MAIN-2017-34
refinedweb
770
65.86
- Attach a device to the system, or resume it #include <sys/ddi.h> #include <sys/sunddi.h> int prefixattach(dev_info_t *dip, ddi_attach_cmd_t cmd); Solaris DDI specific (Solaris DDI) A pointer to the device's dev_info structure. Attach type. Possible values are DDI_ATTACH and DDI_RESUME. Other values are reserved. The driver must return DDI_FAILURE if reserved values are passed to it. The attach(9E) function is the device-specific initialization entry point. This entry point is required and must be written. The DDI_ATTACH command must be provided in the attach(9E) entry point. DDI_ATTACH is used to initialize a given device instance. When attach(9E) is called with cmd set to DDI_ATTACH, all normal kernel services (such as kmem_alloc(9F)) are available for use by the driver. Device interrupts are not blocked when attaching a device to the system. The attach(9E) function is called once for each instance of the device on the system with cmd set to DDI_ATTACH. Until attach(9E) succeeds, the only driver entry point which may be called is getinfo(9E). See the Writing Device Drivers for more information. The instance number may be obtained using ddi_get_instance(9F). At attach time, all components of a power-manageable device are assumed to be at unknown levels. Before using the device, the driver needs to bring the required component(s) to a known power level. The pm_raise_power(9F) function can be used to set the power level of a component. This function must not be called before data structures referenced in power(9E) have been initialized. The attach() function may be called with cmd set to DDI_RESUME after detach(9E) has been successfully called with cmd set to DDI_SUSPEND. When called with cmd set to DDI_RESUME, attach() must restore the hardware state of a device (power may have been removed from the device), allow pending requests to continue, and service new requests. In this case, the driver must not make any assumptions about the state of the hardware, but must restore the state of the device except for the power level of components. If the device driver uses the automatic device Power Management interfaces (driver exports the pm-components(9P) property), the Power Management framework sets its notion of the power level of each component of a device to unknown while processing a DDI_RESUME command. The driver can deal with components during DDI_RESUME in one of the following ways: If the driver can determine the power level of the component without having to power it up (for example, by calling ddi_peek(9F) or some other device-specific method) then it should notify the power level to the framework by calling pm_power_has_changed(9F). The driver must also set its own notion of the power level of the component to unknown. The system will consider the component idle or busy based on the most recent call to pm_idle_component(9F) or pm_busy_component(9F) for that component. If the component is idle for sufficient time, the framework will call into the driver's power(9E) entry point to turn the component off. If the driver needs to access the device, then it must call pm_raise_power(9F) to bring the component up to the level needed for the device access to succeed. The driver must honor any request to set the power level of the component, since it cannot make any assumption about what power level the component has (or it should have called pm_power_has_changed(9F) as outlined above). As a special case of this, the driver may bring the component to a known state because it wants to perform an operation on the device as part of its DDI_RESUME processing (such as loading firmware so that it can detect hot-plug events). The attach() function returns: Successful completion Operation failed See attributes(5) for descriptions of the following attributes: cpr(7), pm(7D), pm(9P), pm-components(9P), detach(9E), getinfo(9E), identify(9E), open(9E), power(9E), probe(9E), ddi_add_intr(9F), ddi_create_minor_node(9F), ddi_get_instance(9F), ddi_map_regs(9F), kmem_alloc(9F), pm_raise_power(9F)
https://docs.oracle.com/cd/E23823_01/html/816-5179/attach-9e.html
CC-MAIN-2019-51
refinedweb
670
51.78
05-08-2017 04:29 PM See attached file. The two planar faces work fine. But UF_MODL_ask_face_type (same with UF_MODL_ask_face_data) returns "toroidal" for the type of the revolved spline face. Is this expected behavior? For what it's worth, it appears that coercing the toroidal face to a spline using UF_MODL_extract_face seems to give a correct B-surface. This is expensive, so I do not want to do it for all surfaces that claim to be toroidal. How do I know which cases are the bad ones? 05-08-2017 09:19 PM In this case, NX did not make the surface toroidal (though it will, if it can). The interactive Info-->Object function correctly identifies the surface type as "Revolved". I think there's something wrong with the UF_MODL_Ask_Face functions, or the set of constants used as type codes. I don't know exactly what the problem is, but I found some old code of mine that contained a bizarre workaround. In that code, when I encounter a surface that is claimed to be toroidal, I read the minor radius. If that minor radius is zero, then I conclude that the "toroidal" claim is a lie, and the surface is actually of type "Revolved". I realize that this is a pretty vague answer, but maybe it points you in the right direction. If you can isolate the problem, please send in a PR. 05-08-2017 09:45 PM - edited 05-08-2017 11:38 PM SNAP gets the right answers, and SNAP is just calling NX/Open functions, so there must be a way. Using this code: public class NXJournal { public static void Main() { foreach(var body in Snap.Globals.WorkPart.Bodies) { foreach(var face in body.Faces) Snap.InfoWindow.WriteLine(face.ObjectSubType.ToString()); } } } I got the following results for your model: FacePlane FaceRevolved FacePlane Here is what I did in some old code: myType = myFace.SolidFaceType; if (myType == NXOpen.Face.FaceType.SurfaceOfRevolution) { double minorRadius = GetSurfaceRadii(myFace)[1]; if (minorRadius != 0) myType = NX.ObjectTypes.SubType.FaceTorus; else myType = NX.ObjectTypes.SubType.FaceRevolved; } 05-08-2017 10:15 PM It may be off interest why NX still call the face toriodal. The image below shows the poles for the revolved face. Note that it is treating as having a major radius and two minor radii instead of the traditional major and single minor radius. Frank Swinkels 05-08-2017 10:29 PM I should mention that Nx can treat this like a toriod only because the spline has the correct number of poles (4 poles which is what is used for a standard torus. I am not saying that we have two radii. Frank Swinkels 05-08-2017 10:37 PM This seems to work: public class NXJournal { public static void Main() { var workPart = NXOpen.Session.GetSession().Parts.Work; foreach(NXOpen.Body body in workPart.Bodies) { foreach(NXOpen.Face face in body.GetFaces()) Snap.InfoWindow.WriteLine(face.SolidFaceType.ToString()); } } }
https://community.plm.automation.siemens.com/t5/NX-Programming-Customization-Forum/Revolved-spline-says-its-surface-type-is-a-torus/td-p/407755
CC-MAIN-2018-39
refinedweb
490
66.03
Overview of AJAX AJAX has definitely been the hot buzzword in the Web application world for the last few years. AJAX is an acronym for Asynchronous JavaScript and XML and, in Web application development, it signi - fies the capability to build applications that make use of the XMLHttpRequest object. The creation and inclusion of the XMLHttpRequest object in JavaScript and the fact that most upper- level browsers support it led to the creation of the AJAX model. AJAX applications, although they have been around for a few years, gained popularity after Google released a number of notable, AJAX-enabled applications such as Google Maps and Google Suggest. These applications demon - strated to the world the real value of AJAX, and every developer that saw these applications in action immediately went out to do research in how these applications were built. AJAX is now an out-of-the-box feature of ASP.NET 3.5, and every ASP.NET application that you build is AJAX-enabled by default. This means that you don’t have to create a separate AJAX project for your Web applications as the standard projects in Visual Studio for Web applica - tion development will already be enabled to use ASP.NET AJAX. This is one of the main new features of ASP.NET 3.5 because of the power that AJAX brings to your applications. The AJAX capability has become so popular since the release of ASP.NET 3.5 that most ASP.NET applica - tions built today make use of at least some features provided by this technology. Why AJAX Applications Are Needed Web applications were in a rather stagnant state for many years. The first “Web” applications were nothing more than text and some images, all represented in basic HTML tags. However, this wasn’t what people wanted; they wanted more — more interactivity, a more integrated workflow, more responsiveness, and an overall richer experience. When building applications, even today, you have to make some specific decisions that really end up dictating the capabilities and reach of your application. Probably one of the more important decisions is the choice of building the application as a “thin” client or a “thick” client. 1 92171c01.indd 1 12/15/08 1:44:51 PM 2 Chapter 1: Overview of AJAX A thick client application is a term used for applications that are either MFC (in the C ++ world) or Windows Forms applications. These types of applications also provide the container along with all the container contents and workflows. A thick client application is typically a compiled executable that end users can run in the confines of their own environment, usually without any dependencies elsewhere (for example, from an upstream server). A thin client application is the term generally used for Web applications. These types of applications are typically viewed in a browser, and your application can provide end user workflows as long as it is contained within this well-known container. A thin client application is one whose processing and ren- dering are controlled at a single point (the upstream server), and the results of the view are sent down as HTML to a browser to be viewed by the client. Typically, a Web application is something that requires the end user to have Internet access in order to work with the application. On the other hand, a thick client application was once generally considered a self-contained application that worked entirely locally on the client’s machine. However, in the last few years, this perception has changed as thick clients have evolved into what are termed “smart clients” and now make use of the Internet to display data and to provide workflows. Web applications have historically been less rich and responsive than desktop applications. End users don’t necessarily understand the details of how an application works, but they know that interacting with a Web site in the browser is distinctly different from using an application installed locally. Web applications are accessible from just about any browser, just about anywhere, but what these browsers present is limited by what you can do with markup and script code running in the browser. There are definitely pros and cons in working with either type of application. The thick client applica- tion style is touted as more fluid and more responsive to an end user’s actions. Thick client applications require that users perform an installation on their machine but let developers leverage the advanced mouse and graphics capabilities of the operating system that would be extremely difficult to implement in a Web browser, and also take advantage of the user’s machine for tasks such as offline storage. Conversely, the main complaint about Web applications for many years has been that every action by an end user typically takes numerous seconds and results in a jerky page refresh. Conversely, Web applications can be updated just by changing what is running on the server, and site visi- tors get the latest version of that application instantaneously. However, it is much more difficult to update a desktop application, because you would have to get users to perform yet another installation or else ensure that the application has been coded to include a clever system for doing updates automatically. Web applications are said to use a zero-deployment model, but desktop applications use a heavy deployment and configuration model. The choice is often characterized as a tradeoff between rich and reach: Desktop applications generally offer a richer user experience than what could be offered in the browser, but with a Web application you are able to reach users anywhere on any OS with almost no extra effort. Furthermore, many companies have restrictive policies in place regarding what software can be installed on employees’ machines, and they often don’t allow employees to have administrative access that is required to install new applications, so Web applications are the only viable option in many situations. AJAX is the first real leap of a technology to bridge this historic wall between thick and thin. AJAX, though still working through the browser, focuses on bringing richness to Web applications by allowing for extremely interactive workflows that usually were only found in the thick client camp. 92171c01.indd 2 12/15/08 1:44:52 PM 3 Chapter 1: Overview of AJAX Bringing Richness to Web Applications Years ago, having a Web presence was a distinguishing factor for companies. That is no longer the case. Now just having a Web presence is no longer enough. Companies are distinguishing themselves further through Web applications that react intuitively to customer actions and anticipate user input. This book shows you how ASP.NET AJAX addresses specific Web development challenges and paves the way for taking your Web site to another level of user experience. The fundamental set of technologies used in the AJAX model that enable the next generation of Web applications is not entirely new. You will find that many people point to Google, Flickr, and several other services as prime examples of leveraging AJAX and its underlying technologies in unique ways. The applications have some unique features, but in reality, the underlying technologies have been around and in use for nearly a decade. Look at how Microsoft Exchange Server provided rich access to e-mail from a Web browser in the Outlook Web Access application, and the concept of ubiquitous access from a browser while leveraging a common set of browser features for a rich user experience has been around for years. In this case, users get a remarkably full-featured application with no local installation and are able to access e-mail from virtually any machine. While the AJAX acronym is nice, it doesn’t do much to explain what is actually happening. Instead of building a Web application to be just a series of page views and postbacks, developers are using JavaScript to communicate asynchronously with the Web server and update parts of the page dynamically. This means that the Web page can dynamically adapt its appearance as the user interacts with it, and it can even post or fetch data to or from the Web server in the background. Gone are the days of the ugly post- back, which clears the user’s screen and breaks his concentration! Instead, you need to post back now only if you want to change to a different Web page. Even that rule can be bent. Some applications are pushing this boundary and completely changing the user’s view, just as though they navigated to a new page, but they do so through an asynchronous post and by changing the page content without actually navigating to a new URL. The AJAX acronym refers to XML as the data format being exchanged between client and server, but in reality, applications are being built that retrieve simple pieces of text, XML, and JSON (JavaScript Object Notation) (which is discussed in more detail in Chapter 4). Part of the AJAX appeal is not even covered by the acronym alone: In addition, to communicating with the server without blocking, developers are leveraging Dynamic HTML (DHTML) and Cascading Style Sheets (CSS) to create truly amazing user interfaces. JavaScript code running on the client communicates asynchronously with the server and then uses DHTML to dynamically modify the page, which supports rich animations, transitions, and updates to the content while the user continues interacting with the page. In many cases, end users will some- times forget they are using a Web application! Just remember that AJAX is not a single holistic entity but instead is a novel and creative way of using a combination of technologies such as the XMLHttpRequest object, HTML, XHTML, CSS, DOM, XML, JSON, XSLT, and JavaScript. You might be thinking of the difficulties of piecing this all together to get the Web applications you want to build. Be ready to be wowed, however, as the focus of this book is on showing you how to use the built-in technologies provided by ASP.NET 3.5 to give you this power in an easy to use manner. 92171c01.indd 3 12/15/08 1:44:52 PM 4 Chapter 1: Overview of AJAX Who Benefits from AJAX? AJAX offers benefits to both end users and developers. For end users, it reduces the “rich or reach” conflict; for developers, it helps in overcoming the constraints raised by HTTP such as the dreaded page postback. Why End Users Want AJAX Applications Users tend to view desktop applications as a commitment. They install a program, usually from a disk pulled from a costly shrink-wrapped box. The program consumes hard disk space as well as a position in the program menu. The user may need to update the program periodically or perform an upgrade later on to get new features. If the program is proactive about updating itself, the user is confronted regularly with dialogs about accepting patches or downloads. In exchange for this investment of time, money, and energy, the user is repaid with an application that is able to leverage the operating system and machine resources. It is a rich application. It has local storage capabilities, offers quick response times, and can present a compelling and intuitive graphical user interface. More and more applications are becoming accessible from the Web browser, where the full resources of the hardware and OS are not available, but the user commitment of a desktop application is not required. Over the years, interacting with a Web application has meant a predictable pattern for users. They click a link in the page, and the browser flashes while the user waits until the page is repainted (the dreaded page postback). This cycle is repeated over and over. The user looks at what is presented on the page, interacts with it, and clicks somewhere on the page. The browser then produces an audible click for feedback and begins to postback to the server. The screen of the Web browser flashes blank and some icon spins or flashes while the user waits for a new version of the page to be returned from the server. Many times, the new version of the page is almost exactly the same as the previous version, with only part of the page being updated. And then the cycle begins all over again. This has a sluggish feeling even when the user has a high-speed network connection and is simply unacceptable for some types of applications. The AJAX set of technologies has changed what users expect from Web applications. JavaScript code running in the browser works to exchange data with the Web server asynchronously. There is no click sound and the browser does not flash. The request to the server is non-blocking, which means the user is able to continue viewing the page and interacting with it. The script gets the updated data from the server and modifies the page dynamically, using the DHTML coding methodology. The user is able to continue looking at the page while parts of it are updated in the background. AJAX is used to pro- vide a more responsive experience, making Web applications behave more like desktop installations. JavaScript is used to provide a richer experience with support for drag-and-drop, modal dialogs, and seemingly instantaneous updates to various parts of the page based on user inputs. A big part of successfully leveraging AJAX technologies is in the perceived performance increase. Users appreciate Web applications that anticipate their actions. If you also use JavaScript code in the background to pre-fetch images and data that may be needed, users can get a speedy response without the usual pause that accompanies their actions. Nobody wants to wait for data exchanges between client and server; studies have shown that a time lag between user input and subsequent UI changes can significantly reduce their productivity and give them the frustrating feeling that they are fighting the application. Users want Web applications to behave like desktop installations but without the overhead associated with an installation. As more applications employ smart caching, anticipate user actions, and provide richer UIs, the difference between Web and desktop applications is definitely becoming blurred. Expectations for Web applications are rising. The end user has now seen that it is possible to avoid the commitment of installing a desktop application and still have a rich and responsive experience. 92171c01.indd 4 12/15/08 1:44:52 PM 5 Chapter 1: Overview of AJAX Why Developers Want AJAX Often, the first question to arise when starting a new development project is what type of application it will be. Should it be a desktop application or a Web application? This is a key decision because it has historically dictated a lot about the nature of the application and the development problem space. Many developers are now choosing to build Web applications by default unless something about the applica- tion dictates that it must be a desktop install. If it must run offline or if it requires a user interface that is too complex to achieve in HTML, targeting the Web browser may be ruled out, and developers are forced to write a standalone application. Developers have a difficult job writing modern Web applications due to the inherent World Wide Web functionality constraints imposed by the use of the Hypertext Transfer Protocol (HTTP) and the way that browsers use it. HTTP is a stateless protocol. The Web browser requests a page, possibly carrying some sort of state (a querystring or form input parameters), and the Web server processes the request and sends a response that includes HTML-rendered content. The Web server can only react to the infor- mation supplied in the current request and does not know any additional information from the request itself, such as any details about the path the user took to get to the current view. When the response is rendered, the connection may be broken and the server will not have any infor- mation to preserve for the next request. From the server’s perspective, it is simply listening for requests to come in from any browser anywhere and then reacting. The browser issues a request to the page and receives an HTML page in response. It uses the HTML it receives to render the user interface. The user interacts with the page, and, in response, the browser clears the screen and submits a new request to the server, carrying some information about user input or actions. Again, a complete HTML page is returned. The browser then presents the new version of HTML. Fundamentally, the HTTP protocol is stateless. The server gets a request and responds to it. The request carries limited information about the ongoing conversation that is happening between client and server. This can definitely be a problem. AJAX makes this much better. AJAX breaks this pattern by updating portions of the page separately, via partial page rendering. Figure 1-1 shows a typical non-AJAX series of browser and server interactions (requests and responses). Each request results in full-page rendering. In response, the browser updates the user’s entire view with the HTML that is returned. The sequence presented here in Figure 1-1 is typical of the type of Web application that we have been living with for many years now. It has a request and response cycle that is abrupt and rather noticeable to the end user. Let it be said that, with the introduction of AJAX technologies, these types of applica- tions are changing quickly to the new model this technology provides. On the other hand, Figure 1-2 shows how AJAX is employed to improve the user’s experience. In this case, a request is made for the initial page rendering. From there, asynchronous requests to the server are made. An asynchronous request is a background request to send or receive data in an entirely nonvisual manner (meaning that there won’t be any resulting page flickering). They are asyn- chronous because the user interface is not frozen during this time, and users can continue interacting with the page while the data transfer is taking place. These calls get just an incremental update for the page instead of getting an entirely new page. JavaScript running on the client reacts to the new data and updates various portions of the page as desired. The number of requests to the server may be no different, or in some cases, there may actually be more calls to the server, but the users’ perception is that the application feels more responsive. End 92171c01.indd 5 12/15/08 1:44:52 PM 6 Chapter 1: Overview of AJAX users are not forced to pause, even if it is only a slight pause, and wait for the server while staring at a blank browser screen. This model, while chatty in some regards, provides the fluidity you are looking for in your Web applications. Client ASP.NET Engine Web Services Web Server Request/ Response HTML Request/ Response HTML Figure 1-1 AJAX applications make use of the XMLHttpRequest object as an initiator and caller of the underlying data needed by the application to make the necessary changes. These requests are routed through a serialization process before being transmitted across the wire. In most cases, the output is some type of XML (such as SOAP) or JSON (for those who want an especially a tight format). The response from the server is then deserialized and provided to the JavaScript on the page, which then interacts with DHTML to render the parts of the page, outside of the normal postback process. Technologies of AJAX Almost. 92171c01.indd 6 12/15/08 1:44:52 PM 7 Chapter 1: Overview of AJAX Client ASP.NET Engine Web Services XMLHttpRequest Object JSON/XML Serializer DHTML Rendering Web Server Request/ Response Initial Response Request/ Response JSON/XML Figure 1-2 The browsers that can make use of this object include the following: Internet Explorer 5.0 and above (currently in version 8.0)❑❑ Safari 3.1❑❑ Firefox 3❑❑ Opera 8+❑❑ Netscape 9❑❑ applications that would not require any client installation and could be accessed from any browser anywhere. Web applications began to move to a whole new level of richness. Without AJAX libraries, you would be faced with writing lots and lots of JavaScript code and debugging the sometimes subtle variations in different browsers to reach this new level of richness. 92171c01.indd 7 12/15/08 1:44:53 PM 8 Chapter 1: Overview of AJAX JavaScript Libraries and AJAX Developers have had access to AJAX technologies for years, and many have been leveraging AJAX to push the limits of what can be done in the Web browser. But what is really making AJAX more compel- ling now are the comprehensive script libraries and integration with server technologies that make it easier to write rich Web applications and avoid the need to become an expert on the different versions of JavaScript. A JavaScript library is referenced within the HTML of a page by using the <script> tag: <html> <head> <script src=”” type=”text/javascript”> </script> </head> ... The script is downloaded and cached by the browser. Other pages within the application can reference the same URL for script, and the browser will not even bother to go back to the server to get it. The functional- ity of that script file is available for use from within the page rendered to the browser. A script library sent to the browser and then leveraged for writing a richer UI and a more responsive application is at the heart of all AJAX libraries. The Initiator Component To initiate calls to the back end server, you need JavaScript on the client to invoke the XMLHttpRequest object, which takes charge of making these out-of-bound calls. This component works to send data back and forth asynchronously. This core capability is browser-independent and allows for requests and responses to occur without interrupting the end user experience. The JavaScript Component AJAX technologies take advantage of the common support for JavaScript found in modern browsers. Because there is a standard that is supported across the various browsers, you can write scripts knowing that they will run. This wasn’t always the case. In the mid-1990s, use- ful for marketing purposes.) JavaScript program snippets are sent down to the browser along with the HTML, and they run inside the user’s browser to affect how the page is processed on the client. JavaScript is not compiled; it is interpreted. There is no static type-checking as you get in C++ and C#. You can declare a variable without needing to specify a type, and the type to which the variable refers can change at any time. This makes it easy to start programming in JavaScript, but there is inevitably a certain amount of danger in allowing the data type of a variable to change dynamically at runtime. In the following snippet, notice that the variable can reference any type without difficulty: var something = 1; something = true; something = “a string”; 92171c01.indd 8 12/15/08 1:44:53 PM 9 Chapter 1: Overview of AJAX that are considered essential for many programming tasks are included in JavaScript. snippet> 92171c01.indd 9 12/15/08 1:44:54 PM 10 Chapter 1: Overview of AJAX You can check specifically to see if a variable has been defined like this: if( typeof(undefinedVar ) == “undefined” ) { alert(“undefinedVar is undefined”); } Variables can also have a null value, which is not the same thing as being undefined, because this did not state that it takes two numbers. Remember, JavaScript variables do not have a defined type, so I could just as easily pass two strings and concatenate them vis- ibility to local variables), which lets you create data structures that represent entities in JavaScript code. Missing from this sort of object-oriented programming is a concept of type inheritance. Although, there are things like the Microsoft AJAX Library, which provides a set of classes and recommended patterns for achieving inheritance in JavaScript, making it more natural to switch; 92171c01.indd 10 12/15/08 1:44:54 PM 11 Chapter 1: Overview of AJAX Web Services Component The fundamental concept of Web services is powerful and continues to evolve and advance. The original Simple Object Access Protocol (SOAP) that the target site is rendering. This resulted in frustration, because screen-scraping, you are able to call a Web service and have XML-formatted data returned that is easily consumed by a program. By passing plain-text data formatted as XML and by eliminating the visual elements, data passed in Web services is much easier to parse than HTML. Moreover, pro- gressed beyond simple XML formats. Unlike previous implementations of Web services, you can now define Web service contracts to be built to employ arbitrary encoding and utilize any one of a number of wire protocols. What drives the Web service concept is the ability to access data easily from various 92171c01.indd 11 12/15/08 1:44:54 PM 12 Chapter 1: Overview of AJAX applications in a loosely coupled way, and the new Microsoft Windows Communication Foundation (WCF) takes this concept to a completely new level, allowing the contract to specify wire protocols, deployment strategies, and logging infrastructure, along with providing support for transactions. ASP.NET AJAX provides a set of JavaScript proxy objects to access some new Web services built into. Moreover, because the JavaScript libraries are designed to be easy to use by developers already familiar with server-side .NET programming, all of this extra functionality comes in a friendly package that is easy to leverage. The Dynamic HTML Component DOM that represents the structure of the HTML being displayed. The DOM can be accessed from JavaScript embedded in, or referenced by, the page. The appearance of the HTML is affected by applying Cascading Style Sheets (CSS), which. It can also communicate with the server to expand the dynamic nature of the page even further. The user will see a dynamically changing user interface that responds to his actions in real time, which will greatly enhance his overall experience, thereby increasing his productivity and satisfaction with the application. This one piece of the pie is the one that changes the underlying page without the page refresh. All these pieces together, in the end, provide you the tools that you need to build state-of-the-art applications for today’s Web world. AJAX Libraries ASP.NET AJAX is the focus of this book. ASP.NET AJAX is an AJAX library that provides you with the tools and components that you need to tie all the varying aforementioned technologies together. Although this book is about ASP.NET AJAX in particular, there are many third-party AJAX libraries that can be used with ASP.NET, although not all of them were specifically designed for it. Some of these AJAX libraries are mainly focused on providing JavaScript libraries for use from within the browser to make manipulation of the browser DOM easier. Others. So 92171c01.indd 12 12/15/08 1:44:54 PM 13 Chapter 1: Overview of AJAX if you decide to move forward on this route, make sure that you are aware of the potential problems. Some of the available libraries include the following: Ajax.NET Professional❑❑: Michael Schwartz developed Ajax.NET Professional as a tool primarily used to simplify the data transport mechanism that enables a client JavaScript routine to com- municate in DHTML, and there are not many prebuilt visual controls. This is a lightweight solution with very little overhead in terms of bytes transferred and processing cycles needed on the client and server. The source code is available, and the package is free ( ). Anthem.NET❑❑: are not well versed in DHTML. This project is similar to ASP.NET AJAX in many ways but is not as comprehensive. DoJo❑❑:❑❑: does not provide much help for producing a richer user interface but puts forth the building blocks for an improved Web-scripting experience. ❑❑ Script.aculo.us: The Script.aculo.us library can be found at the Web site of the same name, http:// script.aculo.us . Their tagline is “it’s about the user interface, baby!” which accurately describes their focus. is built on top of the Prototype script library and picks up where it stops. It includes functionality for adding drag-and-drop support to an application. It has a lot of effects code for fading, shrinking, moving, and otherwise animating DOM elements. http:// script.aculo.us also has a slider control and a library for manipulating lists of elements. Rico❑❑: The Rico library also builds on top of the Prototype script library. . 92171c01.indd 13 12/15/08 1:44:54 PM 14 Chapter 1: Overview of AJAX Although there are many options out there for ASP.NET developers, you will find that the toolkit defined in this book is the most integrated with ASP.NET and will be one of the more robust options in your arsenal.. Listing 1-1: The Web service to communicate with the AJAX-enabled Web page using System.Web.Services; /// <summary> /// Summary description for WebService /// </summary> [WebService(Namespace = ““)] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class WebService : System.Web.Services.WebService { [WebMethod] public string HelloWorld() { return “Hello Ajax World!”; } }. Listing 1-2: Changing the web.config file in order to allow HTTP-GET <system.web> <webServices> <protocols> <add name=”HttpGet” /> </protocols> </webServices> </system.web> Including the <add> element within the <protocols> element enables the HTTP-GET protocol so that your Web page will be able to make the AJAX calls to it. Finally, the HTML page that will make the AJAX call is represented here in Listing 1-3. 92171c01.indd 14 12/15/08 1:44:54 PM 15 Chapter 1: Overview of AJAX Listing 1-3: The HTML page that will make the AJAX calls to the Web service <html xmlns=””> <head runat=”server”> <title>Basic Ajax Page</title> <script type=”text/javascript” language=”javascript”> function InitiationFunction() { var xmlHttp; try { // Try this for non-Microsoft browsers xmlHttp = new XMLHttpRequest(); } catch (e) { // These are utilized for Microsoft IE browsers && xmlHttp.status == 200) { response = xmlHttp.responseXML; document.forms[0].statement.value = response.getElementsByTagName(“string”)[0].firstChild.nodeValue; } } xmlHttp.open(“GET”,”/BasicAjax/WebService.asmx/HelloWorld?”,true); xmlHttp.send(null); } </script> </head> <body> Continued 92171c01.indd 15 12/15/08 1:44:54 PM 16 Chapter 1: Overview of AJAX Listing 1-3: The HTML page that will make the AJAX calls to the Web service (continued) <form> <div> Statement from server: <input type=”text” name=”statement” /> <br /> <br /> <input id=”Button1” type=”button” value=”Button” onclick=”InitiationFunction()“ /> </div> </form> </body> </html> From this bit of code, you can see that the HTML page creates an instance of the XMLHttpRequest object. From there, a JavaScript function is assigned to the onreadystatechange attribute. Whenever the state of the XMLHttpRequest instance changes, the function is invoked. Since, for this example, you are interested only in changing the page after the page is actually loaded, you are able to specify when the actual function is utilized by checking the readystate attribute of the XMLHttpRequest object. if(xmlHttp.readyState == 4 && xmlHttp.status == 200) { } In this case, the readystate is checked to see if it equals a value of 4 and if the request status is equal to 200, a normal request was received. If the status attribute is equal to something other than 200 , a server-side error most likely occurred. A readystate value of 4 means that the page is loaded. The pos - sible values of the readystate attribute include 0 , 1 , 2 , 3 , and 4 . A value of 0 (which is the default value) means that the object is uninitialized. A value of 1 means that the open() method was called successfully, a value of 2 means that the request was sent but that no response was yet received, a value of 3 means that the message is being received, and a value of 4 (again) means that the response is fully loaded. The open() method called by the XMLHttpRequest object is quite simple, as it is an HTTP-GET request made to the specific URL of your service. When you run this page and click the button found on the page, you are presented with results illus - trated in Figure 1-3. Figure 1-3 92171c01.indd 16 12/15/08 1:44:55 PM 17 Chapter 1: Overview of AJAX The Power of AJAX Without the advanced use of JavaScript running in the browser, Web applications have their logic run- ning on the server. This means many page refreshes for potentially small updates to the user’s view. With AJAX, much of the logic surrounding user interactions can be moved to the client. This presents its own set of challenges. Some examples of using AJAX include streaming large datasets, managed entirely in JavaScript, to the browser. While JavaScript is a powerful language, the debugging facilities and options for error handling are very limited. Putting complex application logic on the client can take a lot of time, effort, and patience. AJAX as a whole allows you to naturally migrate some parts of the application processing to the client, while leveraging partial page rendering to let the server actually control some aspects of the page view. Some Web sites make an application run entirely from a single page request, where JavaScript and AJAX will do a great deal of work. This presents some tough challenges. Users generally expect that the Back button will take them to the state of the application they were just viewing, but with AJAX appli- cations, this is not necessarily the case. The client may be sending some information to the server for persistent state management (perhaps in server memory or a database), but this requires extra code and special attention to error handling and recovery. The richest, most maintainable applications seem to be those that balance client and server resources to provide quick response times, easy access to server resources, and a minimum of blocking operations while new page views are fetched. ASP.NET AJAX itself provides a mix of client and server programming features. The Microsoft AJAX library is aimed at client development. It provides a type system for an object-oriented approach to JavaScript development. It makes it easy to register code to respond to events. It provides useful functions to simplify common tasks like finding elements on the page, attaching event handlers, and accessing the server. The server features include functionality for managing JavaScript code to be sent to the client, declaring regions of the page to be updated asynchronously, creating timers for continuous updates, and accessing ASP.NET services such as user profile data and authentication. Summary The Web has evolved over the last decade from providing a static presence to being the default choice for developers writing applications. With Web applications, you get reach without having to deal with the deployment and servicing issues that accompany desktop applications. But the bar continues to move higher for Web applications as users come to expect more. AJAX technologies are driving Web applications to rival rich desktop apps. You can use the results of asynchronous communication with the Web server to update portions of the page without forcing the user to stop his or her work and wait for the page to post back and be repainted. Dynamic HTML allows you to create a rich GUI with transi- tions and animations leveraging CSS for colors, fonts, positioning, and more. ASP.NET AJAX includes the Microsoft AJAX library, which makes writing browser-based JavaScript easier and simplifies many common client programming tasks. It is easy to attach code to DOM events, write JavaScript in an object-oriented way, and access the server for persistent storage, authentication, and updated data. 92171c01.indd 17 12/15/08 1:44:55 PM 18 Chapter 1: Overview of AJAX ASP.NET AJAX also includes extensions to version 2.0 of the .NET Framework that can greatly improve your Web application. There is built-in support for returning data in the JSON format that is easily con- sumed by JavaScript in the browser. In this book, you will see how the client and server features of ASP.NET AJAX make it easier to push the limits of what you can do with a Web application! You learn how to update portions of a page asyn- chronously and how to manage the scripts that are used in the browser. You will find out how to use the networking facilities, with a dive into accessing ASP.NET services such as authentication and profile storage. You will get a closer look at the JavaScript language and how the Microsoft AJAX library builds on the language to simplify programming tasks. You will also see what ASP.NET AJAX offers for add- ing a richer UI to Web applications and look at how to debug and test Web applications. 92171c01.indd 18 12/15/08 1:44:55 PM Log in to post a comment
https://www.techylib.com/en/view/scaredbacon/overview_of_ajax
CC-MAIN-2017-51
refinedweb
6,200
59.53
The threading library is a collection of routines and classes for creating multithreaded and thread safe code and programs. Remember that just because you can make something multithreaded and threading safe does not mean you should do so, or doing so is a good idea and will give you a lot of benefit. Use with care, when appropriate. All threading related classes and operations are in the CS::Threading namespace. Atomic operations are the basic and smallest operations behind threading safe code. Atomic in this context means that they are guaranteed to complete with a deterministic result in relation to other threads and even cores doing other atomic operations on the same data. Atomic operations in Crystal Space is found in CS::Threading::AtomicOperations class in ‘csutil/threading/atomicops.h’. There are a few different atomic operations, namely: A thread is the smallest unit of execution when looking at multithreaded execution. Each thread is a "lane" of sequential execution and by having multiple threads executing at the same time you get the effect of simultaneous execution. As this concept of simultaneous execution can be a bit confusing at first there are two important things to remember A more important result of this is that you cannot rely on or even know when one thread is interrupted to let another one execute. This means that whenever you operate on data shared between two or more threads you must use one of the syncronization primitives or atomic operations. To create a thread you first need to implement the interface CS::Threading::Runnable and instance it. Then create an instance of CS::Threading::Thread to start a new thread executing the runnable instance. Use the Start() and Stop() methods of the thread to control its execution and Wait() to wait until it finishes execution. Here is an example of a simple thread and creation As you can see in this example it is not doing anything useful while the thread is running. In a real application you would do something useful while the thread is for example waiting for IO. The threading library provides two different thread syncronization primitives. The two works differently and do not have the same purpose. Which primitive to use depends on the situation at hand. To note is that a condition always is used together with a mutex, which also should be shared between the threads. The example below shows how a mutex and a condition can be used to distribute work units between two threads. Note, this sample works but is not fully complete. For a better implementation, look at CS::Threading::ThreadedJobQueue This document was generated using texi2html 1.76.
http://www.crystalspace3d.org/docs/online/manual-1.4/Threading.html
CC-MAIN-2014-41
refinedweb
444
52.49
Microsoft Help 2 enables authors to insert the TOC of a child collection into the TOC of a parent collection. This topic explains the markup that inserts the TOC of a child Help collection into the TOC of a master (parent) Help collection. The following table illustrates one possible integration: + folder1 ++ folder1.a (id1) ++ folder1.b + folder2 (id2) + folder3 + child1.a ++ child1.a.1 ++ child 1.a.2 + child1.b + child2.a + child2.b + child 2.c +++ child1.a ++++ child1.a.1 ++++ child1.a.2 +++ child1.b + folder 2 (id2) ++ child2.a ++ child2.b ++ child2.c Both the parent namespace and the child namespace must use run-time collection files (for example, HxC, HxT) to define their collections. These collections can contain from one to n registered titles (HxS or HxS/HxI). Two files must be modified to insert the TOC of a child collection into the TOC of a parent collection: The run-time HxT file for the parent collection must have an ID assigned to a node where the HxT of the child collection is expected to appear. The HxC file for the child collection must have a matching ID assigned to a TOCDef element, which also points to an HxT file belonging to the child collection. To arrange the TOCs of child collections in the correct order, each element must have a unique ID. A third file can be used to adjust the appearance of the merged TOC: The HxT file for the child collection can contain markup using the PluginStyle and PluginTitle attributes to achieve the correct layout. Because all three files are created at authoring time, some coordination is required to ensure that the ID strings match and that PluginStyle and PluginTitle are used consistently. A parent HxT may define multiple HelpTOCNodes with the same ID. A child HxT with the matching ID is inserted into each of the HelpTOCNodes. Likewise, a child collection can contain multiple TOCDef elements with the same ID. Using IDs that are not unique precludes the ability to define the order of appearance. In such a case, each of the HxT files that the TOCDef elements reference is inserted into any HelpTOCNode that has a matching ID in the parent HxT file. Use unique IDs that are not too long. Avoid using XML character entities (those using the % symbol), double quotes, and other characters that are reserved for XML. The syntax of the run-time HxT file is not enforced by a DTD. It is only checked to enforce well-formed XML. Consider using a consistent naming convention for readability, for example: Id="InsertTOC:<namespace>[_<HXT filename>]" Id="InsertTOC:PartnerSDK" Id="InsertTOC:PartnerSDK_partner1" The first step required to insert the TOC of a child collection into the TOC of a parent collection is to identify and mark the positions in the parent HxT file where the insertions should occur. The Id attribute of the HelpTOCNode element is used for this purpose. When a child namespace is plugged into a parent namespace, the IDs of the TOCDef elements of the child collection are reconciled with HelpTOCNode IDs in the run-time HxT file of the parent collection. If a match is found, the HxT with a matching ID that is specified in the TOC of the child collection is inserted into the parent TOC. Insert a TOC node by using the Id attribute value, as shown in the following example: <HelpTOCNode Id="InsertTOC:vcedit" NodeType="TOC"/> It is still possible to specify a URL that points to a registered title or topic in the parent or plugged-in namespace, as shown in the following examples. Using the URL attribute value to reference a registered namespace: <HelpTOCNode NodeType="TOC" Url="vcedit"/> Using the URL attribute value to reference an individual topic: <HelpTOCNode NodeType="Regular" Url="/vcedit/howtouse.htm"/> Note the following limitations: If the URL attribute value is present, the Id attribute value is ignored. The Id attribute value must conform to the rules of MSXML for CDATA attributes. ID strings are case-sensitive ("MyID" != "myid"). The second step required to insert the TOC of a child collection into the TOC of a parent collection is to add an ID to the child-collection TOC(s). The Id attribute of the TOCDef element is used to identify the nodes to insert. When a child namespace is plugged into a parent namespace, the IDs of the TOCDef elements of the child collection are reconciled with IDs in the runtime HxT file of the parent collection. If a match is found, the HxT specified in the TOC of the child’s collection is inserted into the parent TOC at the node with the matching ID. The markup for the TOCDef element is as follows: <TOCDef Id="TOC_01" File="/main/Runtime.HxT" /> Note the following limitations: The Id attribute value must match an ID specified in a HelpTOCNode of the run-time HxT file of the parent collection. The File attribute value must reference a valid run-time HxT file for the child collection. The PluginStyle and PluginText attributes of the HelpTOC element of the HxT file of the child collection can be modified to adjust the layout of the merged TOC. If the value of PluginStyle is set to "Hierarchical" (the default), the child TOC is inserted into a folder that is automatically generated by the runtime of the parent HxT. The name is specified by the value of the PluginTitle attribute, as shown in the following table: CS1.HXT PluginStyle= "Hierarchical" CS2.HXT PluginTitle="Child2" +++ child1\CS1 ++++ child1.a +++++ child1.a.1 +++++ child1.a.2 ++++ child1.b ++ Child2 +++ child2.a +++ child2.b +++ child2.c If the PluginTitle attribute is not present, the name of the runtime-generated folder is a concatenation of the parent namespace + a slash (\) + the child namespace. If the value of PluginStyle is set to "Flat", the contents of the child’s HxT file are inserted directly into the node created in the parent HxT that contains the matching ID. PluginTitle is ignored, as shown in the following example. PluginStyle="Flat"
http://msdn.microsoft.com/en-us/library/bb164944(VS.80).aspx
crawl-002
refinedweb
1,012
51.99
From: Gennadiy Rozental (gennadiy.rozental_at_[hidden]) Date: 2007-06-09 19:21:56 "Rene Rivera" <grafikrobot_at_[hidden]> wrote in message news:466B304C.6060400_at_gmail.com... > Gennadiy Rozental wrote: >> I don't mean in general. static vars have the same issue. I mean why is >> it >> reported by our tools? > > Because, once upon a time, we found real ODR problems in some of the > headers that use(d) unnamed namespaces. And someone decided that it > would be a good idea find as many of those as possible. And what better > way to do that, than an automated tool. I don't believe it right approach. Almost every feature can be misused.Should we report usage of any one of them? It there any problems with unnamed namespace usage within Boost.Test? Gennadiy Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2007/06/123150.php
CC-MAIN-2020-29
refinedweb
152
71.61
PEP 621 -- Storing project metadata in pyproject.toml Contents - Abstract - Motivation - Rationale - Specification - Backwards Compatibility - Security Implications - Reference Implementation - Rejected Ideas - Other table names - Support for a metadata provider - Require a normalized project name - Specify files to include when building - Name the [project.urls] table [project.project-urls] - Have a separate url/home-page field - Recommend that tools put development-related dependencies into a "dev" extra - Have the dynamic field only require specifying missing required fields - Different structures for the readme field - Allowing the readme field to imply text/plain - Other names for dependencies/optional-dependencies - Drop maintainers to unify with authors - Support an arbitrary depth of tables for project.entry-points - Using structured TOML dictionaries to specify dependencies - Require build back-ends to update pyproject.toml when generating an sdist - Allow tools to add/extend data - Open Issues - References Abstract This PEP specifies how to write a project's core metadata [1] in a pyproject.toml file for packaging-related tools to consume. Motivation The key motivators of this PEP are: - Encourage users to specify core metadata statically for speed, ease of specification, unambiguity, and deterministic consumption by build back-ends - Provide a tool-agnostic way of specifying metadata for ease of learning and transitioning between build back-ends - Allow for more code sharing between build back-ends for the "boring parts" of a project's metadata To speak specifically to the motivation for static metadata, that has been an overall goal of the packaging ecosystem for some time. As such, making it easy to specify metadata statically is important. This also means that raising the cost of specifying data as dynamic is acceptable as users should skew towards wanting to provide static metadata. Requiring the distinction between static and dynamic metadata also helps with disambiguation for when metadata isn't specified. When any metadata may be dynamic, it means you never know if the absence of metadata is on purpose or because it is to be provided later. By requiring that dynamic metadata be specified, it disambiguates the intent when metadata goes unspecified. This PEP does not attempt to standardize all possible metadata required by a build back-end, only the metadata covered by the core metadata [1] specification which are very common across projects and would stand to benefit from being static and consistently specified. This means build back-ends are still free and able to innovate around patterns like how to specify the files to include in a wheel. There is also an included escape hatch for users and build back-ends to use when they choose to partially opt-out of this PEP (compared to opting-out of this PEP entirely, which is also possible). This PEP is also not trying to change the underlying core metadata [1] in any way. Such considerations should be done in a separate PEP which may lead to changes or additions to what this PEP specifies. Rationale The design guidelines the authors of this PEP followed were: - Define a representation of as much of the core metadata [1] in pyproject.toml as is reasonable - Define the metadata statically with an escape hatch for those who want to define it dynamically later via a build back-end - Use familiar names where it makes sense, but be willing to use more modern terminology - Try to be ergonomic within a TOML file instead of mirroring how build back-ends specify metadata at a low-level when it makes sense - Learn from other build back-ends in the packaging ecosystem which have used TOML for their metadata - Don't try to standardize things which lack a pre-existing standard at a lower-level - When metadata is specified using this PEP, it is considered canonical Specification When specifying project metadata, tools MUST adhere and honour the metadata as specified in this PEP. If metadata is improperly specified then tools MUST raise an error to notify the user about their mistake. Data specified using this PEP is considered canonical. Tools CANNOT remove, add or change data that has been statically specified. Only when a field is marked as dynamic may a tool provide a "new" value. Details Table name Tools MUST specify fields defined by this PEP in a table named [project]. No tools may add fields to this table which are not defined by this PEP or subsequent PEPs. For tools wishing to store their own settings in pyproject.toml, they may use the [tool] table as defined in PEP 518. The lack of a [project] table implicitly means the build back-end will dynamically provide all fields. name - Format: string - Core metadata [1]: Name (link) - Synonyms The name of the project. Tools MUST require users to statically define this field. Tools SHOULD normalize this name, as specified by PEP 503, as soon as it is read for internal consistency. version - Format: string - Core metadata [1]: Version (link) - Synonyms The version of the project as supported by PEP 440. Users SHOULD prefer to specify already-normalized versions. description - Format: string - Core metadata [1]: Summary (link) - Synonyms The summary description of the project. readme - Format: String or table - Core metadata [1]: Description (link) - Synonyms The full description of the project (i.e. the README). The field accepts either a string or a table. If it is a string then it is the relative path to a text file containing the full description. Tools MUST assume the file's encoding is UTF-8. If the file path ends in a case-insensitive .md suffix, then tools MUST assume the content-type is text/markdown. If the file path ends in a case-insensitive .rst, then tools MUST assume the content-type is text/x-rst. If a tool recognizes more extensions than this PEP, they MAY infer the content-type for the user without specifying this field as dynamic. For all unrecognized suffixes when a content-type is not provided, tools MUST raise an error. The readme field may also take a table. The file key has a string value representing a relative path to a file containing the full description. The text key has a string value which is the full description. These keys are mutually-exclusive, thus tools MUST raise an error if the metadata specifies both keys. A table specified in the readme field also has a content-type field which takes a string specifying the content-type of the full description. A tool MUST raise an error if the metadata does not specify this field in the table. If the metadata does not specify the charset parameter, then it is assumed to be UTF-8. Tools MAY support other encodings if they choose to. Tools MAY support alternative content-types which they can transform to a content-type as supported by the core metadata [1]. Otherwise tools MUST raise an error for unsupported content-types. requires-python - Format: string - Core metadata [1]: Requires-Python (link) - Synonyms The Python version requirements of the project. license - Format: Table - Core metadata [1]: License (link) - Synonyms The table may have one of two keys. The file key has a string value that is a relative file path to the file which contains the license for the project. Tools MUST assume the file's encoding is UTF-8. The text key has a string value which is the license of the project whose meaning is that of the License field from the core metadata [1]. These keys are mutually exclusive, so a tool MUST raise an error if the metadata specifies both keys. A practical string value for the license key has been purposefully left out to allow for a future PEP to specify support for SPDX [6] expressions (the same logic applies to any sort of "type" field specifying what license the file or text represents). keywords - Format: array of strings - Core metadata [1]: Keywords (link) - Synonyms The keywords for the project. classifiers - Format: array of strings - Core metadata [1]: Classifier (link) - Synonyms Trove classifiers [5] which apply to the project. urls - Format: Table, with keys and values of strings - Core metadata [1]: Project-URL (link) - Synonyms A table of URLs where the key is the URL label and the value is the URL itself. Entry points - Format: Table ([project.scripts], [project.gui-scripts], and [project.entry-points]) - Core metadata [1]: N/A; Entry points specification [8] - Synonyms There are three tables related to entry points. The [project.scripts] table corresponds to the console_scripts group in the entry points specification [8]. The key of the table is the name of the entry point and the value is the object reference. The [project.gui-scripts] table corresponds to the gui_scripts group in the entry points specification [8]. Its format is the same as [project.scripts]. The [project.entry-points] table is a collection of tables. Each sub-table's name is an entry point group. The key and value semantics are the same as [project.scripts]. Users MUST NOT create nested sub-tables but instead keep the entry point groups to only one level deep. Build back-ends MUST raise an error if the metadata defines a [project.entry-points.console_scripts] or [project.entry-points.gui_scripts] table, as they would be ambiguous in the face of [project.scripts] and [project.gui-scripts], respectively. dependencies/optional-dependencies - Format: Array of PEP 508 strings (dependencies) and a table with values of arrays of PEP 508 strings (optional-dependencies) - Core metadata [1]: Requires-Dist and Provides-Extra (link, link) - Synonyms - Flit [2]: requires for required dependencies, requires-extra for optional dependencies (link) - Poetry [3]: [tool.poetry.dependencies] for dependencies (both required and for development), [tool.poetry.extras] for optional dependencies (link) - Setuptools [4]: install_requires for required dependencies, extras_require for optional dependencies (link) The (optional) dependencies of the project. For dependencies, it is a key whose value is an array of strings. Each string represents a dependency of the project and MUST be formatted as a valid PEP 508 string. Each string maps directly to a Requires-Dist entry in the core metadata [1]. For optional-dependencies, it is a table where each key specifies an extra and whose value is an array of strings. The strings of the arrays must be valid PEP 508 strings. The keys MUST be valid values for the Provides-Extra core metadata [1]. Each value in the array thus becomes a corresponding Requires-Dist entry for the matching Provides-Extra metadata. dynamic - Format: Array of strings - Core metadata [1]: N/A - No synonyms Specifies which fields listed by this PEP were intentionally unspecified so another tool can/will provide such metadata dynamically. This clearly delineates which metadata is purposefully unspecified and expected to stay unspecified compared to being provided via tooling later on. - A build back-end MUST honour statically-specified metadata (which means the metadata did not list the field in dynamic). - A build back-end MUST raise an error if the metadata specifies the name in dynamic. - If the core metadata [1] specification lists a field as "Required", then the metadata MUST specify the field statically or list it in dynamic (build back-ends MUST raise an error otherwise, i.e. it should not be possible for a required field to not be listed somehow in the [project] table). - If the core metadata [1] specification lists a field as "Optional", the metadata MAY list it in dynamic if the expectation is a build back-end will provide the data for the field later. - Build back-ends MUST raise an error if the metadata specifies a field statically as well as being listed in dynamic. - If the metadata does not list a field in dynamic, then a build back-end CANNOT fill in the requisite metadata on behalf of the user (i.e. dynamic is the only way to allow a tool to fill in metadata and the user must opt into the filling in). - Build back-ends MUST raise an error if the metadata specifies a field in dynamic but the build back-end was unable to provide the data for it. Example [project]=3.8" license = {file = "LICENSE.txt"} keywords = ["egg", "bacon", "sausage", "tomatoes", "Lobster Thermidor"] authors = [ {email = "hi@pradyunsg.me"}, {name = "Tzu-Ping Chung"} ] maintainers = [ {name = "Brett Cannon", email = "brett@python.org"} ] classifiers = [ "Development Status :: 4 - Beta", "Programming Language :: Python" ] dependencies = [ "httpx", "gidgethub[httpx]>4.0.0", "django>2.1; os_name != 'nt'", "django>2.0; os_name == 'nt'" ] [project.optional-dependencies] test = [ "pytest < 5.0.0", "pytest-cov[all]" ] [project.urls] homepage = "example.com" documentation = "readthedocs.org" repository = "github.com" changelog = "github.com/me/spam/blob/master/CHANGELOG.md" [project.scripts] spam-cli = "spam:main_cli" [project.gui-scripts] spam-gui = "spam:main_gui" [project.entry-points."spam.magical"] tomatoes = "spam:main_tomatoes" Backwards Compatibility As this provides a new way to specify a project's core metadata [1] and is using a new table name which falls under the reserved namespace as outlined in PEP 518, there are no backwards-compatibility concerns. Security Implications There are no direct security concerns as this PEP covers how to statically define project metadata. Any security issues would stem from how tools consume the metadata and choose to act upon it. Reference Implementation There are currently no proofs-of-concept from any build back-end implementing this PEP. Rejected Ideas Other table names Anything under [build-system] There was worry that using this table name would exacerbate confusion between build metadata and project metadata, e.g. by using [build-system.metadata] as a table. [metadata] The strongest contender after [project], but in the end it was agreed that [project] read better for certain sub-tables, e.g. [project.urls]. Support for a metadata provider Initially there was a proposal to add a middle layer between the static metadata specified by this PEP and prepare_metadata_for_build_wheel() as specified by PEP 517. The idea was that if a project wanted to insert itself between a build back-end and the metadata there would be a hook to do so. In the end the authors considered this idea unnecessarily complicated and would move the PEP away from its design goal to push people to define core metadata statically as much as possible. Require a normalized project name While it would make things easier for tools to only work with the normalized name as specified in PEP 503, the idea was ultimately rejected as it would hurt projects transitioning to using this PEP. Specify files to include when building The authors decided fairly quickly during design discussions that this PEP should focus exclusively on project metadata and not build metadata. As such, specifying what files should end up in a source distribution or wheel file is out of scope for this PEP. Name the [project.urls] table [project.project-urls] This suggestion came thanks to the corresponding core metadata [1] being Project-Url. But once the overall table name of [project] was chosen, the redundant use of the word "project" suggested the current, shorter name was a better fit. Have a separate url/home-page field While the core metadata [1] supports it, having a single field for a project's URL while also supporting a full table seemed redundant and confusing. Have the dynamic field only require specifying missing required fields The authors considered the idea that the dynamic field would only require the listing of missing required fields and make listing optional fields optional. In the end, though, this went against the design goal of promoting specifying as much information statically as possible. Different structures for the readme field The readme field had a proposed readme_content_type field, but the authors considered the string/table hybrid more practical for the common case while still accommodating the more complex case. Same goes for using long_description and a corresponding long_description_content_type field. The file key in the table format was originally proposed as path, but file corresponds to setuptools' file key and there is no strong reason otherwise to choose one over the other. Allowing the readme field to imply text/plain The authors considered allowing for unspecified content-types which would default to text/plain, but decided that it would be best to be explicit in this case to prevent accidental incorrect renderings on PyPI and to force users to be clear in their intent. Other names for dependencies/optional-dependencies The authors originally proposed requires/extra-requires as names, but decided to go with the current names after a survey of other packaging ecosystems showed Python was an outlier: Normalizing on the current names helps minimize confusion for people coming from other ecosystems without using terminology that is necessarily foreign to new programmers. It also prevents potential confusion with requires in the [build-system] table as specified in PEP 518. Support an arbitrary depth of tables for project.entry-points There was a worry that keeping project.entry-points to a depth of 1 for sub-tables would cause confusion to users if they use a dotted name and are not used to table names using quotation marks (e.g. project.entry-points."spam.magical"). But supporting an arbitrary depth -- e.g. project.entry-points.spam.magical -- would preclude any form of an exploded table format in the future. It would also complicate things for build back-ends as they would have to make sure to traverse the full table structure rather than a single level and raising errors as appropriate on value types. Using structured TOML dictionaries to specify dependencies The format for specifying the dependencies of a project was the most hotly contested topic in terms of data format. It led to the creation of both PEP 631 and PEP 633 which represent what is in this PEP and using TOML dictionaries more extensively, respectively. The decision on those PEPs can be found at. The authors briefly considered supporting both formats, but decided that it would lead to confusion as people would need to be familiar with two formats instead of just one. Require build back-ends to update pyproject.toml when generating an sdist When this PEP was written, sdists did not require having static, canonical metadata like this PEP does. The idea was then considered to use this PEP as a way to get such metadata into sdists. In the end, though, the idea of updating pyproject.toml was not generally liked, and so the idea was rejected in favour of separately pursuing standardizing metadata in sdists. Allow tools to add/extend data In an earlier version of this PEP, tools were allowed to extend data for fields. For instance, build back-ends could take the version number and add a local version for when they built the wheel. Tools could also add more trove classifiers for things like the license or supported Python versions. In the end, though, it was thought better to start out stricter and contemplate loosening how static the data could be considered based on real-world usage. Open Issues None at the moment. This document is placed in the public domain or under the CC0-1.0-Universal license, whichever is more permissive.
https://www.python.org/dev/peps/pep-0621/
CC-MAIN-2021-39
refinedweb
3,179
53
6 easy steps to upload your Android library to Bintray/JCenter As part of being a developer, we always write code that can be reused in a lot of places. Rather than copy and paste, it is easier for us to write it once and reuse it wherever we want. But if we really want to be productive we can just add the code to a library and reuse it. This article focuses on how to upload an android library to bintray and some of the issues I have faced along the way. So let’s begin! Step 1: Create an account in Bintray Note: you can also create a private account, but I think you need to activate a monthly subscription plan. But for now, we are creating a free account, which means all the projects added to Bintray should be open sourced. Step 2: Add a repository in Bintray Click on Add New Repository. You should be redirect to the below screen. Enter details of the library project and click on Create. You will be redirected to the following screen if all goes well. Step 3: Open your library project in Android Studio I assume you have already added the project as a library. Now, let’s add the bintray to our project. There is a great plugin that is available which makes it super easy to upload our library to bintray. Let’s add that to our project. Add the following code under the root build.gradle file: classpath 'com.novoda:bintray-release:{latest_version}' You can find the latest version here. Step 4: Add project details to the build.gradle file under the /app directory apply plugin: ‘com.android.library’publish { def groupProjectID = '{package_name}' def artifactProjectID = '{name_of_your_library}' def publishVersionID = 'library_version_code' userOrg = '{username_of_bintray}' repoName = 'repository_name' groupId = groupProjectID artifactId = artifactProjectID publishVersion = publishVersionID desc = '{library description}' website = '{github_url} } Step 5: Upload to Bintray In the terminal in Android Studio, add the below command to clean, build and upload the library to bintray: gradle clean build bintrayUpload -PbintrayUser={userid_bintray} -PbintrayKey={apikey_bintray} -PdryRun=false Note: the items marked in bold need to be filled by you. The userId is your bintray userId and the key is the api key. You can find the api key in bintray website -> Edit Profile -> Api Key. Step 6: Link to JCenter Under your project repository in Bintray, you will see your library along with the version details you had specified. Now all you need to do is click on Add to JCenter. And that’s it! You have to wait until you get a notification in bintray that your library has been accepted to join JCenter before anyone can begin to use your library. Bonus: Now, if you are anything like me, then you must have faced one of the below issues when trying to follow the steps above. I thought of highlighting the issues I’ve faced so it would be helpful to someone else in the future. Issue I: Could not find method google() for arguments [] on repository container. Cause: I found out that this issue was because I had recently updated the android studio to 3.1 and so gradle had to be upgraded to the latest version as well in my local system. Solution: I updated my local gradle from 3.1 to 4.6 (which was the latest at the time of the article). I am using a Mac so I just used the below command to upgrade gradle to the latest version: brew upgrade gradle Note: you need to install homebrew first in order to execute the above command. How to install homebrew is given here. For windows people, please use this guide to update gradle. Issue II: Unable to load class 'org.gradle.api.internal.component.Usage'. Possible causes for this unexpected error include:<ul><li>Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.) Cause: This problem appears because the gradle I used is version 3.4.1, and it is not compatible with the plugin ‘com.novoda:bintray-release:0.4.0’ ‘s gradle version. Solution: Updating to the latest version of the plugin i. e. com.novoda:bintray-release:0.8.0. Issue III: com.novoda.gradle.release.AndroidLibrary$LibraryUsage.getDependencyConstraints()Ljava/util/Set; Cause: For some reason, in the latest version of the plugin, I keep getting this error. An open issue is already added to GitHub. Cause yet not known. Solution: Again not sure what the cause is but for some reason, when we add the plugin first before the library plugin, it seems to work. //has to be BEFORE 'com.android.library' apply plugin: 'com.novoda.bintray-release' apply plugin: 'com.android.library' Issue IV: :[MODULE-NAME]:bintrayUpload: Could not find publication: release. Cause: Again, this is an open issue and the cause is not yet found. Once the cause is identified, I will update it here. Solution: But a workaround has been found which seems to be working. Once your library is uploaded to bintray and has been accepted, you can use your library. For example, my dependency looks like this: //packageName:artifactId:versionId implementation 'com.an.optimize:optimize:0.1.0' And that’s it guys! Hope this article was useful. If you thought this was a good article, please don’t forget to clap. Thanks for reading. Happy coding!
https://medium.com/@anitaa_1990/6-easy-steps-to-upload-your-android-library-to-bintray-jcenter-59e6030c8890
CC-MAIN-2020-40
refinedweb
895
66.44
Patches item #648322, was opened at 2002-12-04 05:55 Message generated for change (Settings changed) made by akuchling You can respond by visiting: Category: Library (Lib) Group: None Status: Open Resolution: None Priority: 5 Submitted By: Kjetil Jacobsen (kjetilja) >Assigned to: A.M. Kuchling (akuchling) Summary: asyncore loop_once and remove poll2 Initial Comment: this patch does two things to asyncore.py, none of them should break any existing code which uses the module: 1) remove the (broken) poll2 function, and rather make a reference from poll2 to poll3 in the module namespace (i.e. if someone actually uses the poll2 function, poll3 will be called instead). 2) add a function loop_once which performs the asyncore loop once instead of until the socket map is empty. asyncore.loop_once has the same function signature as asyncore.loop. ---------------------------------------------------------------------- Comment By: Kjetil Jacobsen (kjetilja) Date: 2002-12-05 13:46 Message: Logged In: YES user_id=5685 asyncore.poll2 is broken because it does not mask the EINTR exception when invoking the poll.poll function. this causes asyncore.poll2 to not have the same semantics as asyncore.poll and asyncore.poll3. i don't see the point in preserving support for the poll2 function, as the poll function is now automatically a part of the select module if the system has poll support. or am i missing something obvious here? :) if use_poll is set and there is no poll on the system, asyncore.loop and asyncore.loop_once will fail the same way they did before. ---------------------------------------------------------------------- Comment By: Martin v. Löwis (loewis) Date: 2002-12-05 11:49 Message: Logged In: YES user_id=21627 Can you please explain in what way poll2 is broken? Also, what happens if use_poll is set, but there is no poll available on the system? ---------------------------------------------------------------------- You can respond by visiting:
https://mail.python.org/pipermail/patches/2003-October/013615.html
CC-MAIN-2017-04
refinedweb
301
65.83
Recently, someone opened an issue on Podman.io: Does Dockerfile USER make sense for podman? The user was attempting to set up a container to run a Postgresql container as non-root. He wanted to create a directory for the Postgresql database in his home directory, and volume mount it into the container: $ podman run -it **-v "$PWD"/html:/output:Z** schemaspy/schemaspy:snapshot -u postgres -t pgsql11 -host 192.168.4.1 -port 5432 -db anitya ... INFO - Starting Main v6.1.0-SNAPSHOT on 9090a61652af with PID 1 (/schemaspy-6.1.0-SNAPSHOT.jar started by java in /) INFO - The following profiles are active: default INFO - Started Main in 2.594 seconds (JVM running for 3.598) INFO - Starting schema analysis **ERROR - IOException** **Unable to create directory /output/tables** INFO - StackTraces have been omitted, use `-debug` when executing SchemaSpy to see them Does running rootless Podman as non-root make sense? The issue he was having was that the directory he created in the home directory, $PWD/html was owned by his UID. This UID looks like root inside of the container, and the Postgresql process inside of the container does not run as root: It runs as the postgres user ( -u postgres). Therefore, the Postgresql process is unable to write to the directory. The easy solution to this problem is to chown the html directory to match the UID that Postgresql runs with inside of the container. However, if the user attempts to chown the file: chown postgres:postgres $PWD/html chown: changing ownership of '/home/dwalsh/html': Operation not permitted They get permission denied. This result is because the user is not root on the system, and is not allowed to chown files to random UIDs: $ grep postgres /etc/passwd postgres:x:26:26:PostgreSQL Server:/var/lib/pgsql:/bin/bash If the user adds sudo to chown the directory, they will get a similar error. Now the directory is owned by UID 26, but UID 26 is not mapped into the container and is not the same UID that Postgres runs with while in the container. Recall from my previous articles on user namespace that Podman launches a container inside of the user namespace, which is mapped with the range of UIDs defined for the user in /etc/subuid and /etc/subgid. On my system, I run with this user namespace: $ podman unshare cat /proc/self/uid_map 0 3267 1 1 100000 65536 This result shows that UID 0 is mapped to my UID, 3267, while UID 1 is mapped to 100000, UID 2 is mapped to 100001, and so on. This result means that inside of the container, UID 26 runs as UID 100025. Excellent, let’s try that: $ chown 100025:100025 $PWD/html chown: changing ownership of '/home/dwalsh/html': Operation not permitted Well, that did not work either. The problem is that even though my user account can run a user namespace with these mappings, I am not currently in a user namespace. I need to use the podman unshare command, which drops you into the same user namespace that rootless Podman uses, so things look exactly the same for unshare as they do for rootless: $ podman unshare chown 100025:100025 $PWD/html chown: changing ownership of '/home/dwalsh/html': Invalid argument Error: exit status 1 Still incorrect. The issue now is that the chown is happening inside of the user namespace, so chown needs to use the original UID, not the mapped UID: $ podman unshare chown 26:26 $PWD/html Outside of the user namespace, this result looks like: $ ls -ld $PWD/html drwxrwxr-x. 2 100025 100025 4096 Sep 13 07:14 /home/dwalsh/html Now, when the user runs the container, it is successful. The Postgresql process inside of the container runs as UID 26 inside of the container (and 100025 outside). But let's get back to the original question: "Does running rootless Podman as non-root make sense?" If you are already running the container as non-root, why should you run Postgresql as a different non-root in the Podman container? By default, rootless Podman runs as root within the container. This policy means that the processes in the container have the default list of namespaced capabilities which allow the processes to act like root inside of the user namespace, including changing their UID and chowning files to different UIDs that are mapped into the user namespace. If you want to run the container as the Postgresql user, you want to prevent this access. This setup also means that the processes inside of the container are running as the user’s UID. If the container process escaped the container, the process would have full access to files in your home directory based on UID separation. SELinux would still block the access, but I have heard that some people disable SELinux. Doing so means that the escaped process could read the secrets in your home directory, like ~/.ssh and ~/.gpg, or other information that you would prefer the container not have access to. If you run the processes within the container as a different non-root UID, however, then those processes will run as that UID. If they escape the container, they would only have world access to content in your home directory. Note that in order to work with the content in these directories, you need to run a podman unshare command, or set up the directories' group ownership as owned by your UID (root inside of the container). With Podman, you want to allow users to run any container image on any container registry as non-root if the user chooses. And I believe that running containers as non-root should always be your top priority for security reasons. [Want to try out Red Hat Enterprise Linux? Download it now for free.]
https://www.redhat.com/sysadmin/rootless-podman-makes-sense
CC-MAIN-2021-31
refinedweb
976
58.42
Faster Web Applications with SCGI June 1st, 2007 by Jeroen Vermeulen in. If that's not what you see, take a look at the shell where you ran the module. It may have printed some helpful error message there. Or, if there is no reaction from the SCGI server whatsoever, the request may not have reached it in the first place; check the Apache error log. Once you have this running, congratulations—the worst is behind you. Stop your SCGI server process so it doesn't interfere with what we're going to do next. Now, let's write a simple SCGI application in Python—one that prints the time. We import the SCGI Python modules, then write our application as a handler for SCGI requests coming in through the Web server. The handler takes the form of a class that we derive from SCGIHandler. Call me unimaginative, but I've called the example handler class TimeHandler. We'll fill in the actual code in a moment, but begin with this skeleton: #! /usr/bin/python import scgi import scgi.scgi_server class TimeHandler(scgi.scgi_server.SCGIHandler): pass # (no code here yet) # Main program: create an SCGIServer object to # listen on port 4000. We tell the SCGIServer the # handler class that implements our application. server = scgi.scgi_server.SCGIServer( handler_class=TimeHandler, port=4000 ) # Tell our SCGIServer to start servicing requests. # This loops forever. server.serve() You may think it strange that we must pass the SCGIServer our handler class, rather than a handler object. The reason is that server object will create handler objects of our given class as needed. This first incarnation of TimeHandler is still essentially the same as the original SCGIHandler, so all it does is print out request parameters. To see this in action, try running this program and opening the scgitest page in your browser as before. You should see something like Listing 3 again. Now, we want to print the time in a form that a browser will understand. We can't simply start sending text or HTML; we first must emit an HTTP header that tells the browser what kind of output to expect. In this case, let's stick with simple text. Add the following near the top of your program, right above the TimeHandler class definition: import time def print_time(outfile): # HTTP header describing the page we're about # to produce. Must end with double MS-DOS-style # "CR/LF" end-of-line sequence. In Python, that # translates to "\r\n. outfile.write("Content-Type: text/plain\r\n\r\n") # Now write our page: the time, in plain text outfile.write(time.ctime() + "\n") By now, you're probably wondering how we will make our handler class call this function. With SCGI 1.12 or newer, it's easy. We can write a method TimeHandler.produce() to override SCGIHandler's default action: class TimeHandler(scgi.scgi_server.SCGIHandler): # (remove the "pass" statement--we've got real # code here now) # This is where we receive requests: def produce(self, env, bodysize, input, output): # Do our work: write page with the time to output print_time(output) We ignore them here, but produce() takes several arguments: env is a dict mapping CGI parameter names to their values. Next, bodysize is the size in bytes of the request body or payload. If you're interested in the request body, read up to bodysize bytes from the following argument, input. Finally, output is the file that we write our output page to. If you have SCGI 1.11 or older, you need some wrapper code to make this work. In these older versions, you override a different method, SCGIHandler.handle_connection(), and do more of the work yourself. Simply copy the boilerplate code from Listing 4 into the TimeHandler class. It will set things up right and call produce(), so nothing else changes, and we can write produce() exactly as if we had a newer version of SCGI. Once again, run the application and check that it shows the time in your browser. Next, to make things more interesting, let's pass some arguments to the request and have the program process them. The convention for arguments to Web applications is to tack a question mark onto the URL, followed by a series of arguments separated by ampersands. Each argument is of the form name=value. If we wanted to pass the program a parameter called pizza with the value hawaii, and another one called drink with the value beer, our URL would look something like. Any arguments that the visitor passes to the program end up in the single CGI parameter QUERY_STRING. In this case, the parameter would read “pizza=hawaii&drink=beer”. Here's something our TimeHandler might do with that: class TimeHandler(scgi.scgi_server.SCGIHandler): def produce(self, env, bodysize, input, output) # Read arguments argstring = env['QUERY_STRING'] # Break argument string into list of # pairs like "name=value" arglist = argstring.split('&') # Set up dictionary mapping argument names # to values args = {} for arg in arglist: (key, value) = arg.split('=') args[key] = value # Print time, as before, but with a bit of # extra advice print_time(output) output.write( "Time for a pizza. I'll have the %s and a swig of %s!\n" % (args['pizza'], args['drink']) ) Now the application we wrote will not only print the time, but also suggest a pizza and drink as passed in the URL. Try it! You also can experiment with the other CGI parameters in Listing 3 to find more things your SCGI applications can do.. Subscribe now! Featured Video Linux Journal Gadget Guy, Shawn Powers, takes us through installing Ubuntu on a machine running Windows with the Wubi installer. Great article On April 13th, 2008 Yorumcu (not verified) says: Thanks for article. It's work. ---------------------------------- Betsson Casino Euro
http://www.linuxjournal.com/article/9310
crawl-001
refinedweb
966
65.42
I'm a new poster here, and a complete and total beginner at programming. I decided to start with Python since I'd read that it was an easy one to learn for beginners. I'm using some online tutorials, and one of the exercises was to work on some code for a small quiz program. However, I keep getting a strange syntax error, and I can't get the reason. I was hoping that someone experienced could take a look and tell me what I'm missing? Thanks a lot. def main_menu(): print("1. Print the menu") print("2. Take the test") print("3. Quit the program:") def get_questions(): return[["What color is the daytime sky on a clear day? ", "blue"], ["What is the answer to life, the universe and everything? ", "42"], ["What is a three letter word for mouse trap? ", "cat"], ["What noise does a truly advanced machine make?", "ping"]] def check_question(question_and_answer): question = question_and_answer[0] answer = question_and_answer[1] given_answer = input(question) if answer == given_answer: print("Correct") return True else: print("Incorrect, correct was:", answer) return False def run_test(questions): if len(questions) == 0: print("No questions were given.") return index = 0 right = 0 while index < len(questions): if check_question(questions[index]): right = right + 1 index = index + 1 print("You got", right " 100 / len(questions),\ % right out of", len(questions)) choice = 1 while choice != 3: if choice == 1: #Here's where I get a syntax error, in a small space right before the if. main_menu() elif choice == 2: run_test(questions) print() choice = int(input("Choose an option: ")) print("Goodbye")
http://forum.codecall.net/topic/64536-beginners-syntax-error/
CC-MAIN-2018-43
refinedweb
261
74.59
24 February 2010 15:58 [Source: ICIS news] LONDON (ICIS news)--The crude oil markets initially fell by about 40 cents on Wednesday, adding to earlier small losses, when this week’s US stock figures showed a larger-than-forecast build on crude, although this was countered by an unexpected draw on gasoline. April NYMEX light sweet crude futures fell from around $78.85/bbl before the figures from the Energy Information Administration (EIA) were published to around $78.45/bbl, which was a loss of 41 cents from the previous close of $78.86/bbl but above the earlier low of $78.25/bbl. However, it then regained some ground and at 15:40 GMT, April NYMEX crude was trading around $79.25/bbl, up 39 cents from the previous close. On ?xml:namespace> At 15:40 GMT, April Brent was trading around $77.65/bbl, up 40 cents from the previous of $77.25/bbl. Analysts’ predictions for this week’s US stock figures were that they would show a build on crude stocks of about 2.0m bbl and on gasoline of around 400,000 bbl, but a draw on distillate of around 1.6m bbl. The figures from the American Petroleum Institute (API) were published late on 23 February.
http://www.icis.com/Articles/2010/02/24/9337662/crude-prices-seesaw-as-us-stock-build-countered-by-gasoline.html
CC-MAIN-2014-52
refinedweb
213
72.56
i am new to codeing,as i have just finshed the codecademy.com course on python. i was looking for somthing to get my brain going and decided to creat a code to interact whit thepiratebat.sx and return the torrents name and seed number,as well as a few outer fetures i had in mind.. this is what i got into: - Code: Select all import urllib2 header = "http://" def check(): "try:" search_page = "" results = urllib2.urlopen(header+search_page) print results print "done checking..." search = raw_input("what would you like to search for?:") ender = "/search/"+str(search)+"/0/7/0" search_results = urllib2.urlopen(header+str(search_page)+ender) raw_page = search_results.read() print search_results print raw_page """except: print "it looks like the pirate bay is not reach-able..." """ when i run check() and go throw the search veriable the shell window get stuck...i realy have no idea what is going on..can any of you figure it out?
http://www.python-forum.org/viewtopic.php?f=17&t=3777&p=4533
CC-MAIN-2017-09
refinedweb
156
69.48
. For general usage, you can pretty much use any DAC chip. But for better performance, a parallel interface DAC should be used since the digital input bits can be loaded simultaneously rather than being shifted in one by one. The conversion time of the DAC dictates the maximum achievable frequency. Most of the mainstream DAC chips nowadays can operate at more than 100 kHz. Keep in mind though that the number of bits used as waypoints to generate the output waveform also affects the maximum achievable frequency. So a 12 bit DAC that can operate at 100 kHz and output a square wave up to 100 kHz (1bit) may only be able to generate a 25 Hz signal if all the 12 bits are used as waypoints. In general though, we rarely use more than a few hundred waypoints so the typical operating frequencies that can be achieved are well above 1 kHz which is more than adequate in most cases. In this example, a 12 bit DAC (LTC1450) is used. It can operate stably at 200 kHz (1 bit) and the full resolution (12 bit) waveform frequency is around 50 Hz. The wiring for this DAC is very straightforward. As you can see in the sample code below, the parallel input interface (D0-D11) is connected with 12 of ATmega328’s digital and analog pins (the analog pins are used as digital outputs as well). In addition to DAC’s input pins, three additional pins are used to control the DAC. #include <TimerOne.h> const int pinD0 = 14; //PC0; -- D0 const int pinD1 = 15; //PC1; -- D1 const int pinD2 = 16; //PC2; -- D2 const int pinD3 = 17; //PC3; -- D3 const int pinD4 = 18; //PC4; -- D4 const int pinD5 = 19; //PC5; -- D5 const int pinD6 = 2; //PD2; -- D6 const int pinD7 = 3; //PD3; -- D7 const int pinD8 = 4; //PD4; -- D8 const int pinD9 = 5; //PD5; -- D9 const int pinD10 = 6; //PD6; -- D10 const int pinD11 = 7; //PD7; -- D11 const int pinCSLMSB = 12; //PB4; -- CSLSB, CSMSB const int pinWR = 11; //PB3; const int pinLDAC = 10; //PB2; unsigned int counter = 0; void setup() { //LTC1450 ADC output pins pinMode(pinD0, OUTPUT); pinMode(pinD1, OUTPUT); pinMode(pinD2, OUTPUT); pinMode(pinD3, OUTPUT); pinMode(pinD4, OUTPUT); pinMode(pinD5, OUTPUT); pinMode(pinD6, OUTPUT); pinMode(pinD7, OUTPUT); pinMode(pinD8, OUTPUT); pinMode(pinD9, OUTPUT); pinMode(pinD10, OUTPUT); pinMode(pinD11, OUTPUT); //LTC1450 control pins pinMode(pinCSLMSB, OUTPUT); pinMode(pinWR, OUTPUT); pinMode(pinLDAC, OUTPUT); digitalWrite(pinCSLMSB, HIGH); digitalWrite(pinWR, HIGH); digitalWrite(pinLDAC, HIGH); digitalWrite(pinCSLMSB, LOW); digitalWrite(pinWR, LOW); //set timer interval to 100ns //the output frequency is determined byinputs //the number of sample points used in the DAC //in this example, 8 values are used and thus //the frequency is roughly 1s/800ns. //The actual frequency is slighly lower //(in this case 1.1 khz) Timer1.initialize(100); Timer1.attachInterrupt(onTimer); } void onTimer() { //CSLSB/CSMSB=0, WR=0; PORTB &= ~(_BV(PB4) | _BV(PB3)); //set the lower 6 bits (bit 0 to 5) //which corresponds to PC0 to PC5 PORTC = (counter & 0x3F); //set the higher 6 bits (bit 6 to bit 11) //the value is right shifted by 4 since the first //port in PORTD we use is PD2 PORTD = (counter & 0xFC0)>>4; //CSLSB/CSMSB=1, WR=1; PORTB |= _BV(PB4) | _BV(PB3); //Load DAC PORTB &= ~_BV(PB2); PORTB |= _BV(PB2); //generate 8 staircases counter += 500; //reset counter if (counter >= 4096) counter = 0; } void loop() { } Note that both CSLSB and CSMSB of LTC1450 are connected together to enable parallel loading of all 12 bits. For maximum efficiency, I used AVR routines within the timer routine directly as they are significantly faster than the corresponding Arduino functions. For the setup() routine, I used Arduino functions since speed is not an issue as they are called only once and the pin assignment can be seen a bit more clear. I used the 16 bit timer interrupt for precise DAC timing. If the timing requirement is not critical, bitbanging method can also be used. The pins are arranged in such a way that 6 bits are mapped to PORT C pins and 6 bits are mapped to PORT D pins and the bit ordering is the same order (i.e. low to high) as in the corresponding ports. This arrangement is necessary to ensure all 12 bits can be loaded with just two instructions: PORTC = (counter & 0x3F); PORTD = (counter & 0xFC0)>>4; Other pin arrangements are also possible but will require more instructions to load and thus reduce the maximum achievable waveform frequency. The output frequency can be controlled in two places. The first place is the timer interval and the second place is the number of bits used to represent each waveform. While the example above only shows the generation of a fixed staircase signal, other arbitrary waveforms of varies frequencies can be easily achieved by modifying the onTimer portion of the code. Here is the oscilloscope output from the signal generated above. Hello I built the circuit for this using a Ad667 and atmega128. works fine ,no problems. Modded the Timer1 library for the atmega128 timer3. I use countL = 0; and countH = 4094; to start and in OnTimer if (countL >= countH) countL = 0; My question is – How can I change countL and countH during runtime? I am using an rotary encoder, works fine to display a low and high number on a LCD disply. As the encoder is turned, the code generates a low value(encL) and a high value(encH). Any help? Thanks James Where do I find the schematic? Can you provide a schematic of the entire system.
http://www.kerrywong.com/2011/02/26/arbitrary-waveform-generation-with-arduino/
CC-MAIN-2020-29
refinedweb
926
54.46
User talk:Chronarion From Uncyclopedia, the content-free encyclopedia Sign your name with the sign button above if you leave a message. Cleaned up! Old messages archived here: archive 1. edit Sighting! Holy crap! You still exist! We thought that the dingos had eaten you. Is this the result of a major life crisis or a just sign that you've been released from the dungeon? Sir Famine, Gun ♣ Petition » 04/29 02:03 edit Fisher Price wtf? I don't know who to talk to about this, but someone has vandalized the Fisher Price manuscript! Kip the Dip - Okay, never mind. I fixed it. It said "Go eat shit Uncyclopedia". Kip the Dip 12:58, 1 May 2007 (UTC) editTemplate:Hey I'm giving out cookies. You got 10 because you founded Uncyclopedia. -:14, 7 May 2007 (UTC) edit Autograph Seeing as you founded the greatest encyclopedia ever, could I have your aut don't really expect you to answer, but what country did uncyclopedia start in?--TheNewYarkov 01:10, 3 June 2007 (UTC) - It started in the US, then it took over the) - Its not an encyclopedia, its an UNcyclopedia. None of it is real nor to be taken seriously. Its a light-hearted view of the world. No-one seriously believes what is written here. I can understand not everyone finds it funny, but take a chill pill and leave the site if you don't like it. There are a lot of things on the internet which people can find offensive, but the thing about the post-modern age is that you can't censor people, we all have a right to our voice, even you, in the appropriate medium. ~ Dame Ceridwyn ~ talk DUN VoNSE arc2.0 11:27, 03 June 2007 - Um...the IP just called George Bush great. Even if he's talking about George Senior, it indicates a lack of reality in the inner region of said IP's brainial cavity. Unless he meant "great" as in "big", 'cause both Georges are, like, eight feet tall. Isn't satire generally the opposite of propaganda? Also, this isn't my talkpage. Sir Modusoperandi Boinc! 23:38, 3 June 2007 (UTC) - Yeah I decided to gloss over that bit, though it did cause me to choke on my tea somewhat. Its not my talkpage either but when has that ever stopped us? :P ~ Dame Ceridwyn ~ talk DUN VoNSE arc2.0 11:45, 03 June 2007 - Just make sure to clean up before you leave. I'll get the broom. Sir Modusoperandi Boinc! 23:54, 3 June 2007 (UTC) - Also, little late, but since Chron sold it over to Wikia, it's really Sannse, Angela, or Splaka that you should be bitching to.-Sir Ljlego, GUN VFH FIYC WotM SG WHotM PWotM AotM EGAEDM ANotM + (Talk) 21:34, 11 August 2007 (UTC) - No, he called him "greate", surely by early medieval standards either of the Bush's can fit into this this is one of my first edits on Uncyclopedia. I'm from Wikipedia (and Nahuatl Huiquipedia) as you may guess and most of my very few edits on Uncyclopedia had been towards Keane. Let me tell you something about people taking serious or not this. A few weeks ago, it happened the members of the band I said just found their own article on Uncyclopedia, and they liked it! Yeah, it's an offensive (even a bit for me) article but they just enjoyed it instead of complaining. You're not sure if people would like what they'll see. Maybe George Bush comes across his article and laughs at it. You can't ask to stop the Uncyclopedia (apart from uncensorment) 'cause is the cool counterpart of the wiki. If I get tired of Wikipedia (which happens very often), I come here and read any article to lol myself! Long life for Uncyclopedia. Long life for Wikipedia. One wouldn't survive now without the other. Who else would make satirical the reality and seriousness of Wikipedia? Who else would clarify what people may confuse on Uncyclopedia? And anyway, Bush it's not great. That's just a matter of opinion.--Fluence 01:20 26 August 2007 (UTC-5) edit Please change my name Can you please change my name from Edmundkh to EdmundEzekielMahmudIsa, then leave me a message in the English Wikipedia? Thank you very much! --Edmund the King of the Woods! 12:16, 21 August 2007 (UTC) edit Password Sir: Forgive me, but I am unable to log into my account: User:Morsa. The password I have written down is apparently incorrect—and, because I am paranoid about registering my e-mail address to any site, I cannot use the E-Mail Password function. Is there any way you or another administrator could retrieve my password for me? According to my paper, it is an eleven-letter mathematical term (although, obviously, I could be wrong). Thank you for your assistance. 75.71.94.153 03:36, 11 October 2007 (UTC) - I'm not Chron, but since he rarely comes here, I'll answer for him. You want to get in contact with someone from Wikia's staff, since they're the ones with that kind of power. Sannse's our resident staffer/sysop, so you may want to start with her. However, most other staffers only rarely come to Uncyc. Hope that helps. —Hinoa talk.kun 03:42, 11 October 2007 (UTC) edit Merry Xmas! --YeOldeLuke 08:00, 26 December 2007 (UTC) edit Welcome! Hello, Chron. Or you can put {{adoptmecat}} if you don't want to show a big userbox. Again,:45, Jan. 3, 2008 edit Former Yugoslav Republic of Macedonia Former Yugoslav Republic of Macedonia? come on it's supposed to be funny... not nationalist... what's with the flag. i changed the page to be funnier, but dumbass greeks and bulgarians dont like it without propaganda so they reverted it... do something, for the sake of uncyclopedia at least. Guitardemon666 18:19, 22 April 2008 (UTC) edit WEENIES! JYN3 2008 This is the 12th. One year of 3XCELLENCE given out. --Sir General Minister G5 FIYC UPotM [Y] #21 F@H KUN 10:54, 12 June 2008 (UTC) edit Dude Good to see you editing again... We kept your room just as you left it. You know, like one of those creepy shrines people have for their dead kids or something. -- Sir Codeine K·H·P·B·M·N·C·U·Bu. · (Harangue) 21:54, 23 September 2008 (UTC) edit Question Are you really the founder of uncyclopedia? edit Help I'm an administrator of Hungarian Unciklopédia. Help, if you can! Please to control session data processing, because I can't edit, only anonim. Thanks. OsvátA Palackposta 14:12, 24 January 2009 (UTC) - I think you may be looking for Carlb--<< >> 15:34, 24 January 2009 (UTC) - Thanks. Carlb is a man of silence. OsvátA Palackposta 18:33, 24 January 2009 (UTC) edit Reitterating Forum:Silicon Valley Meetup? in case it got too clogged, too quickly I'm up in San Francisco and it wouldn't take much effort to get down to Silicon Valley, or vice versa. I'd definitely be up for a meetup, grabbing a drink or some such similar thing. Drop me an "E-mail this user" with some contact information. -, 30 January 2009 (UTC) edit Username change request Hi Chronarion, could you please change my username from User:Joshuaissac to User:Joshua Issac please? I did not know that spaces were allowed in usernames when I signed up. Thanks. --Joshuaissac 23:46, 4 February 2009 (UTC) - I believe Chronarion is being rather inactive at the moment... -Sockpuppet of an unregistered user 23:48, 4 February 2009 (UTC) - Thank you Sockpuppet of an unregistered user; I'll ask PantsMacKenzie. --Joshuaissac 00:17, 6 February 2009 (UTC) - Nope, you need to talk to Sannse. Or just create a new account with that name, and stop using your old:55, Feb 6 - Thanks. I'll ask Sannse. --Joshuaissac 15:08, 6 February 2009 (UTC) edit press hi mr. chronarion. as the founder and high lord of uncyclopedia, might you take a glance at The Uncyclopedia UnSignpost and give your impressions of it? we try to keep users informed of goings-on at the wiki, and a sound byte from you would certainly be cause for an extra edition! 19:36, 26 June 2009 (UTC) edit Celebrating my 1000th game namespace edit!!!! —Flutter (Talk•Games•Fun Pages•Awards•Help) 23:27, 26 June 2009 (UTC) edit Your wiki design Unlike most wikis, Uncyclopedia's page design exactly resembles Wikipedia's page design. Unfortunately, other wikis are not like that and have that space inbetween the computer wall and the side of the wiki....not sure if you know what I'm talking about, but, like, there would be more room with the amount of space Uncyclopedia's articles have. I was wondering how you were able to make the articles that way. For them to be wider than regular wikis' articles. --Zzgutiar14 11:01, 30 July 2009 (UTC) To be quite honest, I have no idea! :D I long forgot --Chronarion 05:39, September 20, 2009 (UTC) edit UnCon Hello sir, i thought of the best idea since uncyclopedia: UnCon. Thats right, UnCon-a convention where Uncyclopedians meet once a year to share ideas, sell uncyclopedia merchandise, and other cool stuff! Get back 2 me, Clay men are just like slugs-they have no basis in reality 23:40, October 24, 2009 (UTC) edit You Huang Are you the Jonathan "Chronarion" Huang that created this hilarious Uncyclopedia site? If so, give me the Uncyc timeline. Wikipedia says racist articles are disallowed, but how come all the profane and sexual articles stay? And tell me the name of every sister project. edit Hello, and thanks. . . . . .for nailing together this fine boat. Lots of good sailing since. Why don't you shock everyone here and come back and start editing again, at least for a few days or weeks. That would be fun for all involved--and as far as I know you haven't even made the Hall of Shame yet! It would be nice to have your take on the current crop of writers, and where the uncy has gone since you started it up, after it moved to wikia, and the f u t u r e...... Thanks again, and your fine work is appreciated by many. Aleister 18:42 21 7 MMX edit Contest today, August 2nd (U.S. time) or 3rd (civilized world time) MMX edit Nice pic So winning the Useless Gobsite of the Month got you back? Should have done it sooner. Or was it you came up with a good pic, joining the universal dislike of Bill O'Reilly. Nice to have you back, and it'd be fun if you stuck around for awhile to inspire us noobies. Aleister 8:53 13 11 edit HOLY CRAP!!! Are you actually back on Uncyclopedia? --Revolutionary, Anti-Bensonist, and TYATU Boss Uncyclopedian Meganew (Chat) (Care for a peek at my work?) (SUCK IT, FROGGY!) 15:02, December 18, 2010 (UTC) edit Adoption I was just running through the list of potential adoptees and your name sprung up. I'm willing to adopt you, but I do need to warn you I am a hard taskmaster. Why haven't you added anything new since November? Get back to work, adoptee! • Puppy's talk page • 00:40, June 5, 2009 Friday, 06:43, Jan 14 2011 UTC - Your disrespect for our brutal government of Cabal Doom and our Glorious Leader Chronarion means your gonna get raped, shaved and shot by Olipro. Then we'll send your spunk filled torso back to your family. 'Sorrry Great Chonarion, that you were disturbed' /Me does Arnold Rimmer salute while leaving to summon Olipro...--Sycamore (Talk) 06:54, January 14, 2011 (UTC) edit HOLY SHIT You created the website? You did this all? Amazing. How about coming back soon, and joining the UnFun Gang. -- 23:59, January 20, 2011 (UTC) edit "You had created the Uncyclopedia????" You had created the Uncyclopedia???? 189.81.8.152 03:19, March 12, 2011 (UTC) - Yes. -- Brigadier General Sir Zombiebaron 07:18, March 12, 2011 (UTC) edit Mirror Uncyc (Aliciapedia) Chron? Somebody created an account here in your name, but I don't think that it is you. Is it really you? Alicia Keys 23:37, May 26, 2011 (UTC) edit Oh My God!!!!! Oh...My...God! I'm on Chronarion's talk page! I feel like i'm gonna pass out! Okay, so you are, like, my internet hero, as you have created the best website in the history of the internets. Autograph pl0x :)))))))))))))))))))))))))))))))))))))))))))))))))). *passes out and random keystrokes ensue as head is on keyboard* r9iguf35ptif35[pofk3rg0[ori3g[f0o5iit53ujfm;p3mfkvewrfvjrj3rgopr3gj3ropgjr3opgjr3pojgpr3og --BieberAxeKiller (talk) 21:17, May 12, 2012 (UTC)
http://uncyclopedia.wikia.com/wiki/User_talk:Chronarion
CC-MAIN-2015-35
refinedweb
2,153
74.69
So, I bought a DRV8835 (from one of your Canadian distributors). I plugged it into a breadboard I have set up with an Arduino Nano, a servo, a pot, and a 5 volt regulator. The whole thing is run off a 7.4 volt Lipo, which feeds into the 5 volt regulator (1 amp, switcher). The 5 volt output from the regulator (I’ll call it Vcc) powers both the Nano, and the servo. It also feeds into Vcc on the DRV8835, but I had BATT+ going into Vin. The code looks like this: [code]#include <Servo.h> #include <Metro.h> #define POT_PIN 0 #define MOTOR_PWM_PIN 5 #define MOTOR_DIR_PIN 4 #define RUDDER_SERVO_PIN 3 #define LED_PIN 13 Servo rudder; Metro heartbeatTimer = Metro(250); int ledState; void setup() { rudder.attach(RUDDER_SERVO_PIN); digitalWrite(MOTOR_DIR_PIN, 0); analogWrite(MOTOR_PWM_PIN, 0); ledState = 0; } void loop() { int potPosition = analogRead(POT_PIN); int servoAngle = map(potPosition, 0, 1023, 0, 180); int motorSpeed = map(potPosition, 0, 1023, 0, 255); rudder.write(servoAngle); analogWrite(MOTOR_PWM_PIN, motorSpeed); if (heartbeatTimer.check()) { digitalWrite(LED_PIN, ledState); ledState = !ledState; } delay(50); } [/code] I powered it up, and the motor started running for a few seconds, and then stopped. After that, it has been completely unresponsive. I checked, and I’m definitely getting PWM input into BENBL, and BPHASE is low. I also tried switching channels (from B to A), but the results were the same (nothing). The motor I’m using is a Tamiya motor from one of their submersible pods. It does not have any gearing, and there shouldn’t be a lot of load on the motor, so the current shouldn’t be too high. Should I be adding some protective diodes on this setup? - Jon
https://forum.pololu.com/t/drv8835-dead/6752/7
CC-MAIN-2018-13
refinedweb
282
66.13
A platform independent way to set your Python Path for your Python applications In a software development house where desktop computers run Microsoft Windows while servers run Linux, software developers will have to ensure that the Python code that they wrote on their Windows machine can run on the deployment servers which are running Linux. One unavoidable task for Python application developers is the importing of functionalities that are contained in other Python scripts. In order for the Python interpreter to find the Python scripts that are referenced by Python import statements, the Python Path will need to contain the URLs of the directories that contain the Python scripts to be imported. This post documents how I set my Python Path for my Python applications in a platform independent way. The platform dependent way to set your Python Path One platform dependent way that you may configure your Python Path is by setting the PYTHONPATH environment variable through a script file targeted at the native command-line interpreter that is provided by the Operating System where your Python application will run on. To run your Python application on Windows, you may create a batch file, run.bat with the following contents: set PYTHONPATH=%PYTHONPATH%;C:\your_python_lib python app.py And to run your Python application on Linux, you may create a shell script, run.sh with the following contents: export PYTHONPATH=$PYTHONPATH:/your_python_lib python app.py This approach of configuring Python Path for your Python applications will result in duplicated effort whenever you import new library scripts that are located in new directories. The platform independent way to set your Python Path Setting your Python Path in a platform independent way will avoid duplicated effort whenever you need to import new library scripts that are located in new directories. I typically follow the following guidelines to set my Python Path in a platform independent way: - Place the library scripts in a directory that is near to the starter script. - Set Python Path inside the starter script. Placing the library scripts in a directory that is near to the starter script I tend to follow the following directory structure whenever I need to create new Python applications: . |--app.py |--import |--techcoil |--__init__.py |--controller |--__init__.py |--users.py !--products.py |--storage |--__init__.py |--mongo.py |--file.py |--service |--__init__.py |--users.py |--products.py In the above directory structure, I designate app.py as the starter script. I then designate a directory , which I named as import, in the same directory as app.py. I will place the module packages that my Python application need to import inside the import directory. Setting Python Path inside the starter script To set the Python Path inside the starter script, I will include the following Python codes at the top: import os import sys root_directory = os.path.dirname(os.path.realpath(__file__)) sys.path.append(os.path.join(root_directory, 'import')) ### Application specific logic ### In the above codes, I first import the os and sys in-built Python modules. I then proceed to get the directory path where the executing script resides in (in this case, app.py) and set the value to the root_directory variable. I then construct the url to the import directory and append it to the sys.path variable. This will make the modules inside the import directory visible to the Python interpreter.
https://www.techcoil.com/blog/a-platform-independent-way-to-set-your-python-path-for-your-python-applications/
CC-MAIN-2021-04
refinedweb
562
52.49
Work at SourceForge, help us to make it a better place! We have an immediate need for a Support Technician in our San Francisco or Denver office. You can subscribe to this list here. Showing 2 results of 2 Just trying out the latest CVS Tcl/Tk (8.5) on MacOS X 10.2.8, and found that the following Wish commands lead to an error message ("The application Wish has unexpectedly quit.") when the Tk window is destroyed using the red traffic light control. wm withdraw . toplevel .t wm protocol .t WM_DELETE_WINDOW exit It did quit (as it should) but it isn't unexpected, if you see what I mean. I believe it is quite a recently introduced problem. Anyway, before I got to this point, I was absolutely LOVING the new look text! Congratulations and thanks to Benny and Daniel for getting it into CVS. Best wishes, Alastair Hi, I just started mucking with wikit and have run across a problem. I don't seem to be able to display images using the technique shown on the tcltk wiki. Here is the code on the home page of my local wiki ----------------- '''Welcome to your own wiki!''' ''Congratulations'' - you're looking at the home page of a freshly created wiki. To get started, you can just start editing this page and replace what's here with your own text. See the [Help] page for information on editing and formatting your wiki. This is a [Sample] page. Here is how to add [images]. This is a picture [] followed by text. Here is [] -------------- The wiki data file is named wikit.tkd I have edited the 'images.tcl' file in wikit to replace export LocalImages with namespace export LocalImages. The images are present in the data file [macjerry:~/Desktop/Wiki]$ ./wikit -images list wikit.tkd 2 image cache entries: 80729 2006/04/03 695877 2002/09/19 On my mac ( Aqua BLT dist) the "image" urls show up as footnotes. If I copy the data file to my linux box the images do properly display themselves... Is there a fix? Jerry
http://sourceforge.net/p/tcl/mailman/tcl-mac/?viewmonth=200604&viewday=4
CC-MAIN-2014-35
refinedweb
349
76.82
Hi Andreas, Andreas Tille <andr...@an3as.eu> writes: > On Fri, Apr 13, 2018 at 09:35:39AM +0200, Ole Streicher wrote: >> Andreas Tille <andr...@an3as.eu> writes: >> > On Thu, Apr 12, 2018 at 09:22:35PM +0200, Ole Streicher wrote: >> > Hmmmm, >> > but no --udd option for the /usr/share/blends-dev/blend-gen-control >> > call. How are you triggering the UDD option at your side? >> >> Inside of blend-gen-control, see >> : >> >> if 'GENCONTROL_OPTS' in os.environ: >> opts = parser.parse_args(os.environ['GENCONTROL_OPTS'].split()) >> parser.set_defaults(**opts.__dict__) > > I've read this - but how did you actually *used* this setting. > What are you doing on your side to trigger the UDD option? I just added it to my Makefile and it works. Complete astro/Makefile: ``` #!/usr/bin/make -f BLENDMAKEFILE=/usr/share/blends-dev/Makefile CheckBLENDMakefile := $(shell if [ -e $(BLENDMAKEFILE) ] ; then echo 1 ; else echo 0 ; fi) ifeq ($(CheckBLENDMakefile),1) include $(BLENDMAKEFILE) else err := $(shell echo "$(BLENDMAKEFILE) is missing. Please install blends-dev package!") endif export GENCONTROL_OPTS := --udd dummy: @echo $(err) ``` Note that in the moment, the GENCONTROL_OPTS need to be defined *after* the blends-dev/Makefile inclusion, since the latter set it to be empty (I'll change that in a moment, however). > Well, also apt cache is a moving target. So if we do not talk about > reproducible test conditions and just want to debug the libodil0-dev > issue in a defined time frame, the debug task can be helpful. Yes; I finally did a minimal blend with one task containing just that one dependency. > In summary: I'm fine with a 0.7.0 release to unstable if there is a > documented way to turn on the UDD option. (I'm obviously to stupid and > always need to trigger it manually. :-((((( ) Check if the thing above works. Cheers Ole
https://www.mail-archive.com/debian-blends@lists.debian.org/msg02495.html
CC-MAIN-2018-43
refinedweb
301
57.77
Algorithm to copy the recorded pitches into the tuning curve. More... #include <resettorecording.h> Algorithm to copy the recorded pitches into the tuning curve. This algorith simply copies the recorded pitches. This works also in the case where the keys were only partially recorded. If A4 has been recorded and the ConcertPitch is different, the pitches will be shifted to the wanted ConcertPitch. Therefore, to get an unshifted copy, the ConcertPitch in the settings should be the same as the recorded A4. If A4 was recorded it is assumed that A4=440Hz. This algorithm shows the coder how algorithms can be implemented. It can also be used by the users to copy or shift an existing tune. Definition at line 47 of file resettorecording.h. Constructor of the copy algorithm. Definition at line 46 of file resettorecording.cpp. Worker function in which the computation thread is carried out. Definition at line 60 of file resettorecording.cpp.
http://doxygen.piano-tuner.org/classresettorecording_1_1_reset_to_recording.html
CC-MAIN-2022-05
refinedweb
156
68.97
Today, We want to share with you Laravel 6.2 Create Custom Helper Tutorial with Example.In this post we will show you laravel 6.0 custom helpers, hear for Custom Helper Functions in Laravel 6.2 we will give you demo and example for implement.In this post, we will learn about Custom Helper Functions in Laravel6.2 with an example. Laravel 6.2 Create Custom Helper Tutorial with Example There are the Following The simple About Best Practices for Custom Helpers in Laravel 6.2 Full Information With Example and source code. As I will cover this Post with live Working example to develop how to call helper function in laravel blade, so the create helper in laravel command is used for this example is following below. Phase 1 : Create Custom-helpers.php File app/Custom-helpers.php <?php function convertBasicPrice($money,$from_price,$to_price){ $apiKey = '9898-dfsds-sd56sds-sdsdsd'; $from_Price = urlencode($from_price); $to_Price = urlencode($to_price); $query = "{$from_Price}_{$to_Price}"; $json = file_get_contents("{$query}&compact=ultra&apiKey={$apiKey}"); $results = json_decode($json, true); $data = floatval($results["$query"]); $output = $data * $money; return number_format($output, 2, '.', ''); } Phase 2 : Define Laravel 6 Helper in composer.json root/composer.json "autoload": { "psr-4": { "App\\": "app/" }, "classmap": [ "database/seeds", "database/factories" ], "files": [ "app/Custom-helpers.php" ] }, load the file globally run this commands in laravel 6.2 composer dump-autoload Phase 3 : Use in Controller PriceController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Response; class PriceController extends Controller { public function index() { $total_money = convertBasicPrice(15, 'INR', 'GBP'); echo $total_money; } } Phase 4 : Use in Laravel 6.2 Blade File Laravel 6.2 view blade file @extends('layouts.app') @section('content') <h3>Laravel 6.2 Create Custom Helper With Example</h3> @php $total_money = convertBasicPrice(15, 'INR', 'GBP'); echo $total_money; @endphp @endsection Web Programming Tutorials Example with Demo Read : Summary You can also read about AngularJS, ASP.NET, VueJs, PHP. I hope you get an idea about how to use helper function in laravel. I would like to have feedback on my infinityknow.com blog. Your valuable feedback, question, or comments about this article are always welcome. If you enjoyed and liked this post, don’t forget to share.
https://www.pakainfo.com/laravel-6-2-create-custom-helper-tutorial-with-example/
CC-MAIN-2022-05
refinedweb
363
51.65
Annual Overview 2004 delivering more REVENUE SPLIT BY DIVISION 2004 2003 ��� ��� Mail Express Logistics ��� ��� ��� ��� TOTAL SHAREHOLDER RETURN OPERATING INCOME ���� 40 ���� 20 ��� ��� 0 ��� -20 -40 Total ��� 2000 2001 2002 2003 2004 (8.2) (4.3) (35.3) 23.5 10.6 � ���� ���� ���� ���� ���� ��� ����� ����� ��� ����� ��� ��� ��� ��� ��� ��������������������������������� Key figures 2004 Revenues Operating income (EBIT) 2003 % 12,635 11,866 6.5% 1,174 767 53.1% Net income 667 300 122.3% Underlying net income from continuing operations 1 667 592 12.7% Operational cash flow (11) (10) (10.0%) Earnings per share (€ cents) 140.9 63.1 123.3% Underlying earnings per share (€ cents) 1 140.9 124.6 13.1% 57 48 18.8% Dividend (€ cents) Social Responsibility footprint 2004 Number of employees 2003 % 162,244 163,028 Gender profile: male / female (in %) 63 / 37 64 /36 Number of vehicles 22,387 22,026 Number of aircraft 42 43 71% 69% 2.9% Money spent on community initiatives (in € millions) 8,764 4,997 75.4% CO2 footprint (tonnes of CO2 equivalent) 1,233 1,162 6.1% ISO 9001 certification (% of company covered) (0.5%) (2.3%) Group results 2004 12,635 Total operating expenses Total operating income Gross margin % Net financial (expense) Income taxes Results from investments in affiliated companies Minority interests Net income Net income per diluted ordinary share/ADS (€ cents) 2003 % Total operating revenues 2002 6.5 11,866 11,782 (11,461) (3.3) (11,099) (10,724) 1,174 53.1 767 6.5 9.0 (77) 16.3 (92) (108) (428) (16.3) 9.3 1,058 (368) (341) (3) 50.0 (6) (5) 1 200.0 (1) (5) 667 122.3 300 599 140.7 123.0 63.1 126.1 At TPG, we deliver letters, packages, spare parts and cargo. We deliver on time, every time and just-in-time. But we deliver so much more. Contents Our business is all about delivering. A letter to a 2004 in brief TPG at a glance friend across town. Business parcels to the other Letter to shareholders Group Mail Express Logistics Corporate sustainability Management Information for shareholders TPG in figures from 2000 Glossary side of the world. Component parts to an as2 8 16 28 38 50 58 59 62 sembly line. Container shipments across the sea. Whatever the cargo, we ensure that goods and documents reach their destinations reliably and efficiently. Delivering is our core competence. But it’s also our business strategy. In everything we do, we aim not only to deliver, but to deliver more. More service for our customers. More opportunities for our employees. More value for our shareholders. And more benefits for our world. This is the story of how we delivered in 2004. 1 Letter to shareholders 2 TPG Annual Overview 2004 Delivering more through great people Our business is all about delivering. A letter to a friend across town. Business parcels to the other side of the world. Component parts to an assembly line. Container shipments across the sea. Whatever the cargo, we ensure that goods and documents reach their destinations reliably and efficiently. Delivering is our core competence. But we take it a step further. • Margin improvements across the board • Divisions united under one brand and TNT1 • Strong € 1 billion operating cash flow performance In everything we do, we aim not only to deliver, but to deliver more. More service for our customers. More opportunities for our employees. More value for our shareholders. And more benefits for our world. And we can deliver more because we have great people. It is through their work and dedication that our company exists. Our group strategy for leadership In the beginning of 2004 we introduced a strategy for our group, setting out a clear direction and ambitions. Our mission statement identified our key stakeholders and became the basis for a push to further enhance what we believe is our leading position. One element of our strategy is a move to one brand – TNT – for all our businesses. This move is a clear signal of our commitment to being one company with a comprehensive strategy and shared objectives. Together, the TNT strategy and all its elements add up to what I have come to call the TNT house. This house represents all that TNT stands for and all that we aspire to achieve. Our house is underpinned by a solid foundation – our three divisions, Mail, Express and Logistics. The next layer of building blocks is formed by the five areas of our TNT1 programme human resources, shared services, key account management, information and communication services and procurement. Next come our three growth initiatives: postal consolidation, China and freight management. In between the building blocks is the mortar that binds our house and makes it strong: our mission, standards, corporate governance, social responsibility endeavours and our brand. Covering the house are our four critical success factors: satisfied customers, engaged employees, shareholder value and work for the world. TNT mission Our mission is to exceed customers’ expectations in the transfer of their goods and documents around the world. We deliver value to our customers by providing the most reliable and efficient solutions in distribution and logistics. We lead the industry by: • Instilling pride in our people • Creating value for our shareholders • Sharing responsibility for our world. TNT standards • Aim to satisfy customers every time. • Challenge and improve all we do. • Be passionate about our people. • Act as a team. • Be honest, always. • Measure success through sustainable profit. • Work for the world. Built on a firm foundation So what is the state of the TNT house? I’ll start with the foundation. Overall, our three divisions produced strong results in 2004. They weathered the mixed economy and delivered margin improvements across the board, resulting in an operational cash flow of €1 billion. This healthy development enabled us to buy back around 4% of our stock when the State of the Netherlands decided to reduce its holding in our company to around 19%. The cost flexibility programme we launched in our mail division in 2001 helped employees there to do exceptional job countering 1.5% decline in addressed mail volumes in the Netherlands in 2004. In fact, the volume decline was actually higher than 1.5%; in 2004, a few additional working days due to holidays falling on weekends, for instance, masked a higher rate of decline. Nonetheless, our mail operating margin reached an outstanding 22.2%. TPG Annual Overview 2004 3 Letter to shareholders The entire Board of Management visited China in September 2004 for the opening of the new TNT China head office in Shanghai. Left to right: CFO Jan Haars, Group Managing Director Logistics Dave Kulik, CEO Peter Bakker, Group Managing Director Mail Harry Koorstra, Group Managing Director Express Marie-Christine Lombard. After years of discussions, the Dutch parliament approved the Postal Vision in 2004, setting forth a clear path towards liberalisation of the Dutch mail market. The plan calls for the Dutch mail market to continue to welcome competition, with full liberalisation from 2007, assuming that the mail markets in the United Kingdom and Germany are also liberalised by that date. results, with all business units across all geographies contributing. In the coming year, I hope to see further improvement of the operating margin as we move towards our target of a 10% operating margin by 2007. Express margin development 2004 2003 2002 Looking to 2005, although there is no guarantee, I expect organic growth in European Mail Networks to increase further, compensating for the continuing volume decline in the Netherlands. This development should lead to our overall mail revenues remaining stable, though we do not expect our mail margin to remain at the high level of 2004. Mail margin and volume development 22.2 20.9 20.1 20.0 19.2 2004 2003 2002 2001 2000 margin (in %) 5,302 5,384 5,521 5,562 5,608 volume mail (in € millions) Express continued its impressive record of positive quarterly yields, reaching an operating margin of 7.9%. Operationally, the division has delivered great 4 TPG Annual Overview 2004 2001 2000 7.9 6.5 5.9 4.0 3.8 (in € millions) We are pushing forward with our strategic aim to build the number-one express company in Europe. Further investments in the TNT Express European air hub in Liège, Belgium, as well as in our European road network will expand our capabilities. We will continue to strengthen our domestic positions in a number of countries through acquisitions. By restoring its margin to 3.7% – excluding the contribution of the Wilson Logistics Group, which we acquired in August 2004 – Logistics also contributed to our good results in 2004. The successful implementation of the Transformation through Standardisation programme helped our logistics employees overcome the difficulties of 2003. We’ve made good progress in turning around logistics operational performance, bringing three of the four loss-making business units back into the black. The one unit where the turnaround has not yet taken hold is France. Logistics margin development 2004 2003 2002 2001 2000 3.7 0.6 4.3 5.7 5.0 (in € millions) In 2005 I foresee continued operating improvements and we need to find a solution for France, as well as an ongoing push for standardisation across the entire logistics division. We must get better still at turning our now-significant scale into a positive trend. We are hopeful that revenue growth will be high, mainly driven by the Wilson acquisition. TNT1 Three of the five TNT1 projects entered implementation phases in 2004, and these will create the first concrete results this year. We are targeting extra revenues through key account management. The procurement team is set to book its first wave of savings through streamlined purchasing initiatives, and we have begun standardising our human resources management across our global business. But, to me, TNT1 is more than a programme intended to achieve extra revenues and cost savings through closer cross-divisional cooperation. It is evidence of the fact that our company is one, with a shared vision and mission, and shared standards. We are one company, 162,000 people strong, striving for leadership in our industry. – a great mail, express and logistics company, delivering more through great people. Our three growth initiatives The top floor of our TNT house is dedicated to growth. Growth brings energy and excitement and new opportunities for our talented and ambitious employees and our shareholders alike. We believe we made great progress in all three strategic growth areas in 2004 – postal consolidation, China and freight management. 2004 saw the overture of postal consolidation in Europe when the Danish government offered for sale up to 25% of Danish Post. We have entered a nonbinding bid and are currently awaiting the next steps in the process. We intend to grow our mail activities organically in all European countries. Alliances are also possible ways to accelerate this growth, but the risk and controls in any deal must be secured in an attractive way. China is at the top of my agenda. I made six working visits there in 2004, meeting with customers and government officials. In September, the entire Board of Management spent a week in Shanghai, where we opened our new China head office. The country is an economic powerhouse with enormous potential, but to realise its potential and remain competitive, it needs logistical skills to feed and sustain its incredible growth. We feel honoured to help meet these needs, both through our activities and through the TNT China University, which opened in November 2004. In the coming years we hope to help train thousands of students to begin meeting that country’s exploding need for skilled logistics professionals. China and Taiwan net sales 335 195 205 2004 2003 2002 And how better to express our aim to be one company than by moving all parts of the group to one brand. We compete on a global level, and operating under one brand will let us make the most efficient use of our marketing budget, as well as to show one face to our customers, who increasingly look to us for multicountry, full-service contracts. The re-branding will have the biggest impact in the Netherlands, where our company has been part of everyday life for more than two centuries. Exchanging TPG Post red for TNT orange will take some getting used to by both our customers and our employees. The changeover will be gradual, from 2006, to limit costs and to allow time for all our stakeholders to become comfortable with the change. And one thing I can promise: The re-branding will not change the heart of our company. We will continue to be what we are (in € millions) China is also the arena in which the TNT1 approach comes into its own. TNT China is taking the lead for the whole company, addressing the market with a unified TNT product offering in mail, express and logistics – and reaping the fruits of this approach. In 2004 we took an important first step in freight management with our acquisition of Sweden-based Wilson Logistics Group. I extend a hearty welcome to the 2,300 employees of Wilson, our new colleagues. I trust you will feel at home in our TNT family. TPG Annual Overview 2004 5 Letter to shareholders The city of Shanghai is home to the new TNT China head office. Our customers, particularly those in Asia, are increasingly demanding integrated logistics solutions, which include freight management. Wilson gives us global capabilities in this area, and we will continue looking to strengthen our freight management presence in the United States and in China. Making our house a powerhouse for society The TNT strategy goes beyond our goal to achieve industry leadership. We also aim to achieve social leadership. And just like the TNT house, this goal is built on the solid foundation of our three divisions and the strength of our global TNT brand. Next to those elements come two pillars: transparency & integrity and corporate sustainability. INDUSTRY LEADERSHIP TOWARDS SOCIAL LEADERSHIP MAIL EXPRESS LOGISTICS TNT INTEGRITY PRIDE CORPORATE SUSTAINABILITY GOVERNANCE CORPORATE PHILANTROPHY FINANCIAL CLARITY REPUTATION 6 TPG Annual Overview 2004 When assembled together, all these elements fuel our good reputation and that, in turn, fuels our company pride. While it may seem like a rather intangible factor, I happen to believe that pride is perhaps the highest ideal a company can strive for. When we achieve the capacity to instil pride in our employees and inspire our customers and shareholders, then, I believe, we will contribute to a better world and gain social leadership. Making our house sustainable In the area of corporate sustainability 2004 marked a year of progress for us. We are publishing our first corporate sustainability report over 2004. You can find it on our website at tpg.com, and we will continue to report on our progress in certification. Our aim is to be as open and transparent as possible about our sustainability efforts. Part of our sustainability effort is our partnership with the United Nations World Food Programme (WFP). We use our core competencies and business skills to support WFP in five areas: joint logistics supply chain, private sector fundraising, emergency response, transparency and accountability, and school feeding support. In addition to these projects, more than 40,000 people participated in our first global Walk the World fundraising event in 2004. And at the end of the year, we were able to help WFP in its work to help those affected by the disastrous tsunami in Asia. Our work with the World Food Programme has benefited us as well, not least because it has made our employees more proud of our company. For us in the service industry, customer satisfaction depends on the dedication and quality of our people and their willingness to go the extra mile. Employee engagement is therefore a key performance indicator for us, and our surveys show that our partnership with WFP plays a vital role in strengthening this important measure. Does the partnership with the World Food Programme influence your pride in TNT? Yes, very much Yes, a little Neutral No, not really No, not at all 24 39 22 15 0 (in %) Making our house transparent In addition to the operational challenges in our divisions that I have already mentioned, our group as a whole faces challenges: 2005 will be the year we strive to become fully compliant with the Sarbanes-Oxley Act. This is a big undertaking that will affect our entire company, and we aim to get this right. In response to our review of tax issues in the group, we will continue to formalise, strengthen and adapt, our internal lines of communication and the functioning and monitoring of the tax, legal and financial reporting functions around the group. Another important development will be the switch to the new International Financial Reporting Standards, which on 1 January 2005 became applicable to all listed companies in the European Union. We expect to inform all stakeholders about the changes in our financial statements as a result of the new IFRS in an official announcement on 27 April 2005. As always, we maintain our commitment to the transparency of our financial statements and risk factors, and we aim to continue improving their quality. TNT House will bring new energy in 2005 As we work together to grasp all of the opportunities and meet all these and other challenges that lay ahead, I am certain we will be inspired with new energy to keep building and improving our TNT house. I thank all my TPG and TNT colleagues for the magnificent job they did in 2004. With your help and support, I am confident that 2005 will also be successful. Peter Bakker CEO TPG Annual Overview 2004 7 Group As a global company, we aim to deliver leadership for our industry, society and the world. In 2004, we took steps towards those goals, and we established our TNT1 initiative to ensure that we continue delivering more. 8 TPG Annual Overview 2004 At TPG, we aim for leadership in all we do. We aim to lead our industry, to be a leader in society and to use our business skills and competencies to deliver tangible benefits for our world. That’s why, in 2004, we moved to more closely coordinate our skills and activities across our three divisions – Mail, Express and Logistics – in order to achieve significant cost savings and, more importantly, to offer our customers a comprehensive range of well-integrated services that meet their individual needs. The initiative is called TNT1 because its principal objective is to create a cohesive organisation with a single purpose – delivering more. By leveraging our efforts in procurement, information and communication systems, shared services such as accounting and finance, and strategic human resource management, TNT1 aims to achieve additional EBITA cost savings of between € 200 million and € 300 million over the coming five years. Moreover, by increasing standardisation within and among each of our divisions, and by taking a cross-divisional approach to serving large accounts, TNT1 will allow us to grow our business by delivering more and better services for all our customers. And it will help us seize the strategic growth opportunities we’ve identified in postal consolidation, China and freight management. We’re seizing strategic growth opportunities. In postal consolidation, we set forth in 2004 a deliberate strategy for leveraging our world-leading postal efficiency to become the frontrunner in the emerging pan-European postal market. As postal market liberalisation continues to unfold across Europe, we aim to capture opportunities through our proven abilities to innovate, to deliver efficiencies and cost improvements, and to leverage our growing scale and operational excellence. In China we established a head office in Shanghai. China is important to us not only because of its enormous market potential, but because we’re reaching the market through our new approach – operating as a single organisation, under a single brand, TNT – and integrating our services and activities across divisions. We already gained a substantial foothold. We are the leading logistics supplier to China’s automotive industry. Through our cooperation with China Post we provide inbound and outbound international express services, and we’re exploring further strategic cooperation to leverage our expertise in mail. At the end of 2004, some 2,800 employees were providing services in 500 cities across China. We made progress in all three areas in 2004. TPG Annual Overview 2004 9 Group Fushing Pang delivered first growth in the Chinese market. As senior vice president for strategic development for TNT China, Fushing Pang describes himself as a pioneer. An ethnic Chinese, Pang grew up in Taiwan, then earned an MBA in the United States and began his career there. But in the early days of China’s move to open its borders to international business, Pang couldn’t resist the urge to be part of the action. “I’ve got a pioneering spirit,” he said. “I was excited about the huge potential in China.” BEIJING, CHINA Since joining TNT five years ago, Pang has helped the company start seizing the potential of the world’s fastest-developing market. He recalls that when he arrived in China in 1986, roads were much less congested. “Today the roads in the major cities are filled with cars,” he said, offering the traffic analogy as an illustration of the vast changes taking place in China’s economy. With a strong background in business development, Pang has been instrumental in orchestrating significant business partnerships such as TNT’s joint venture with Shanghai Automotive Industry Corporation (SAIC) and its strategic cooperation with China Post. And with the strong commitment TPG pledged to China in 2004, 10 TPG Annual Overview 2004 Pang sees even bigger opportunities on the horizon. “The major push in 2004 has given us tremendous energy for moving ahead,” he said. “With this kind of commitment we have moved much more aggressively in building alliances and cooperation. We continue building our strong relationships with the Chinese government.” Good government relations is an essential part of success in China, and part of Pang’s role is to head the team that manages that aspect of TNT’s business there. He and his government relations team are located in Beijing so they can be close to government ministries. “By being here, it is easier to make contact with government organisations and we’re better informed about the development in this market,” he said. Pang firmly believes in taking a long-term strategy in China, and he sees 2004 as just the beginning of TNT’s growth there. “In 2004 we sowed the seeds in some major activities that will have significant impact for the company in 2005 and beyond,” he said. “In a market like this, the planting phase is very important. With good seeds, we’ll have plenty of healthy trees and beautiful flowers later.” We made our first big move into freight management in 2004 with the acquisition of Sweden-based freight forwarder Wilson Logistics Group. With a global customer base of 30,000 – and 60% of revenues coming from customers with an international presence – Wilson gives us a strong position in our targeted sectors of automotive, high-tech electronics and fast-moving consumer goods, as well as a strong technology platform in shipping, tracking and logistics management. The experienced management team and 2,300 employees around the world will help us grow our presence in freight management. We believe that true leadership extends past the borders of our own business. We believe that true leadership extends past the borders of our own business. True leadership, in our view, means delivering more for our industry, for society and for the world at large. We delivered for our industry, society and the world. We delivered for our industry in 2004 through our participation in the World Economic Forum’s logistics and transport sector corporate citizenship initiative. This initiative aims to establish key performance indicators for logistics and transportation issues by facilitating bi-lateral consultations with stakeholders including customers, suppliers, environmental groups and others. We aim to deliver more for society by making business decisions that have a positive impact on people around the globe. Our sponsorship of World Press Photo, the major independent platform for photojournalism, is one example. The organisation presents an annual travelling exhibit that highlights important world issues and events through powerful images created by photojournalists. Another example is our decision to purchase our December gift packages for employees in the Netherlands through the Fair Trade Organisation (FTO). Because FTO is dedicated to ensuring that the bulk of profits go to workers who produce the goods, our purchase helps improve the lives of those in developing countries. TPG Annual Overview 2004 11 Group 12 TPG Annual Overview 2004 Fushing Pang, Senoir Vice President Strategic Development, TNT China “In a market like this, the planting phase is very important. With good seeds, we’ll have plenty of healthy trees and beautiful flowers later.” TPG Annual Overview 2004 13 Group Perhaps our most visible commitment to delivering more for society, however, is our partnership with the United Nations World Food Programme (WFP). Since 2002, we have used our business skills and resources to help WFP solve the world’s most profound logistics challenge – getting food to where it’s most needed. Our partnership includes five initiatives: joint logistics supply chain, private sector fundraising, emergency response, transparency and accountability, and school feeding support. In addition to achieving milestones in all five initiatives in 2004, we elevated our commitment to WFP through Walk the World, our worldwide sponsored walk in support of the school feeding initiative. On 20 June, 40,000 TPG employees and their friends and family members participated in the event, collectively walking the circumference of the globe, raising € 700,000 – enough to feed 25,000 children for one school year. 14 TPG Annual Overview 2004 We aim to deliver more for society by making business decisions that have a positive impact on people around the globe. Group highlights Financial Revenues 12,635 11,866 11,782 2004 2003 2002 (in € millions) Earnings from operations 1,174 767 1,058 2004 2003 2002 Underlying1 2004 1,174 1,029 1,058 2003 2002 (in € millions) Net income 667 300 599 2004 2003 2002 Underlying1 2004 667 592 585 2003 2002 (in € millions) Operating margin 9.3 6.5 9.0 2004 2003 2002 Underlying1 2004 9.3 8.7 9.0 2003 2002 (in %) 1. Excluding TtS costs (earnings/income) and impairments (income) Corporate sustainability Coverage of management systems across TPG 2003 2004 65% 71% Investors in People 0% 0% OHSAS 18001 - Health and Safety 3% 2% SA 8000 - Social Accountability 1 65% 67% ISO 9001 - Quality management 28% 34% ISO 14001 - Environmental management 1. Compulsory in non-OECD countries TPG Annual Overview 2004 15 Mail • Mail Netherlands cost flexibility programme delivered € 45 million in savings • European Mail Networks continue to grow • Revenue challenges in Cross-Border and Data and Document Management In Mail, we aim to lead the world in postal efficiency and to be the frontrunner in the emerging panEuropean mail market. We aim to deliver stable revenues and to maintain our margin at around 20%. In Mail, we delivered 5.3 billion letters in 2004. We also delivered a 96.5% next-day quality rating in the Netherlands and 16.1% growth in European Mail Networks. 16 TPG Annual Overview 2004 Demand for mail services continued to be influenced by the weak economy in 2004. In the Netherlands, domestic addressed mail volumes increased slightly due to more consumer letterbox mail and addressed bulk mail. Direct mail volumes, however, were down, due mainly to increased competition from other networks and other media. Together, these developments put the total volume decline at the low end of the expected range. In our European Mail Networks, we achieved 16.1% revenue growth, but revenues declined in our Cross-Border unit. The overall picture, however, remained stable with our Mail division achieving revenues of € 3.9 billion and a margin of 22%. 31% 62% In 2004, our Mail division earned revenues of € 3.9 billion, slightly less than in 2003. Mail contributed 31% of TPG revenues and 62% of TPG earnings from operations. Our cost flexibility programme continues to deliver more savings. Begun in 2001, our cost flexibility programme in the Netherlands has been offsetting volume declines with increased efficiencies in automatic sorting, labour conditions and commercial activities. In 2004, we redesigned the TPG Post overhead organisation, and plan to merge our sorting, distribution and transport units. The redesign aims to realise a reduction of between 700 and 800 full-time equivalents among support staff and line managers before 2008. To minimise negative consequences for employees, we introduced incentives to encourage earlier departures for employees eligible for early retirement in 2006, 2007 or 2008, outplacement assistance and training resources for those who want to pursue careers outside the organisation, as well as exit premiums for those who voluntarily leave before 2006. By offering these incentives now, we aim to avoid more pressing social issues in the future. By the end of 2004, we had installed about half the planned 286 sequence sorting machines, and had hired more than 5,000 new-style mail deliverers – part-time employees who enjoy flexible work schedules. By the year 2012, we expect to employ 20,000 new-style mail deliverers. From its introduction in 2001 through the end of 2004, our cost flexibility programme has saved € 145 million. When fully implemented, it aims to save € 370 million annually (compared to 2001 cost levels), including € 265 million in our production activities and € 55 million in our marketing and sales activities and € 50 million in overhead reduction. In one of Europe’s most open markets, we deliver more service at a lower price. Our Mail business is subject to national regulation, as well as European and international regulation. In the Netherlands, the Postal Act assigns us the undertaking of certain activities. Through a concession granted by the Dutch government, we hold exclusive rights to perform some of these activities, which comprise approximately 40% of our Mail business in the Netherlands. TPG Annual Overview 2004 17 Erik Brink delivered a means for increased sorting efficiency. After joining TPG Post as a management trainee in 1993, Erik Brink found his place in the production area of the company, where six days a week mail is sorted and prepared for delivery to more than 7 million households across the Netherlands. GRONINGEN, NETHERLANDS After progressing through several managerial roles, in 1997 Brink helped implement the new sorting structure that comprises six strategically located sorting centres across the Netherlands. With that project complete, he went on to manage one of those sorting centres before being tapped to manage distribution in the Groningen region. “Being a region manager is one of the nicest jobs at TPG Post,” he said. “Not only do I get to interface with the business of collecting and delivering mail, but I also get to work with lots of men and women who actually do the delivery. It’s a lot of communication, a lot of motivation and at the same time keeping a close eye on the budget and the high quality of delivery service.” 18 TPG Annual Overview 2004 In 2003, Brink took on the additional role of leading the nationwide installation and preparation for implementating 286 new purpose-built sequence sorting machines, part of TPG Post’s so-called Master Plan to proactively combat volume declines and increasing competition. The first of the machines – which use new technology to automate the preparation of postal delivery rounds for some 40,000 mail carriers – were installed in late 2003. The new processes bring optimal efficiency to the collaboration between man and machine. Machines sort the mail, then human carriers ensure each piece is delivered to the home of its recipient. “I really get a kick out of achieving ongoing efficiency in the Mail business, and I get a lot of opportunity to do my thing,” said Brink. “I like the company and the people I work with, and I’m excited about the transformation we’re making to becoming an increasingly streamlined company not only in the Netherlands, but worldwide. That motivates me to keep striving for more.” More than 50% of addressed mail volumes in the Netherlands, as well as 100% of the market for unaddressed mail, is already open to competition. After Sweden and Finland, the Netherlands has the smallest monopoly in Europe. Our exclusive right to provide mandatory services is confined to delivering letters weighing up to 100 grams or costing less than three times the basic tariff of € 0.39. Direct mail is not covered by the mandatory services in the Netherlands as it is in other countries. The government regulates our mandatory activities More than 50% of addressed mail volumes in the Netherlands, as well as 100% of the market for unaddressed mail, is already open to competition. with respect to service provision, price controls, cost and revenue accounting, and financial administration and reporting. We continued to achieve high levels of service quality in 2004. Next-day delivery reached a summer record of more than 97% in August and averaged 96.5% for the entire year. In June 2004, we announced our intention to not increase the price of a consumer postage stamp from the present level of € 0.39 for the years 2004, 2005 and 2006. When corrected for inflation, the price of a postage stamp in the Netherlands has actually decreased by 30% over the past 12 years. We are, however, considering a minor amendment to prices for mandatory postal services for business customers covered by the price-control system in 2006. Any adjustment, however, will be kept below the rate of inflation for 2004 and 2005. Our consistently high service levels and low cost make us one of the most efficient mail delivery providers in the world. We support a more open market in the Netherlands. In 2004, the Dutch minister of economic affairs issued the policy for further liberalising the Dutch postal market. This so-called Postal Vision provides a longterm framework for development of the market in the Netherlands, including these key elements: • Full liberalisation of the Dutch postal market in 2007 (dependent on full liberalisation of the markets in the United Kingdom and Germany). • From 2007, universal service will be subject to a price-cap system based on inflation or the consumer price index. • Universal service obligation after liberalisation restricted to single items at fixed rates; obligation to deliver bulk mail letters up to 50 grams for a transitional period. The minister of economic affairs will assess whether this obligation will indeed be necessary. • Competitors and customers to be treated equally in terms of rates and conditions. TPG Annual Overview 2004 19 Erik Brink, Region Manager, Royal TPG Post “ Not only do I get to interface with the business of collecting and delivering mail, but I also get to work with lots of men and women who actually do the delivery.â€? 20 TPG Annual Overview 2004 TPG Annual Overview 2004 21 We support the policy and its consideration of the pace of liberalisation across Europe, specifically that of the two largest markets, Germany and the United Kingdom. We face more competition. In the past decade, a growing number of delivery organisations have entered the Dutch market, delivering not only unaddressed items, but also addressed mail. Our foreign competitors, too, are building positions in the Dutch market. Deutsche Post and Royal Mail already have their own delivery organisations in the Netherlands, and many other delivery organisations include numerous We aim to be the first pan-European mail company and the second operator in major European countries. potential competitors for addressed mail. Moreover, a large portion of our direct mail volumes is under competitive pressure from other media. We aim to deliver more across Europe. In addition to maintaining our position and profitability in the Netherlands, we aim to be the first panEuropean mail company and the second operator in major European countries. Despite the lingering pace of liberalisation, we remain strong believers in open markets and we continue towards our goal. 22 TPG Annual Overview 2004 We have domestic mail operations in eight European countries, and we strengthened that presence in 2004 when we acquired the remaining 50% stake of unaddressed mail company Höfinger Haushaltswerbung in Germany and the remaining 40% stake of direct mail company DIMAR in the Czech Republic and Slovakia. Through our access agreement with Royal Mail, we also increased our presence in Europe’s second-largest market, where the regulator has announced plans to open 40% of the market to competition. We now are able to offer business customers two-day mail service under the TNT Mail brand and to reach all 27 million households in the United Kingdom. In addition, in 2004 we began delivering heavier-weight addressed letters and parcels for TNT Mail customers in the country. Our Cendris data and document management business offers direct marketing services in the Netherlands, the United Kingdom, Germany, the Czech Republic and Slovakia. In 2004, this business experienced a decrease in the document management business, and continued to be affected by the subdued economy in the Netherlands. Our Cross-Border business, which comprises our Spring joint venture with Royal Mail and Singapore Post, also experienced revenue declines in 2004, partly due to contract rationalisation. Jan Kalverdijk delivered direct marketing expertise that beat the competition. As a senior account manager in TPG Post’s major accounts department, Jan Kalverdijk knows that in the face of increasing competition, keeping customers demands that TPG Post do more than just deliver direct mail pieces. It must deliver measurable results. And that’s exactly what Kalverdijk and his colleagues did when a national food retailing giant went to a competitor with its order for delivering its weekly sales brochures. THE HAGUE, NETHERLANDS As a strategic advisor to large national retailers, Kalverdijk focuses on helping them win customers of their own. “My job is to make sure that the pieces my customers put in the mail are as effective and efficient as possible,” he said. “When you have a name and address, you know who the consumer is, so you know his buying habits and you can make him an attractive offer. But a company can also execute an effective mailing by finding areas where people of like buying habits live and making them a proposition. We have the knowledge to target those areas and help retailers get customers into their stores.” Not only does TPG Post’s extensive databases of the Dutch population give it knowledge of the national consumer market, its skilled workforce gives it the ability to ensure that direct mail pieces actually reach the intended consumers. By showing that TPG Post consistently achieves between 95% and 98% accuracy – delivery to the right address on the right day – compared to competitor rates of between 60% and 70%, Kalverdijk and his colleagues not only won back the account, they got a multiple-year extension of the contract. “Our calculation model showed that every piece we accurately deliver represents a certain amount of money that consumer actually spends at the local grocery store,” said Kalverdijk. “Our ability to show the customer the return for their direct mail investment helped them see that TPG Post is not only a distribution company, but a company that knows how to use distribution to achieve marketing results.” TPG Annual Overview 2004 23 24 TPG Annual Overview 2004 Jan Kalverdijk, Senior Account Manager, Royal TPG Post “ TPG Post is not only a distribution company, but a company that knows how to use distribution to achieve marketing results.â€? TPG Annual Overview 2004 25 Mail highlights Financial Strategy Revenues 3,900 3,915 4,005 2004 2003 2002 (in € millions) Earnings from operations 865 820 804 2004 2003 2002 (in € millions) Margin 22.2 20.9 20.1 2004 2003 2002 (in %) Mail revenue split 3,900 3,915 4,005 2004 2003 2002 (in € millions) Mail Netherlands Cross border European Mail Networks Data and document management Our ambition is to become the leading provider of business and consumer services for communication, transactions and delivery. We want our Mail operations to be recognised as the industry benchmark for quality, efficiency and customer service, for producing the best returns in the industry and for making optimal use of new technologies and European postal market liberalisation. Our Mail strategy is based on three key elements: • In Mail Netherlands, our focus is on the retention of our current margins by implementing cost flexibility measures. In addition, we continue to offer new services that bring cost savings to our customers’ production chains. • Internationally, we continue to expand along three tracks: - Through our European Mail Networks we offer addressed, unaddressed and segmented distribution solutions for direct mail, brochures, leaflets and samples with an excellent price/quality ratio. - We continue to strengthen our European position through alliances with other organisations and postal operators. - Our 51%-owned subsidiary Spring – our joint venture with Royal Mail Group plc and Singapore Post Pte Ltd. – offers cross-border mail services on a global scale. • In addition to physical mail delivery, we continue to offer mail-related data and document management services, such as direct and interactive marketing services and services for managing physical and electronic information flows. Sustainability Market position Coverage of managementsystems across Mail Our Mail division provides services for collecting, sorting, transporting and distributing domestic and international mail including letters, printed matter and parcels, as well as for distributing addressed direct mail and unaddressed mail. We also provide a range of data and document management services, including direct marketing and interactive services, and services for managing physical and electronic information flows. 2003 2004 77% 79% Investor in People 0% 0% OHSAS 18001 - Health and Safety SA 8000 - Social Accountability 1 0% 0% 80% 83% ISO 9001 - Quality management 69% 80% ISO 14001 - Environmental management 1. Compulsory in non-OECD countries Our substantial and long experience in the mail industry has helped us become one of the world’s leading postal operators. It also helps us anticipate and respond to the changing market. In addition to providing world-class mail service, we continue to combine our expertise with technology to develop new mail-related data and document management services that meet specific consumer and business needs. We have long viewed our core competence not as merely moving physical mail from one location to another, but as intelligently managing both physical and electronic flows of information. This skill is central to our objective, which is to maintain our margins through the implementation of cost flexibility measures and to maintain market share in the Netherlands, and to achieve growth through international expansion and the provision of mail-related data and document management services. TPG Post market share in the Netherlands 6% 94% Source: Annual reports, team analysis 26 TPG Annual Overview 2004 European Mail Networks Through our European Mail Networks we are building a position to offer our customers a full-service concept for mail, based on high quality and wide coverage in addressed and unaddressed delivery, as well as a broad portfolio of services to reinforce our distribution activities. We currently have a presence in Austria, Belgium, the Czech Republic, Germany, Italy, the Netherlands, Slovakia and the United Kingdom. Our services combine our expertise in data collection and direct marketing to offer customers an intelligent unaddressed service that approaches addressed mail in its ability to target consumers. Mail Netherlands 2004 Addressed Mail Netherlands items (millions) 2003 %-change 2002 5,302 (1.5) 5,384 5,521 per Netherlands delivery address (items) 707 (2.3) 724 747 per Mail Netherlands FTE (thousands of items) 161 3.2 156 151 per Netherlands inhabitant (items) 325 (1.8) 331 341 17 (5.6) 18 18 Total operating revenues per FTE (thousands of ₏) 95 6.7 89 92 Average percentage of national mail sorted automatically (%) 82 - 82 80 1 2 per delivery day (millions) 2 1. Excluding international mail items per delivery day (millions). 2. This FTE (full-time employee equivalent) deďŹ nition is based on a 37-hour work week. Cross-Border Mail productivity statistics 2004 Total Cross-Border Mail volumes (thousands of kilograms) 90.2 2003 %-change (4.5) 94.5 TPG Annual Overview 2004 2002 90.7 27 Express • Strong volume growth • 21 consecutive quarters of positive revenue quality yield • Expansion in air and road networks In Express, we aim to be the leader in day/timecertain, door-to-door transport, focussing on business-to-business customers, with the widest geographical coverage. We aim to deliver long-term revenue growth of between 5-10%, and to achieve a 10% margin in 2007. In Express, we delivered more than 176 million consignments for one million customers in 2004. We also delivered strong earnings and margins increases and a revised strategy aimed at leadership in Europe, emerging markets and special services. 28 TPG Annual Overview 2004 Despite the mixed global economy, our Express division delivered good results in 2004. Volume growth, particularly in our international business, along with ongoing optimisation of our network and continued revenue quality yield made for a strong performance. By instituting a fuel surcharge, we were able to mitigate the impact of increased fuel prices. Overall revenues were € 4.7 billion with a margin of 7.9%. 37% 27% In 2004, our Express division earned revenues of € 4.7 billion, a 10.5% increase from 2003. Express contributed 37% of TPG revenues and 27% of TPG earnings from operations. Volume growth was strong in our home market of Europe, where more than 80% of our revenues originate. We saw strong growth in the United Kingdom, Eastern Europe, Spain and the Netherlands. We also achieved growth outside Europe, particularly in China and the Middle East. Revenue growth was aided by our continued focus on improving revenue quality yield – our composite measure of growth in revenue per consignment and per kilo – by offering the right products, disciplined pricing management and an efficient sales process. We’re enhancing our networks so we can deliver more. With dense coverage in 33 countries, our extensive integrated road and air networks are key to delivering for our customers. We expanded our European network in 2004 by adding 16 new road linehaul connections between eight new European Union member states. We also added a road service to Bosnia in 2004, making it the thirty-third country in our road network, and we added a new road transit hub in Spain. In March, we introduced a direct flight between our TNT Express European air hub in Liège, Belgium and Turku Airport in Finland. The new daily route improved delivery times for imports to customers by more than two hours and extended collection time for exports by the same period. In September, we replaced a smaller aircraft with a Boeing 737 16-tonne capacity aircraft on our six-day-a-week Liège-Istanbul-Liège route, and in December we replaced a chartered B737 with a second TNT B737. The aircraft are among five new leased B737s that will replace chartered aircraft across our European network. We expect to add an additional aircraft each year in 2005, 2006 and 2007. In May, we introduced global express and airfreight services into Somalia. This twice-weekly service operates between our hub in Dubai in the United Arab Emirates and the Somali capital Mogadishu, with an air connection to Hargeisa in the north of the country. To facilitate delivery to remote areas, we signed an agreement with Somal Post that allows us to access the organisation’s network using its fleet of 19 road vehicles. Also in May, we announced a € 36 million investment to expand and upgrade facilities at our European air hub. The initial investment – to be completed in the first half of 2006 – is part of a six-year plan that will create 245 new jobs at the facility by 2010. The first phase includes doubling sortation space from 28,000 square metres to 56,000 square metres, re-engineering to improve TPG Annual Overview 2004 29 Express Roger Corcoran delivered a turnaround of the Express business in Australia. SYDNEY, AUSTRALIA In his 26 years with the company, Roger Corcoran has helped establish TNT’s business in new markets, including several countries in Asia. But his most recent challenge was not establishing a new business, but turning around the business in what was TNT’s original home market – Australia. A variety of factors, including poor integration among several business units and problems in administration activities such as invoicing and collections, the business in Australia was experiencing significant losses when Corcoran was tapped to step in. When he arrived in September 2001, Corcoran and a team of new senior managers immediately put in place measures to rectify situation. “The first thing we did was to strangle costs,” he said. Then they embarked on a revenue quality generation programme that included streamlining decision-making and reviewing all contracts and eliminating unprofitable agreements. At the same time, Corcoran and his team launched the division’s seven key processes across the business and began re-building strong alliances 30 TPG Annual Overview 2004 among our depot managers. Those activities allowed employees to improve the levels of performance and service offered to customers. “We set very clear, but aggressive targets, which allowed us to improve our service drastically and that ultimately allowed us to improve our revenue stream by increasing prices.” The programme worked. In just over two years, the team has increased revenue quality by some 50%. “Our target was to break even by the end of 2003, which we achieved,” said Corcoran. “Then we had to start making money, and 2004 was the year of making real money. We’ve turned this business around not only for our shareholders, but for the 5,000 employees in Australia.” The improved financial results are not the only proof that the turnaround worked. “I recently got an email from the largest car manufacturer in Australia, congratulating us on the outstanding logistics service we provide them. It was a powerful statement.” speed and efficiency of sortation systems, expanding office space, and improving staff facilities. Phases two and three will add new sortation equipment, increase air container throughput, modernise equipment, and further improve information and other systems. We laid the foundation that we believe will help us continue delivering more for customers and to grow our business well into the future. associate network that allows us to serve some 500 cities. We aim to have 35 of our own locations by the end of 2005. Our network development, however, is dependent on infrastructure development within the country. The government has made realising a sound infrastructure a key focus of its most recent economic development programme and is investing heavily in port and city development and highway reconstruction, but realising a modern infrastructure in China is a long-term initiative. We’ve revised our strategy to deliver more to targeted markets. In 2004 we laid the foundation that we believe will help us to not only continue delivering more for our customers, but to grow our Express business well into the future. Our revised strategy builds on our strong position in Europe. It is aimed at achieving leadership in both domestic and intra-European express flows in Europe, leveraging our presence in China to fuel our European network and establish an intra-China network, and seizing the number-one positions in emerging markets in the rest of the world, and in special services. As there is no commonly shared market definition for the global courier, express and parcel (CEP) market, our strategy begins by defining what we see as our market. The CEP market can be segmented along the axes of transport speed – same-day and in-night, timecertain, next-day, day-certain, and day-uncertain – and weight per consignment. TNT Express market definition TNT Express entered China in 1988, working with a state-owned joint venture partner. In June 2003, we began operating under our own auspices in 12 locations. In a country of some 10 million square kilometres, we estimate that a pan-China network must cover 100 cities with 140 to 170 locations in order to serve about 1,000 cities and reach 95% of the addressable population. Today, we have 25 companyowned locations supported by an extensive agency and Same day & in-night Time certain TRANSPORT SPEED We aim to establish our second home market in China. If the China express market continues its current trend of 25% per annum growth, by 2010 it will be the world’s sixth-largest express market and a key cog in global supply chains. We’re currently outstripping the industry in China, turning in 40% growth in 2004. To sustain that growth, we’re making significant investments in our network. Next day Day certain Day uncertain Document Parcels > 1 kg Freight 31.5 kg LTL, FTL 1000 kg WEIGHT PER CONSIGNMENT We define our market to include time-definite and next-day delivery of shipments and consignments transported through a scheduled network. It includes both scheduled and on-call pick-up with drop-off possibilities. It allows for door-to-door tracking-andtracing of individual items, and often includes a money- TPG Annual Overview 2004 31 Express Viviane Reichert, Director, Customer & Market Intelligence, TNT Express “ Thriving in this business is all about our ability to provide better customer service than our competitors.â€? 32 TPG Annual Overview 2004 TPG Annual Overview 2004 33 Express Viviane Reichert delivered a clear understanding of customer satisfaction. HOOFDDORP, NETHERLANDS Viviane Reichert knows what customers want. As director of Customer & Market Intelligence for TNT Express, Reichert leads the ongoing process of measuring customer satisfaction and incorporating those findings into business strategy. And thanks to a comprehensive approach that cascades customer feedback across the organisation, Reichert makes sure that all TNT Express managers also know what customers want. The ultimate aim of the process, she said, is to give TNT Express a competitive edge in the marketplace. On-time delivery, of course, consistently claims the number-one spot among customer demands. Timely, proactive notification of issues that may cause delays comes in second. For instance, said Reichert, when customers ship a package to another country, they want to be informed upfront of any special customs requirements or upcoming national holidays that may delay delivery of their package. Rounding out the top three customer demands is an ability to solve such problems when they arise and to follow through on those commitments. Reichert and her team use a three-step, ongoing process. “Our first objective is to measure customer 34 TPG Annual Overview 2004 satisfaction with our services – to understand what they regard as important and how well we live up to that,” she said. That’s done with a survey sent to a selection of 90,000 customers around the globe three times a year. For each returned survey, TNT Express makes a donation to the World Food Programme, and response rates consistently average around 17%, a significantly high rate for such mailings. Results are compiled using a web-based analysis system that can be accessed by managers around the world, who can monitor customer satisfaction within their own regions or business areas. The second step of the process is benchmarking results against competitors. “This gives us the ability to fill any gaps and to capitalise on our strengths,” said Reichert. The third step is inviting customers to take part in focus groups to provide specifics about what they need and want from TNT Express. In 2004, the process revealed steadily increasing levels of customer satisfaction. But linking the results back to the business is the most crucial step. When that happens, according to Reichert, TNT Express can gain a competitive advantage. “Thriving in this business is all about our ability to provide better customer service than our competitors,” she said. “If we get that right, we can stand out from the crowd.” TNT Express market share in Europe 24% 33% 1 6 5 2 4 5% 3 22% We aim to achieve the number-one position in emerging markets in the rest of the world. In South America, for instance, we’re pursuing selected opportunities in countries such as Brazil. In India, we’re investigating development of the domestic express business, and in Southeast Asia, we’re also working to leverage our relationships with large multinational customers to increase flows into Europe. 7% 9% 1. DHL 2. TNT 3. UPS 4. GeoPost 5. FedEx 6. Other players back guarantee. Weight can be up to 1,000 kilograms per consignment, and it includes both domestic and international shipments. Our Express market includes only business-to-business shipments, not those going from business to consumer or consumer to consumer. Within this market definition, TNT Express has a 22% share of the European market. We also aim to achieve the number-one position in special services such as transporting pharmaceuticals. We’re investigating partnerships with niche players in the United States to serve our vertical market customers, and we’re developing non-network services to provide solutions to customers. For example, we support the logistics of large-scale clinical trial programmes by delivering test kits and medications to research sites, and returning clinical samples to labs located all over the world. We aim to leverage our relationships with multinational customers in China to fuel consignment flows carried by both air and sea from China to Europe and the rest of the world, and to establish an intra-China network. TPG Annual Overview 2004 35 Express Express highlights Financial Strategy Revenues 4,696 4,251 4,175 2004 2003 2002 (in € millions) Earnings from operations 373 276 246 2004 2003 2002 (in € millions) Our ambition is to be the leader in day/time certain, door-to-door transport for our business-to-business customers, with the widest geographical coverage. Our global strategy is to: • Be number one in Europe in domestic and intra-European express flows. • Build volume capacity from China to fuel our European network and establish an intra-China network. • Be number one in emerging markets in the rest of the world. • Be number one in special services. Margin 7.9 6.5 5.9 2004 2003 2002 (in %) Sustainability Coverage of management systems across Express 2003 2004 77% 79% Investor in People 1% 1% OHSAS 18001 - Health and Safety 8% 7% SA 8000 - Social Accountability 1 The most important elements of our strategy are to: • Achieve profitable revenue growth through volume acquisitions at optimised pricing. • Maintain a balanced customer portfolio that includes global accounts, major national, large, medium, small and ad hoc customers. • Focus on product performance. • Improve cost effectiveness. • Ensure quality in all key areas. • Provide high-quality and cost-effective intra-European services through connecting strong domestic businesses. • Secure outstanding levels of customer satisfaction. • Equip employees to fully satisfy customer needs. • Develop leading-edge support technologies that provide added value for customers. • Strengthen the TNT brand and increase top-of-mind awareness of the comprehensive range of reliable on-demand express delivery services we provide. Market position 67% 69% ISO 9001 - Quality management 5% 14% ISO 14001 - Environmental management 1. Compulsory in non-OECD countries Our Express division provides on-demand door-to-door express delivery services for customers sending documents, parcels and freight. We offer regional, national and worldwide express delivery services, primarily for business-to-business customers. The Express services we provide and the prices we charge to customers are, in general, classified by transit times, distances covered and sizes and weights of consignments. In Europe we provide regional, national and pan-European Express services as well as time-sensitive door-to-door services that deliver consignments between Europe and the rest of the world. Our extensive integrated road and air networks give us a strong position in the European market and, with dense coverage in 33 European countries, are an important strategic asset. We also provide door-to-door express delivery of documents, parcels and freight in all areas outside Europe and from these areas to Europe. Our worldwide coverage extends to more than 200 countries. In many of these countries our global Express services are augmented by domestic and regional express delivery services. We also are building our position in Asia and have further improved service levels between Europe and Asia. Our business in Asia is expanding through a mix of organic growth, acquisitions and cooperative ventures such as our alliance ough a mix of organic growth, acquisitions and cooperative ventures such as our alliance with China Post. 36 TPG Annual Overview 2004 On-time performance European road network extensions Q1 New linehauls in 2004 90.5 90.1 90.3 2004 2003 2002 Q2 92.1 90.1 90.9 2004 2003 2002 Q3 92.4 91.3 90.8 2004 2003 2002 Q4 90.9 90.3 89.3 2004 2003 2002 Full year 91.5 90.5 90.3 2004 2003 2002 (in %) Air and road network development Airports 58 57 54 2004 2003 2002 Number of aircraft 42 43 43 2004 2003 2002 Road connections 33 32 31 2004 2003 2002 Quarterly revenue quality yield development of core volumes in Europe 25 20 15 10 5 0 13.9 14.4 6.7 13.3 7.3 4.2 3.3 2.1 0.8 2.8 6.8 4.9 6.5 2.9 (0.1) 2.5 1.0 0.8 4.7 3.7 9.6 15.8 20.6 14.0 9.0 6.3 5.1 3.6 5.0 1.8 (0.4) 3.3 1.4 2.9 0.7 0.9 5.1 3.0 5.2 7.4 4.1 9.4 1.6 1.8 3.6 1.0 2.9 7.5 5.7 2.8 2.2 2.0 2.4 2.8 4.3 3.3 4.5 2.8 3.2 3.2 3.6 4.5 4.2 (in %) Consignment growth Kilo growth Revenue quality yield TPG Annual Overview 2004 37 Logistics • Good revenue growth, mainly due to freight management acquisition • TtS programme paying off; annualised savings of more than € 50 million achieved • French business faces challenges In Logistics, we aim to lead the industry by using world-class technology to provide solutions for complex logistics needs. Long-term, we aim to deliver revenue growth up to 10% and a margin of 4-6%. In Logistics, we delivered everything from spare auto parts to computers to gourmet coffee in 2004. We also delivered margin improvements and a turnaround of our business. 38 TPG Annual Overview 2004 Ongoing implementation of our Transformation through Standardisation (TtS) programme and a commitment to future growth delivered results for our Logistics division in 2004. We achieved good revenue growth, due mainly to our acquisition of global freight management company Wilson Logistics Group, and we increased our operating margin. We achieved revenue of € 4.1 billion in 2004 and a margin of 3.7%. 32% 11% In 2004, our Logistics division earned revenues of € 4.1 billion, a 9.3% increase from 2003. Logistics contributed 32% of TPG revenues and 11% of TPG earnings from operations. The results achieved through our TtS programme show that TNT Logistics was back on track. As we continue to embed TtS initiatives across our business, we have achieved savings in line with our expectations, and we continue to see high levels of contract renewals and healthy increases in new contracts. In 2004, we marked four successive quarters of earnings growth and of exceeding internal budgets. Our businesses in Germany, Italy and Spain have recovered. As we continue moving towards increased standardisation, our central procurement team is delivering solid cost savings, and we have implemented the JD Edwards back-office system across our business units. Moreover, we have implemented our proprietary Matrix™ software in operations around the world, including Australia, Brazil, Italy, Thailand and the United Kingdom. Our French business unit continued to under-perform in 2004. We have identified the key issues for this deficit and we are taking decisive actions, including making changes in senior management, closing warehouses and rationalising our contract portfolio, to correct the problems. In addition, we’re working to optimise our transportation networks in France and implementing lean warehousing techniques across our operations there. We’ve also increased our business development efforts, particularly in automotive, high-tech and fastmoving consumer goods. Our move into freight management lets us deliver more for our customers. We made our first big move into freight management in 2004 with our purchase of Sweden-based freight forwarder Wilson Logistics Group. This move means that we can now offer our customers the full array of supply-chain management services, including air freight, ocean freight and combined sea/air freight. We had previously met this demand through strategic alliances, such as our partnership with Kintetsu of Japan. Bringing freight management in-house, however, means that we can deliver an integrated, high-quality service. With a global base of 30,000 customers – many in our target sectors – strong technology assets, an experienced management team and 2,300 dedicated employees, Wilson supports our ambition to expand our business in the high-growth freight management market. As manufacturers continue to seek out efficiencies and move their operations to regions with lower costs of production, Asia is an increasingly important arena. China alone is expected to be the world’s third-largest exporter by 2008 and home to up to 30% of the world’s manufacturing by 2013. That translates into huge demand for freight management, and Wilson’s strong presence in Asia should help to accelerate growth across the region. TPG Annual Overview 2004 39 Logistics Onno Meij delivered the transformation of TNT Logistics in the Benelux. CULEMBORG, NETHERLANDS When Onno Meij was named managing director of the Benelux business unit of TNT Logistics in September 2002, the unit was not performing well at all. Service levels were insufficient and as a result, financial performance was down. “No one could be happy with the results at that time,” recalled Meij. Charged with turning around the under-performing unit as part of the division’s Transformation through Standardisation (TtS) programme, Meij and his team of managers set out to create what the unit was sorely missing: a sound structure for improvement, including clear objectives and systems for measuring progress towards those objectives. “We needed to have a clear map of where we wanted to go and how we were going to get there, a plan people could buy into,” said Meij. “We developed a road map to achieve excellence in all parts of our business by the year 2006. And the most important part of the process was to make our objectives clear to everyone so they could get behind those objectives and understand their role in the turnaround.” The plan Meij and his team developed centred on what at first might seem like an unlikely measure of business success – happiness. The team reasoned that their ability to turn around the business could be measured by the happiness of four stakeholders – customers, employees, society and shareholders. “We know what makes our customers 40 TPG Annual Overview 2004 happy – excellent service, continuous cost reduction, and good relationships,” said Meij. And we know what makes shareholders happy – a good return on their investment. We put in place ways to measure our progress in those areas.” The team then set out to deliver the message to every one of the 1,800 employees across the business unit. In addition to communicating via regular team meetings and printed materials, Meij himself makes it a point to visit each site at least four times a year to meet with managers and employees, inform them about ongoing progress and get their feedback. The quest for happiness is paying off. Over the last two years, the business unit improved performance for all four stakeholder groups. Among the progress Meij reported was achievement of the Investors In People standard, ISO 9001 certification for quality management and ISO 14001 certification for sound environmental management. And the unit’s second annual employee satisfaction survey showed progress as well: Satisfaction levels increased by 6%. Meij sees employee satisfaction as crucial for all other performance indicators. “When we are happy, we’re more motivated. More willing to go the extra step to better serve our customers. More eager to develop ourselves,” he said. “Happy employees are one of the most important resources we have. From happy employees come happy customers and happy shareholders.” We’re delivering more through our increased global footprint and our network innovator strategy. In 1999, we set out to establish a global footprint that would allow us to offer services in all key logistics markets and to more effectively serve global customers. Today we have operations on all continents and have achieved the critical mass necessary to offer consistent services to multi-national customers. Today we have operations on all continents and have achieved the critical mass necessary to offer consistent services to multi-national customers. We’ve also set forth our network innovator strategy, which is our plan for becoming an industry innovator in selected sectors. The strategy aims to help us deliver superior value for customers by managing and designing changes in the supply chain. It focuses on six strategic offerings, six target sectors and investments in key account management, lean warehousing and standardisation. Key account management is crucial to good service delivery because it gives us a better understanding of customer requirements, allowing us to be proactive in meeting their needs. Lean warehousing means precisely what the name implies – managing warehouses in the most lean and efficient manner possible, eliminating all non-value-adding activities. We began implementing the approach across our European operations in 2004. The first wave of implementation in 10 warehouses shows that significant efficiency gains are achievable. Our proprietary software helps us deliver more benefits for customers. Matrix™ is a centrally hosted, integrated suite of supply chain technologies that enables us to manage complex domestic and global supply chains. It provides a link between TNT Logistics and our trading partners. Matrix™ supports inbound just-in-time logistics, outbound logistics and reverse logistics across multiple industry verticals, and integrates transportation, inventory management, order fulfilment, financial settlement and e-commerce applications that enable global collaboration. TPG Annual Overview 2004 41 Logistics 42 TPG Annual Overview 2004 Onno Meij, Managing Director, TNT Logistics Benelux “ Happy employees are one of the most important resources we have. From happy employees come happy customers and happy shareholders.â€? TPG Annual Overview 2004 43 Logistics Matrix™ automatically shares operating data among processes such as strategic planning, optimisation, warehousing activities and back-office functions, and creates significant supply chain efficiencies. The major modules of Matrix™ include: • Matrix™ Designer - strategic network design • Matrix™ Router - real-time routing based on demand from shipping or manufacturing points • Matrix™ Centralised Logistics Manager - event engine that manages the status of all parts, routes and assets • Matrix™ Yard Management and Cross-Dockingradio-frequency-based communications to direct material handlers • Advanced Warehouse Management - all warehousing functionality • Financial Settlement - all transactional activity from the operating systems is used by our financial back-office system, JD Edwards. 44 TPG Annual Overview 2004 Our ambition is to be the recognised worldwide leader in targeted industry sectors. Jeff Hoogesteger delivered a successful acquisition in freight management. After starting and running three successful freight management companies, Jeff Hoogesteger was more than a little familiar with the business. That’s why he was the perfect candidate to help TPG explore the global market to find its own perfect candidate to move it into the freight management business. Hoogesteger joined TPG as group director, Mergers & Acquisitions in 2001. He worked on mergers and acquisitions for all areas of TPG’s business, but his background gave TPG an advantage to achieve its strategic objective of adding freight management to its portfolio. GOTHENBERG, SWEDEN After an extensive search and a nearly 12-month due diligence review, Hoogesteger and his team recommended that TPG purchase Sweden-based Wilson Logistics Group as its first step into the global business. “We targeted Wilson because it offered precisely what we were looking for,” said Hoogesteger. “We looked at the company inside and out. We looked at the management team on all continents, the quality of its services and the people who deliver those services. We liked what we saw.” Hoogesteger and his team then developed a comprehensive plan for integrating Wilson into TPG’s business so it can offer seamless service to customers around the globe. “If there’s one industry that’s benefited from globalisation, it’s freight management,” said Hoogesteger. “Adding this service to our portfolio was a 100% customer-driven proposition. TNT can now make a fantastic offer to our customers, with an array of services that really differentiates us from others. We offer a global network and all the different skills required to operate end-to-end logistics solutions on a global scale. We now cover it all.” After the acquisition, Hoogesteger was selected to serve as managing director of Wilson and now leads its integration into TPG, which he aims to complete by the end of 2005. In the meantime, TPG will be looking for other ways to increase its freight management presence. “This was our first step into freight management,” said Hoogesteger. “We will continue taking more steps.” TPG Annual Overview 2004 45 Logistics Jeff Hoogesteger, Managing Director, Wilson “We targeted Wilson because it offered precisely what we were looking for. We looked at the company inside and out, and liked what we saw.â€? 46 TPG Annual Overview 2004 TPG Annual Overview 2004 47 Logistics Logistics highlights Financial Strategy Earnings from operations 153 24 157 2004 2003 2002 Underlying1 2004 153 103 157 2003 2002 (in € millions) Margin 3.7 0.6 4.3 2004 2003 2002 Underlying1 2004 3.7 2.8 4.3 2003 2002 (in %) Revenues 4,081 3,735 3,610 2004 2003 2002 (in € millions) 1. Excluding TtS costs (earnings/income) and impairments (income) Sustainability Coverage of management systems across Logistics 2003 2004 6% 29% Investor in People 0% 0% Our ambition is to be the recognised worldwide of both 2003 and 2004. Our long-term Logistics strategy encompasses the following: • Standardise key processes that are intended to bring immediate and significant improvements to the profitability of the division. • Serve specific target industry chains, including inbound automotive and outbound spare parts, tyres, consumer electronics and high-tech, publishing and media, and fast-moving consumer goods/retail. • Achieve “network innovator” status, which means that we aim to be an industry innovator in selected sectors. We will do this by creating superior value for customers through new and additional services supported by our innovative Matrix™ technology, our global presence, and our skill at optimising costs. By overseeing the total supply chain, coupled with control over assets and strong expertise in managing operations, we believe our Logistics division can both capitalise on economies of scale and optimise the utilisation of assets and networks to the benefit of our customers. • Expand our areas of operation in those parts of the globe that our key customers consider important to the growth of their businesses. • Establish a global freight management capability, providing both our existing and future customers with a more complete supply chain solution. Market position OHSAS 18001 - Health and Safety SA 8000 - Social Accountability 1 0% 0% 44% 53% ISO 9001 - Quality management 3% 6% With operations in 39 countries, our Logistics division provides services focussed on supply chain management. One key aspect of this service is reducing the time it takes to bring goods from suppliers to their customers by using the latest technology to increase visibility of goods in the supply chain. This objective comes on top of the traditional logistics goal of ensuring that – across the functions of procurement, manufacturing and distribution – the right goods, in the right quantities and condition are available at the right place and time. TNT market share in contract logistics ISO 14001 - Environmental management 1. Compulsory in non-OECD countries Through a combination of targeted acquisitions and organic growth, we have built a truly global Logistics business with significant operations in Europe, North and South America, Asia and Australia. Our acquisition strategy has focussed on achieving critical mass in selected geographies and six industry sectors: inbound automotive; outbound spare parts; tyres; consumer electronics and high-tech; publishing and media; and fast-moving consumer goods/retail. With a few exceptions in certain segments, we believe we have achieved critical mass in terms of market presence and customer base in every market we serve. 3% 2% 2% 1 23 4 1% 5% 5 6 87% 1. TNT 2. UPS 3. DHL 4. Wincanton 5. Exel 6. Other players Source: Annual reports, TNT estimates 48 TPG Annual Overview 2004 Global footprint North America 6,790 employees 72 warehouses 1,600,000 m2 UK Nordics 7,700 employees 69 warehouses 800,000 m2 Benelux South East Asia 3,500 employees 64 warehouses 440,000 m2 1,886 employees 69 warehouses 510,000 m2 Italy France 3,100 employees 43 warehouses 750,000 m2 5,077 employees 14 warehouses 340,000 m2 648 employees 14 warehouses 291,000 m2 Germany & Eastern Europe 2,600 employees 18 warehouses 285,000 m2 South America China 1,200 employees 19 warehouses 136,000 m2 Spain 6,398 employees 85 warehouses 1,600.000 m2 Australia Turkey 730 employees 12 warehouses 170,000 m2 560 employees 25 warehouses 155,000 m2 372 employees 2 warehouses 58,000 m2 Logistics operating revenue per industry 2004 Automotive %-of total 2003 %-of total 2002 1 %-of total 1,455 35.8 1,428 38.2 1,379 38.2 642 15.7 635 17.0 655 18.1 Hi-tech and electronics 503 12.3 499 13.4 445 12.3 Publishing and media 250 6.1 229 6.1 238 6.6 221 5.9 219 6.1 Fast-moving consumer goods Tyres 177 4.3 Freight management (Wilson) 279 6.8 Other 775 19.0 723 19.4 674 18.7 4,081 100.0 3,735 100.0 3,610 100.0 Total - - 1. Restated to reflect the impact of the transfer of In-night services from express to logistics. 2004 Business development efficiency 2003 18% 2004 Number of warehouses Number of square metres managed (in thousands) 2002 22% 2003 20% 2002 1 655 471 415 7,098 6,607 6,186 Joint ventures Number of warehouses Number of square metres managed (in thousands) 44 69 70 1,359 969 968 1. Restated to reflect the impact of the transfer of In-night services from express to logistics. TPG Annual Overview 2004 49 Corporate sustainability When it comes to corporate sustainability, we promise transparency about the economic, environmental and social dimensions of our business. In 2004, we made good on that promise, sharing our results with the world. 50 TPG Annual Overview 2004 We recognise that some of these data are subject to a degree of uncertainty due to the various methods and measurement techniques used to determine the environmental and health and safety data. Building sustainability into our business is an ongoing process, which we will continue to develop when refining our data and reporting systems for our future reports. This year, for the first time, we’re making our corporate sustainability report public. This move confirms our commitment to be open about how we manage the economic, environmental and social dimensions of our business, how our business affects people and the world, and how we aim for continuous improvement. The report sets forth our corporate sustainability strategy and goals, and measures our progress towards meeting those goals. You can find the full report on our website at www. tpg.com. Sustainability was important to all three of our businesses long before our group was formed in 1998. In 2000, we began aligning the various initiatives within our three divisions. In 2002 we adopted a corporate sustainability policy, and signed the United Nations Global Compact, which deals with human rights, labour rights and environmental protection. We support the standards of the Organisation for Economic Cooperation and Development and the International Labour Organisation, and our TPG Business Principles are based on these guidelines. Also in 2002, we established an annual award competition to recognise outstanding contributions to sustainability within the company, made preparations for reporting according to the guidelines of the Global Reporting Initiative, and set up a sustainability process with the company. Reporting on our efforts is the next step in our corporate sustainability journey. Covering our activities for 2003 and 2004, our report establishes baseline measurements for issues that affect key stakeholders – our customers, our people, our shareholders and our world. Because we see corporate sustainability as an integral and necessary part of our ongoing business, and not as a separate activity, we are reporting our 2004 corporate sustainability results alongside our 2004 financial results. With respect to performance data, we present figures from only those parts of our organisation that are externally certified against the standards explained below. This is because we believe that only these data really make sense since the certificates guarantee active management. Corporate sustainability: The challenge and our ambitions For too many organisations, sustainability simply means avoiding liabilities or not doing bad things. At TPG, we define it differently. For us, the essence of corporate sustainability is an active search for opportunities to make our world a better place. It’s about actively doing good things. To guide our pursuits, we have set forth our corporate sustainability ambition on three consecutive levels. Think of it as a three-tiered pyramid with global standards at the base, industry-related initiatives in the middle and TPG’s unique approach to corporate sustainability at the top. We’re building from the ground up. Manage: Meet the standards We have selected leading international standards to ensure that we can fulfil and measure our corporate sustainability promises in the course of our day-today business. The following systems for measuring actions have already been implemented across many of our business units. By 2007, they are expected to be implemented across all business units. • ISO 9001 to ensure operational excellence • OHSAS 18001 to ensure safe workplaces • ISO 14001 to ensure responsible treatment of the environment • Investors in People to enable our employees to continuously develop • SA 8000 to demonstrate social accountability, particularly in non-OECD countries • Global Reporting Initiative guidelines to report corporate sustainability performance. TPG Annual Overview 2004 51 Corporate sustainability Luis Rivera, Shipping Supervisor, TNT Logistics “ Being involved in the Moving the World partnership made me feel part of something very big, something great. I’d do it again in a heartbeat.” 52 TPG Annual Overview 2004 TPG Annual Overview 2004 53 Corporate sustainability Luis Rivera delivered clean water – and baseball equipment. As a shipping supervisor for TNT Logistics’ contract with Hewlett-Packard in Puerto Rico, Luis Rivera takes pride in delivering the right goods when and where his customer needs them. But the satisfaction he gets from running the shipping operation pales in comparison to how he feels about his work for the World Food Programme (WFP). AGUAVILLA, PUERTO RICO Rivera joined the company three years ago when Hewlett-Packard outsourced its logistics operations to TNT, and he was among the first team of eight volunteers who spent three months working with WFP’s school feeding programme. Rivera and Sandra Moneta of TNT Argentina worked with schools in Nicaragua. Their first task was to determine what the schools needed to be able to provide healthy meals to students. “The first thing we saw was that there was no electricity and no water,” recalled Rivera. “It rains a lot in Nicaragua, but the water is used for so many purposes it’s no longer good for drinking. Supplying electricity would have been difficult, but water we could do something about.” Rivera and Moneta proposed installing water collection tanks, simple water filters and working stoves at 54 TPG Annual Overview 2004 each school. Then, working with local WFP staff and parents, they successfully installed those three items at a school with about 80 students. Having clean water and a functioning stove for cooking the cereal, rice and beans WFP provides meant children got hot, nutritious meals. “For many of these kids, this is the only food they get each day,” said Rivera. Clean water and stoves are not the only items lacking at the schools. “A class of five kids might have two pencils and one notebook to share,” said Rivera. When Rivera and Moneta arrived, the children played baseball with a stick and a ball of yarn, using their hats as baseball gloves. “Nicaragua loves baseball, and the kids love to play it after lunch,” said Rivera. After meeting the students’ need for food, Rivera and Moneta wanted to give them something more, so they asked their colleagues back home to donate money to buy some real baseballs, bats and gloves. “Of course we should take care of their health and help them study, but they are kids. They also need to play.” Rivera’s work with WFP has reinforced his bond to TNT. “My colleagues and I work in Hewlett-Packard’s facilities,” he said. “Our building doesn’t even have a TNT sign on it, but being involved in the Moving the World partnership made me feel part of something very big, something great. I’d do it again in a heartbeat.” Express Logistics TPG 24% 63% 64% 46% 54% 37% 76% Fully owned operations (including rent and lease contracts and temporaty staff) Our ambition is to certify all our fully owned operations. The charts above show the scope of our ambition, indicating the balance between fully owned operations and subcontractors. DIFFERENTIATE IMPROVE MANAGE Improve: Sector reputation The second tier of our ambition calls for us to help enhance the reputation of our entire sector. We aim to do that via the World Economic Forum’s logistics and transportation corporate citizenship initiative, which comprises companies from across the industry, from sea freighters to TPG’s key global competitors. We have been actively involved in this group since mid-2003. Chairmanship of the group is awarded annually to a participating company, and in 2004 TPG CEO Peter Bakker led the effort. In January, a number of the CEOs of participating companies signed the Logistics and Transportation Corporate Citizenship Principles and called on their peers to place corporate citizenship at 36% Contracted out (suppliers, agents, subcontractors) the centre of their business strategies. TPG is one of the signatories. The principles include conducting a consultation with key sector stakeholders. The consultation was begun in 2004, when 182 organisations provided input on those corporate citizenship issues they believe the sector should focus on. It continued with a discussion with customers, which will be followed in 2005 by one with employees. Based on this input, involved companies have engaged in a stakeholder dialogue facilitated by the Global Reporting Initiative with the purpose of agreeing key performance indicators (KPIs) relevant for the sector, and encouraging an industry-wide ambition to manage according to those KPIs. TPG Annual Overview 2004 55 Corporate sustainability Stefania Lallai delivered employee empowerment through information. TURIN, ITALY Stefania Lallai joined TNT Express in Italy in 2001 with a clear mandate. When the business unit’s first Investor in People survey revealed employees’ need to know more about their company, Lallai was hired to establish the unit’s first internal communication department to cascade information to the more than 3,000 people who work in 135 depots and 162 locations across Italy. One of Lallai’s first objectives was to help employees see that TNT is larger than their own environments, that the company depends on their contributions each day, but that it also transcends the network in Italy. “If you only see your part of the work, you cannot perceive what a great feat it is to deliver a parcel from the other side of the world to a customer in Italy,” said Lallai. “Behind every parcel we deliver is an enormous world that is constantly moving. It’s really an amazing company.” Also central to Lallai’s mandate was cascading business strategy to employees at all levels. To get those messages across, Lallai and a team established an intranet that reaches all depots and locations. “The site really shortened the distances between the field and head office,” she said. “It created a sense of teamwork and started the process of employee involvement.” 56 TPG Annual Overview 2004 To continue that momentum, Lallai also developed the business unit’s first social report in 2001. Capturing information about the business unit and presenting it in a document that adheres to Global Reporting Initiative guidelines and is certified by independent auditors, Lallai reasoned, was one of the best ways to inform employees. Lallai’s reasoning proved sound. Now in its third year, the report is distributed not only to employees, but to customers, subcontractors, social associations and other stakeholders. It has drawn employee feedback that led to development of a career-track training programme, garnered attention from the Italian ministry of welfare, and served as the catalyst for a dialogue with employees and customers. Lallai sees the report and the actions that have resulted from it as central not only to the unit’s communication strategy, but to its business strategy. “To me, being a leader means providing clear, factual communication about what we really are. It’s important to face the market with an awareness that we are a great company, but with a humble approach of serving our customers and stakeholders in the best way we can. When you can show you’re great, you don’t have to shout it. People will see that and they will follow you.” TPG has set an objective to meet key milestones in the second tier of its corporate sustainability ambition – improving our sector reputation – by 2006. Differentiate: Lead the industry The third tier of our corporate sustainability ambition aims to distinguish TPG from its peers. Here, we have defined three specific areas where we want to put TPG at the front of the industry: • Delivering Clean: Supporting the reduction of carbon dioxide emissions by helping to develop a “clean” truck. • Driving Safety: Developing a plan to enhance road safety and reduce the number of road accidents we’re involved in; leveraging this experience to develop a tailor-made road safety plan for China. • Moving the World and Moving our City: Helping the World Food Programme fight hunger; developing a neighbourhood survey to assess needs and make focussed contributions to worthy causes in our own communities. Our rating in the Dow Jones Sustainability Index In 2004, TPG’s economic, environmental and social dimensions were reviewed and rated by the Dow Jones Sustainability Index. TPG received a total sustainability score of 46 out of a possible 100 points. The bestranked company received a total score of 69. TPG’s overall sustainability performance Total score 46 44 69 Economic dimension 53 65 70 Environmental dimension 39 25 76 Social dimension 46 43 72 (in %) We see corporate sustainability as an integral and necessary part of our ongoing business. Average score Company score Best score GET MORE INFORMATION Visit these links on the TPG corporate website for detailed information about: TPG Business Principles corporategovernance/ TPGbusinessprinciples/index.asp TPG Whistleblower Policy corporategovernance/ TPGbusinessprinciples/ whistleblowerpolicy/index.asp Compliance to Global Compact corporatesustainability/ unglobalcompact/index.asp Compliance with World Economic Forum principles corporatesustainability/ roadtosocialleadership/improve/ index.asp World Economic Forum stakeholders survey v281204.html Dow Jones Sustainability Index assessment Jones_Sustainability_World_ Index_Assessment_2004_ tcm31-75044.pdf TPG Annual Overview 2004 57 Management M.P. (Peter) Bakker (1961) Peter Bakker is Chief Executive Officer of TPG and chairman of the Board of Management. He joined TPG Post in 1991. In 1996, he was appointed financial control director of TPG Post, and was nominated to the TPG Post board of management in 1997. From the demerger from KPN in June 1998, Bakker was chief financial officer of TPG and a member of the Board of Management. On 1 November 2001, he was appointed CEO and chairman of the Board of Management. Bakker is a Dutch national and earned a degree in economics from Erasmus University in Rotterdam. Number of TPG shares owned: 12,832 J.G. (Jan) Haars (1951) Jan Haars is chief financial officer of TPG and a member of the Board of Management. He joined the company in August 2002. Prior to that, Haars worked for ABN AMRO Bank, Thyssen Bornemisza Group, Royal Boskalis Westminster, Rabobank Nederland, and most recently as worldwide group treasurer of Unilever N.V. Haars is a Dutch national and earned a degree in applied mathematics from the University of Twente in Hengelo. Number of TPG shares owned: 12,903 H.M. (Harry) Koorstra (1951) Harry Koorstra is Group Managing Director Mail and a member of the TPG Board of Management. He joined TPG Post in 1991 as managing director of its Media Services business unit and became a member of its board of management in 1997. Before joining the company, Koorstra worked for 15 years at the Netherlands’ largest publisher, VNU. Koorstra is a Dutch national and earned degrees in civil engineering and business economics from the Polytechnic in Amsterdam and Dordrecht. Number of TPG shares owned: 12,031 M.C. (Marie-Christine) Lombard (1958) Marie-Christine Lombard is Group Managing Director Express and a member of the TPG Board of Management. She joined the company in 1998 when TPG acquired Jet Services, where she was managing director. She served as managing director of TNT Express France until her appointment as Group Managing Director Express on 1 January 2004. Lombard is a French national and earned a master’s degree in business from ESSEC Business School in Paris. Number of TPG shares owned: 0 D.G. (Dave) Kulik (1948) Dave Kulik is Group Managing Director Logistics and a member of the TPG Board of Management. He joined the company in September 2000 when TPG purchased CTI Logistx, where he was president and CEO. He served as managing director of TNT Logistics North America before his appointment as Group Managing Director Logistics on 1 September 2003. Kulik is an American national and earned a degree in transportation management from Youngstown State University in Youngstown, Ohio. Number of TPG shares owned: 5,871 J. (Jeroen) Brabers (1953), Corporate Secretary 58 TPG Annual Overview 2004 Information for shareholders Since 29 June 1998, following our demerger from KPN, our ordinary shares have been listed on the Amsterdam Stock Exchange (which was renamed Euronext Amsterdam in connection with the merger of the Amsterdam, Brussels and Paris stock exchanges in 2000), the London Stock Exchange, the New York Stock Exchange and the Frankfurt Stock Exchange. The principal market for trading in TPG ordinary shares is Euronext Amsterdam. TPG is included in the AEX index, which comprises the top 25 companies in the Netherlands, ranked on the basis of their turnover in the stock market and free float. We have an unrestricted sponsored American Depositary Receipt (ADR) facility with Citibank N.A. as depositary. The ADRs evidence American Depositary Shares (ADSs), which represent the right to receive one ordinary share. The ADSs trade on the New York Stock Exchange under the symbol TP. Average daily volume (in shares) in 2004: 2004 2003 1st quarter 1,654,655 1,356,444 2nd quarter 1,492,099 1,242,102 3rd quarter 1,491,089 1,404,351 4th quarter 1,559,948 1,272,351 The highest quotation of TPG shares during 2004 was € 20.15 on 7 October and the lowest was € 16.22 on 24 March. A total of 5,836,500 shares in the form of ADRs were traded on the New York Stock Exchange in 2004, compared with 5,674,500 in 2003. 2004 2003 2002 Stock price (in €) High 20.15 19.34 25.07 Low 16.22 11.71 14.98 19.98 18.57 15.45 140.9 63.1 126.1 Dividend in € cents 57.0 48.0 40.0 Dividend pay-out ratio (as a %) 40.5 76.1 31.7 Earnings per outstanding share in € cents Dividend yield (based on closing rate for the year) P/E Ratio Number of issued shares Stock market capitalisation (in € billions) 2.85 2.58 2.59 14.18 29.41 12.26 480,259,522 480,259,522 480,259,522 9,596 8,823 7,420 TPG Annual Overview 2004 59 Information for shareholders Stock performance 21 20 19 18 17 16 JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC Our relative performance on the AEX at closing prices during 2004 (AEX index rebased to TPG) 35 30 25 20 15 10 5 1998 1999 2000 2001 2002 2003 2004 Our relative performance on the AEX at closing prices since its listing in 1998 (AEX index rebased to TPG) Our ordinary shares are held worldwide in the form of bearer shares, non-ADS registered shares and ADSs. Outside the United States, ordinary shares are held primarily in bearer form. In the United States, ordinary shares are held primarily in the form of ADSs. Only bearer shares are traded on Euronext Amsterdam and the other European exchanges on which our ordinary shares are listed. Only ADRs relating to ADSs are traded on the New York Stock Exchange. The following table indicates the form in which the ordinary shares were held as of 22 February 2005: Forum Number of shares Bearer shares Non-ADS registered shares ADSs 1 Percentage of outstanding ordinary shares 385,065,260 80.18% 89,376,767 18.61% 5,817,496 1.21% 1. Held by approximately 55 holders of record. Since some shares are held by brokers and other nominees for their clients, this number may not be representative of the actual number of ordinary shares held by US residents or of the actual number of US-resident beneficial holders of ordinary shares. 60 TPG Annual Overview 2004 On 4 October 2004, TPG took delivery of 7.6 million shares at €19.74 per share. On 5 January 2005, TPG took delivery of another 13.1 million shares at the same price. As of that date, the State of the Netherlands owns 18.6% of TPG’s ordinary shares. In 2004, 398.7 million TPG shares were traded on the Euronext Amsterdam market (2003: 336.6 million). Peer group comparison For comparative reasons, we have deďŹ ned a peer group of publicly listed companies with activities in the same industries in which TPG is active. This peer group consists of the Germany-based company Deutsche Post World Net (DPWN) with activities in mail, express and logistics; the United Kingdom-based company Exel, with activities in logistics; Switzerland-based Kuehne & Nagel, with activities in freight management and logistics; as well as the two United States-based express carriers FedEx (FDX) and United Parcel Service (UPS). For this peer group, the comparative performance in terms of total shareholder returns in 2004 is charted below. 80 60 40 20 0 -20 AEX Eurotop 300 DPWN FDX UPS EXEL Kuehne & Nagel TPG 6.8% (11.6%) 6.2% 46.2% 16.4% 1.8% 59.1% 10.6% Total shareholder return 40 20 0 -20 -40 2000 2001 2002 2003 2004 (8.2) (4.3) (35.3) 23.5 10.6 Dividend We aim to meet shareholder return requirements through dividends and growth in value of our shares. TPG annually pays interim and ďŹ nal dividends in cash, denominated in euros. Exchange rate movements will affect the amounts received by ADS holders on conversion by the depository of such cash dividends. 60 50 40 30 20 10 0 1997 1998 1999 2000 2001 2002 2003 2004 36 36 36 36 38 40 48 57 TPG Annual Overview 2004 61 Information for shareholders TPG in figures from 2000 Year ended at 31 December 2004 2003 2002 2001 2000 1 3,900 3,915 4,005 3,896 3,706 Express 2 4,696 4,251 4,175 3,910 4,145 Logistics 2 4,081 3,735 3,610 3,353 2,179 (42) (35) (8) 59 (94) 12,635 11,866 11,782 11,218 9,936 4,305 4,163 4,027 3,836 3,230 Intercompany / Non allocated Total operating revenues Salaries /social security contributions Depreciation, amortisation and impairments Other expenses Total operating expenses Total operating income as % of total operational revenues Net financial (expense) / income Income taxes Results from investments in affiliated companies Minority interests Net income 533 711 490 437 343 6,623 6,225 6,207 5,928 5,542 11,461 11,099 10,724 10,201 9,115 1,174 767 1,058 1,017 821 9.3% 6.5% 9.0% 9.1% 8.3% (77) (92) (108) (93) (60) (428) (368) (341) (335) (282) (3) (6) (5) (1) (4) 1 (1) (5) (3) (2) 667 300 599 585 473 Fixed assets 5,083 5,057 5,573 5,587 5,216 Current Assets 3,199 2,858 2,693 2,867 2,380 Total Assets 8,282 7,915 8,266 8,454 7,596 Group Equity 3 2,784 2,986 2,979 2,613 2,199 Provisions 1,237 817 1,036 1,173 1,311 Long-term liabilities 1,646 1,661 1,661 1,789 577 2,615 2,451 2,590 2,879 3,509 8,282 7,915 8,266 8,454 7,596 937 1,032 Short-term liabilities Total liabilities and group equity 3 Net cash provided by operating activities 1,000 773 572 Net cash used in investing activities (338) (373) (518) (698) (1,242) Net cash used by financing activities (500) (436) (598) 125 592 Changes in cash and cash equivalents 162 128 (84) 200 (78) Interest cover (times) 15.2 8.3 9.8 10.9 Average total capital 8,099 8,091 8,360 8,025 6,909 Return on average total capital 14.5% 9.5% 12.7% 12.7% 11.9% 13.7 Return on Assets 14.2% 9.7% 12.8% 12.0% 10.8% Net return on Equity 3 24.0% 10.0% 20.1% 22.4% 21.5% Gearing at year end 23.6% 26.4% 32.0% 39.8% 37.7% 290 287 398 454 388 Capital expenditures on major fixed assets as % of turnover 2.8% 3.0% 4.0% 4.3% 3.9% Capital expenditure on investments as % of turnover 1.8% 0.6% 1.2% 2.9% -0.3% Cash conversion efficiency 7.9% 7.9% 8.8% 6.9% 5.8% 3 Capital expenditure on PPE Number of ordinary shares on diluted basis (in millions) 474.0 475.4 475.0 475.1 477.3 Net income per diluted ordinary share (€) 1.41 0.63 1.26 1.23 0.99 Total shareholder return (%) 10.6 23.5 (35.3) (4.3) (8.2) (in € millions, unless otherwise stated) 1. Restated to reflect the impact of the changes in accounting principles in 2001. 2. Restated to reflect the impact of the transfer of Innight services from express to logistics. 3. Per 1 January 2003 dividends proposed, but not yet declared, are to be presented as a component of equity instead of a liability. The prior year balances are adjusted for comparison purposes. 62 TPG Annual Overview 2004 2005 financial calendar 28 February Announcement of 2004 full-year results 7 April TPG Annual General Meeting of Shareholders 11 April Ex-dividend listing of TPG shares 18 April Payment of final dividend 4 May Publication of 2005 first-quarter results 29 July Publication of 2005 half-year results 31 October Publication of 2005 third-quarter results Publications TPG Share is a Dutch-language quarterly magazine distributed to 14,000 individual shareholders and other interested readers in the Netherlands. This magazine and other publications can also be viewed and ordered through our website. Websites For the latest and archived press releases, corporate presentations and speeches, current share price and other company information such as our online annual report and interim reports, visit our website at www. tpg.com. Our website also offers special sections with information about Corporate Governance and Investor Relations, and links to the websites of Euronext Amsterdam; the United States Securities and Exchange Commission; AFM, the authority for Dutch financial markets; and other public institutions. Our interactive site is continuously refined to better reflect those topics of interest to investors. It is possible to subscribe via the website to regular e-mail updates about our company and related topics. TPG Investor Relations Through our Investor Relations activities, we aim to provide shareholders with accurate and timely information. We proactively and openly communicate with institutions and private investors and with intermediary groups such as analysts and financial journalists. In addition to the quarterly, half-yearly and yearly financial results presentations, we maintain regular contacts with financial analysts and retail and institutional investors through meetings, roadshows, conference calls and visits. In 2004, we visited investors in major financial cities in Europe, the United States and Asia. Our annual report on Form 20-F is filed electronically with the United States Securities and Exchange Commission. Mailing address TPG Investor Relations P.O. Box 13000 1100 KG Amsterdam The Netherlands Visiting address Neptunusstraat 41-63 2132 JA Hoofddorp The Netherlands Telephone Fax E-mail Website +31 20 500 6455 +31 20 500 7515 investorrelations@tpg.com We also invite you to visit and. TPG Annual Overview 2004 63 Published by TPG N.V. P.O. Box 13000 1100 KG Amsterdam The Netherlands This annual overview includes a summary of the information presented in the official 2004 annual report of TPG N.V. (TPG). A Dutch translation of this document is also available. Telephone General + 31 20 500 6000 Investor Relations + 31 20 500 6241 Information contained in this overview and the annual report can also be found on our website. For additional copies of the English or Dutch overview or report, e-mail a request to annualreport@tpg.com, fax a request to + 31 26 319 5221 or send a request to TPG Investor Relations. Fax + 31 20 500 7000 Website Chamber of Commerce Amsterdam Reg. No. 27168968 Coordination and design Mattmo concept | design Photography Anton Corbijn Lithography and printing De Bussy Ellerman Harms Binding Binderij Hexspoor 64 Note about forward-looking statements Except for historical statements and discussions, statements contained in this document are forward-looking statements. By their nature, forward-looking statements involve risk and uncertainty because they relate to events and depend on circumstances that will occur in the future. These forward-looking statements involve known and unknown risks, uncertainties and other factors, many of which are outside our control, and may cause actual results to differ materially from any future results expressed or implied in the forward-looking statements. These forward-looking statements are based on current expectations, estimates, forecasts and projections about the industries in which TPG operates, management’s beliefs and assumptions made by management about future events. There are a number of factors that could cause actual results and developments to differ materially from those expressed or implied by these forward-looking statements, including, but not limited to those described in our 2004 annual report. As a result of these and other factors, no assurance can be given as to TPG’s future results and achievements. You are cautioned not to put undue reliance on these forward-looking statements, which are neither predictions nor guarantees of future events or circumstances. TPG disclaims any obligation to publicly update or revise these forward-looking statements, whether to reflect new information, future events or circumstances or otherwise. TPG Annual Overview 2004 Glossary of terms used in this annual overview Average total capital The averaged sum of the total assets of two consecutive years. Interest cover (times) Total operating income divided by net financial (expenses)/income. Capital expenditures on investments as % of turnover The capital expenditures on acquisitions of new, or stake increase in existing group and/or affiliated companies as a percentage of total operating revenues. International Organization for Standardization (ISO) The ISO is a network of national standards institutes from 146 countries working in partnership with international organisations, governments, industry, business and consumer representatives. The ISO is the source of ISO 9000 standards for quality management, ISO 14000 standards for environmental management, and other international standards for business, government and society. For more information, see. Capital expenditures on major fixed assets as % of turnover The capital expenditures on property, plant and equipment and other tangibles as a percentage of total operating revenues. Cash conversion efficiency Net cash provided by operating activities as a percentage of total operating revenues. Corporate governance The OECD (see reference elsewhere in this glossary) defines corporate governance as the system by which corporations are directed and controlled. The corporate governance structure specifies the distribution of rights and responsibilities among different participants such as the board, managers, shareholders and other stakeholders, and spells out the rules and procedures for making decisions. By doing this, it also provides the structure through which company objectives are set, and the means of attaining those objectives and monitoring performance. Dow Jones Sustainability Indexes Launched in 1999, the Dow Jones Sustainability Indexes are the first global indexes tracking the financial performance of the leading sustainability-driven companies worldwide. They provide asset managers with reliable and objective benchmarks to manage sustainability portfolios. For more information, see. Free cash flow Cash flow from operations minus net capital expenditure on plant, property and equipment and other intangible assets. Gearing at year end The net debt as percentage of total group equity plus net debt. Global Reporting Initiative (GRI) The GRI is a multi-stakeholder process and independent institution whose mission is to develop and disseminate globally applicable sustainability reporting guidelines for voluntary use by organisations reporting on the economic, environmental and social dimensions of their business. The GRI incorporates participation of business, accountancy, investment, environmental, human rights, research and labour organisations from around the world. Started in 1997, the GRI became independent in 2002, and is an official collaborating centre of the United Nations Environment Programme, and works with the United Nations Global Compact. For more information, see. Operating revenues Net sales and other revenues. Organisation for Economic CoOperation and Development (OECD) The Organisation for Economic CoOperation and Development (OECD) comprises 30 member countries that share a commitment to democratic government and the market economy. Member countries – sometimes referred to as OECD countries – represent the world’s key developed countries. For more information, see. Return on assets The total operating income as a percentage of the total assets. Investors in People Developed in 1990 by a partnership of leading businesses and national organisations, Investors in People helps organisations to improve performance and realise objectives through the management and development of their people. For more information, see. Return on average total capital The total operating income as percentage of the average total capital. ISO 14001 (environmental management) The ISO 14001 standard is an international standard for the control of environmental aspects and the improvement of environmental performance. Minimising harmful effects on the environment and achieving continual improvements in environmental performance. SA 8000 (social accountability) SA8000 is a standard issued by human rights organisation Social Accountability International (SAI). The standard is designed to maintain just and decent working conditions throughout a supply chain. It is based on international workplace norms in the International Labour Organization conventions and the UN’s Universal Declaration of Human Rights and the Convention on Rights of the Child. It covers child labour, forced labour, health and safety, freedom of association and right to collective bargaining, discrimination, discipline, working hours, compensation and management systems. For more information, see. ISO 9001 (quality management) The ISO 9000 standards cover an organisation’s practices in fulfilling the customer’s quality requirements and applicable regulatory requirements while aiming to enhance customer satisfaction and achieve continual improvement of its performance in pursuit of these objectives. Key Performance Indicators (KPIs) KPIs are measures that focus on the achievement of outcomes critical to the current and future success of an organisation. These indicators should deal with matters that are linked to the organisation’s mission and vision, and are quantified and influenced where possible. Net return on equity Net income as a percentage of total group equity. OHSAS 18001 (occupational health and safety) OHSAS 18001 is a standard for occupational health and safety management systems. It is intended to help organizations control occupational health and safety risks, and was developed in response to widespread demand for a recognised standard for certification and assessment. OHSAS 18001 was created through collaboration of several of the world’s leading national standards bodies, certification organisations and consultancies. For more information, see. Revenue quality yield The percentage change year-on-year in revenue per consignment plus the percentage change year-on-year per kilo divided by two. Sarbanes-Oxley The Sarbanes-Oxley Act was signed into law on 30 July 2002, introducing significant legislative changes to financial practice and corporate governance regulation. It also introduced a number of deadlines, where multinational companies must meet the financial reporting and certification mandates for any end-of-year financial statements filed after 15 November 2004 (amended from 15 June). The act is named after its main architects, Senator Paul Sarbanes and Representative Michael Oxley, and followed a series of high-profile scandals, such as Enron. Sarbanes-Oxley allows firms to stay abreast of the proposed and final rules and regulations issued by the United States Securities and Exchange Commission to implement the Act. For more information, see. com. Total shareholder return The total share price appreciation (or depreciation) plus return on reinvestment of gross dividend. (Source: Bloomberg Professional) World Economic Forum The World Economic Forum is an independent international organisation committed to improving the state of the world. It provides a collaborative framework for the world’s leaders to address global issues, engaging its corporate members in global citizenship. For more information, see and “Principles of Corporate Citizenship.” TPG N.V. P.O. Box 13000 1100 KG Amsterdam The Netherlands Telephone +31 20 500 6000 Fax +31 20 500 7000 Royal TPG Post P.O. Box 30250 2500 GG The Hague The Netherlands Telephone +31 70 334 3434 TNT P.O. Box 13000 1100 KG Amsterdam The Netherlands Telephone +31 20 500 6500
https://issuu.com/mattmo/docs/tpg_annual_overview_2004
CC-MAIN-2017-34
refinedweb
19,196
51.48
23 January 2008 10:49 [Source: ICIS news] (updates closing share, oil and naphtha prices in paragraphs 4-9, 12 and 15) By Jeanne Lim SINGAPORE (ICIS news)--Asia-Pacific petrochemical stocks bounced back on Wednesday from a two-day meltdown as the US Federal Reserve’s move to cut interest rates boosted investor sentiment. In a rare policy move outside of its ordinary meetings, the Federal Reserve cut interest rates by 75 basis points to 3.5% on Tuesday, its biggest cut in more than 23 years. By lowering borrowing costs, such a move should help industry by boosting spending as well as lowering investment costs, and possibly stave off an ?xml:namespace> Japanese chemical stocks ended 2-3% higher as the Nikkei 225 index closed 2% up at 12,829.06 points. The share price of chemical major Asahi Kasei closed 2.4% higher after gaining as much as 5.4% earlier in the day while Mitsubishi Chemical and Mitsui Chemical stocks closed at 2.3% and 2.9% respectively. The shares of Chinese state-owned refiners PetroChina and Sinopec continued their upward trend and closed 17.5% and 17.6% higher respectively as The Standard & Poors/Australia Stock Exchange (ASX) 200 index jumped 4.4% to close at 5,412.30 points while the Stock Exchange of Thailand (SET) index recovered from earlier losses to close 2.8% higher. In South Korea, the Korea Composite Stock Price Index (KOSPI) ended 19.4% higher but stocks of chemical majors such as LG Chemical and Hanwha Chemicals saw their stock price end 1.2-3.8% lower respectively. SK Energy’s share price closed 3.8% lower after rising slightly in the day while Honam Petrochemical’s stock continued its rise to close higher at 3.8%. The Federal Reserve interest rate cuts could have boosted market sentiment in “I think the interest cuts could not remove all the concerns of the market for the time being. Particularly in the first quarter, the stock market will maintain its weak trend,” he added. Crude oil hovered near $89/bbl, attempting to consolidate a nervous recovery after the Asian naphtha markets picked up a little, tracking the $3/bbl rebound in crude values. Discussion levels for second half March naphtha cargoes were heard at $831-834/tonne CFR (cost and freight) Asian naphtha was traded at $837-839/tonne CFR Japan for second-half March open spec grades. Some traders were, however, worried that if the Prices fell $38/tonne on Tuesday, following the stock market meltdown. The Asian toluene market was quiet on Wednesday following the $15/tonne erosion of offers to $905/tonne FOB (free on board) However, traders anticipate prices to firm slightly on Wednesday on the back of stabilised crude values and modest overnight gains in the A higher offer emerged mid morning at $920/tonne FOB But trade was scant as the Meanwhile, a South Korean polyethylene terephthalate (PET) producer said that there had been no effect on prices so far on steadying crude values. “Crude will impact on raw material one month later usually. Our deals have been concluded at lower prices because bid prices are decreasing. Demand is weak,” he said. Another southeast Asia-based orthoxylene (OX) trader added that he didn’t think that the interest rate cut would have any impact on the market. ($1 = €0.68) Helen Lee, Prema Viswanathan and Hong Chou H
http://www.icis.com/Articles/2008/01/23/9094947/asia-petchem-stocks-close-higher.html
CC-MAIN-2014-49
refinedweb
573
62.07
Extracted from: iOS Recipes Tips and Tricks for Awesome iPhone and iPad Apps This PDF file contains pages extracted from iOS Recipes, published by the Prag- matic Bookshelf. For more information or to purchase a paperback or PDF copy, please visit. Note: This extract contains some colored text (particularly in code listing). This is available only in online versions of the books. The printed versions are black and white. Pagination might vary between the online and printer versions; the content is otherwise iOS Recipes Tips and Tricks for Awesome iPhone and iPad Apps Matt Drance Paul Warren: Jill Steinberg (editor) Potomac Indexing, LLC (indexer) Kim Wimpsett -74-6 Printed on acid-free paper. Book version: P1.0—July 2011 Your goal as a programmer is to solve problems. Sometimes the problems are hard, sometimes they’re easy, and sometimes they’re even fun. Maybe they’re not even “problems” in the colloquial sense of the word, but you are there to discover solutions. Our goal as authors is to help you solve your problems better and more quickly than before—preferably in that order. We decided to write a recipe- style book that focuses on a specific set of tasks and problems that we attack explicitly, rather than discuss programming issues at a high level. That’s not to say we’re not about educating in this book. The blessing of a recipe book is that it gives you trustworthy solutions to problems that you don’t feel like discovering on your own. The curse of a recipe book is that you might be tempted to copy and paste the solutions into your project without taking the time to understand them. It’s always great to save time by writing less code, but it’s just as great to think and learn about how you saved that time and how you can save more of it moving forward. If you are familiar with the iOS SDK and are looking to improve the quality and efficiency of your apps, then this book is for you. We don’t teach you how to write apps here, but we hope that this book helps you make them better. If you’re more of an advanced developer, you may find that you save yourself time and trouble by adopting some of the more sophisticated tech- niques laid out in the pages that follow. We wrote many of these recipes with maximum reusability in mind. We weren’t after demonstrating a technique or a snippet of code that simply gets the job done. Instead, we set out to build solutions that are ready for you to integrate into whatever iPad and iPhone projects you’re working on. Some might find their way into your projects with zero changes, but you should feel free to use this recipe book as you would a traditional cookbook. When cooking food from a recipe, you might add or remove ingredients based on what you like, or need, in a meal. When it comes to your own apps and projects, this book is no different: you are invited to extend and edit the projects that accompany these recipes to fit your specific needs. The recipes in this book help you get from start to finish, but we hope they also encourage you to think about when and why to choose a certain path. There are often multiple options, especially in an environment like Cocoa. With multiple options, of course, come multiple opinions. In the interest of consistency, we made some decisions early on about certain patterns and approaches to use in this book. Some of these techniques may be familiar to you, some may be employed in a way you hadn’t considered, and some may be brand new to you. Regardless, we’d like to explain some of our deci- sions up front so that there are no surprises. Formatting and Syntax We had to format a few code snippets in this book to fit the page. A verbose language like Objective-C doesn’t always play nicely with character limits, so some of the code may sometimes look unusual. You may encounter terse method or variable names, a seemingly excessive number of temporary variables, and odd carriage returns. We tried to preserve the “spirit” of Cocoa convention as much as possible, but in a few places the printed page won. Don’t be alarmed if the coding style suddenly changes from time to time. Categories A fair number of recipes make use of categories on standard Apple classes to accomplish tasks. Categories are an incredibly powerful feature of the Objective-C programming language, and they tend to alienate new Cocoa programmers. Categories can also quickly pollute namespaces and create (or mask) unexpected behavior in complex class hierarchies. They aren’t to be feared, but they are to be respected. When considering a category, do the following: • Ask yourself whether a subclass or a new class would be more appropri- ate. As The Objective-C Programming Language from Apple states, “A category is not a substitute for a subclass.” • Always prefix category methods when extending a class you don’t control (for example, UIApplication) to avoid symbol collisions with future APIs. All new category methods in this book use a prp_ prefix. • Never override defined methods such as -drawRect: in a category. You’ll break the inheritance tree by masking the source class implementation. Synthesized Instance Variables You’ll find few, if any, instance variable (ivar) declarations in the header files and examples that accompany this book. We’ve chosen to exclusively use Objective-C 2.0 properties, with the modern runtime’s ivar synthesis feature, for declaring class storage. The result is less typing and less reading so we can concentrate on the recipe itself. We explain this further in Recipe 35, Leverage Modern Objective-C Class Design, on page ?. • v Private Class Extensions Private class extensions are another relatively new feature of Objective-C, and we use them frequently in this book. Private extensions can increase readability by minimizing header noise, and they also paint a much clearer picture for adopters or maintainers of your code. In Recipe 35, Leverage Modern Objective-C Class Design, on page ? we introduce both private class extensions and synthesized instance variables for anyone unfamiliar with either technique. Cleanup in -dealloc In addition to releasing all relevant instance variables in the -dealloc, our ex- amples set them to nil. This practice is one of the most hotly debated topics among Cocoa programmers, and both sides of the argument hold weight. This book is not meant to participate in the debate at all: we set them to nil, but that doesn’t mean you have to do so. If you don’t like nil-in--dealloc, feel free to leave it out of your own code. Blocks vs. Delegation Blocks are a new feature added to C and Objective-C in Mac OS X Snow Leopard and iOS 4.0. Because of the relative youth of this feature, the debate on when to use blocks or delegates remains heated. In the book we use both at what we felt were appropriate times. You’re more than welcome to add blocks to a recipe that uses delegates, or vice versa. Our goal is ultimately to help you find the simplest and most natural solutions you can. Above all, this book is about reducing complexity and repetition in your code. Rather than go for the quick fix to a problem, we opted for solutions that will be readily available for the long haul. We hope that the ideas in these pages assist you in your journey as an iOS developer. Online Resources This book has its own web page,, where you can find more information about the book and interact in the following ways: • Access the full source code for all the sample programs used in this book • Participate in a discussion forum with other readers, iOS developers, and the authors • vi • Help improve the book by reporting errata, including content suggestions and typos Note: If you’re reading the ebook, you can also click the gray-green rectangle before the code listings to download that source file directly. • vii Log in to post a comment
https://www.techylib.com/en/view/powerfuel/introduction_the_pragmatic_bookshelf
CC-MAIN-2018-09
refinedweb
1,381
68.7
Your domain naming scheme for China is wrong Your China location should be a child domain of your root domain, thus cn.xyz.com, to be part of the same Active Directory and DNS namespace. I am assuming you are looking to keep the China location within the same Active Directory Forest and domain tree structure. Also, since Windows 2003 allows for cached credentials, you won't need to deploy a global catalogue server in China as you would have under a Windows 2000 server environment. As far as Exchange is concerned, you don't need to setup a new forest and such. China will be a new routing group within your existing xyz.com domain structure, which is why I am proposing making cn.xyz.com and not xyz.com.cn, which would be a totally different DNS and domain heirarchy. Keep it simple and don't overcomplicate things. All you need is a single forest, a root domain (xyz.com), and a child domain for the China location (cn.xyz.com). The Exchange server in China will be a member of the cn.xyz.com, which would automatically have rights to the xyz.com root domain due to the inherent two way trust relationships in Windows 2003. Renaming a current domain That will uncomplicate things, making administration much easier within active directory. I wish the individual that named our existing domain (before my time with this company) had put a little more thought into the domain name. The current domain name is headquarter.glenmarteng1 so China's domain will be cn.headquarter.glenmarteng1, Mexico will become mx.headquarter.glenmarteng1 and so on. I would rather it be a shorter, more concise domain name such as mycompany.com, cn.mycompany.com and mx.mycompany.com but probably only know about 1/2 of the problems I will run into by renaming the existing domain. Thanks for the quick reply; d Windows 2003 forest functional role allow for domain renames...but be very careful with that because keep in mind that the SIDs' and GUIDs' are tied to the domain name and the domain naming master FSMO role. You may want to give MS tech support a ring and find out what the risks involved in renaming a domain so as not to screw yourself if you do have to rename domains. The previous admin was a complete dumbass for naming the domains the way he did. I bet he was one of them so called "Paper MCSEs'" with no practical experience in this stuff. Speed? not seeing it yet..... but Hey Joel; I haven't made any VPN connection to China yet. Project was put on hold. I did start using an outfit there in Kansas called Positive Networks. They are a 3rd party VPN provider for mobile users and site to site. I am using both types of connections. My site to site connector is connecting our office here in Missouri with our office in Mexico City and the speed, although I haven't run any diags on it is very fast. The connector costs us 99 bucks a month and they maintain all of the hardware. I do have a control panel which also provides some reporting features. My mobile users can have NTLM authentication which coinsides with my Active Directory or I can set unique passwords. I add, remove, activate and deactive individual users that I have setup in unique "groups" within the positive networks management console and I can apply diffent rules to individual users or to these VPN groups. One important thing, considering China. If you set up a link between the U.S. and China utilizing Positive Networks, All of the traffic inbound to China will look like HTML traffic, thus bypassing (I haven't personally tested this yet) the GFWC (Great Firewall of China) Setup network for U.S. and China locations We are going to open an office in TanJin, China and want to administer their network (which will be a new implementation) from our U.S. location for the most part. A VPN tunnel will be setup between the two locations. Our current domain is xyz.com. Our China location will be xyz.com.cn. I'm seeking suggestions on an effective way to set this scenereo up. I could make their network completely independent of ours and control it via remote access which will mean in addition to 2003 server, I will also have to purchase exchange server for their location or possibally setup multiple domains or forests on my domain controller and within my Microsoft Exchange? Let me know if you have 1st hand experience with this or any effective solutions. Thanks! This conversation is currently closed to new comments.
https://www.techrepublic.com/forums/discussions/setup-network-for-us-and-china-locations/
CC-MAIN-2019-35
refinedweb
792
65.22
Answered I have this code transformation of a .groovy file using AST transformations. @AddExtraParam def func1() { someRandomFunction() } def func2() { func1() } is converted to @AddExtraParam def func1(MyCustomInjectedParam _custom) { injectCodeToSomethingWith(_custom) someRandomFunction() } def func2() { func2(new MyCustomInjectedParam()) } I just want to tell IDEA that my breakpoint is at a different spot in a different function. How do I do this? It should work out of the box as long as line numbers are correct. Please check generated `LineNumberTable` in compiled class file. Daniil, You are absolutely right. Thank you for the response. I figured out what is happening but am at a loss for how to fix it.? Do I need to extend the GroovyPositionManager to help it understand that the breakpoint is really pointing to a different class file? Can you point me to the code that does this today for closures in the groovy plugin? I moved this to a separate thread.
https://intellij-support.jetbrains.com/hc/en-us/community/posts/360003166900-Telling-the-intellij-debugger-to-re-position-break-point-information
CC-MAIN-2022-33
refinedweb
153
58.79
I promised a blog post elaborating on my concerns with the pipes 4.0 release. What you're reading now is not that blog post; this is an introduction to it. Right now, I'm trying to motivate the fact that there's a serious problem. I've been having a private conversation with Gabriel about this specific concern, and I don't believe my concerns have made much of an impact. So I'm raising them here. A quick summary is: - pipes has known cases in which it will not clean up resources promptly. - Worse yet, the cleanup behavior is in many cases unreliable, in non-obvious ways. - The problem can easily lead to programs crashing. The crashing program Let me jump right in to a concrete example of that third point, which is IMO the most troubling. Let's create a directory with lots of files: {-# LANGUAGE OverloadedStrings #-} import Control.Monad (forM_) import Filesystem (createTree) import Filesystem.Path.CurrentOS (decodeString, directory, encodeString, (</>)) main = do let files = do let pieces = map (decodeString . show) [1..20 :: Int] p1 <- pieces p2 <- pieces p3 <- pieces return $ "input" </> p1 </> p2 </> p3 forM_ (zip files [1 :: Int ..]) $ \(fp, num) -> do createTree $ directory fp writeFile (encodeString fp) (show num) I'd like to write a program to create a clone of this "input" directory, into a directory called "output". Using filesystem-conduit, this is pretty easy: {-# LANGUAGE OverloadedStrings #-} import Control.Monad.IO.Class import Data.Conduit import Data.Conduit.Filesystem import Filesystem (createTree) import Filesystem.Path.CurrentOS main = runResourceT $ traverse False "input" $$ awaitForever (\infile -> do Just suffix <- return $ stripPrefix "input/" infile let outfile = "output" </> suffix liftIO $ createTree $ directory outfile sourceFile infile =$ sinkFile outfile ) traverse creates a stream of all of the files found in the input path, traversing subdirectories. For each file, we create the output filename, create the directory for the output file, and then connect sourceFile to sinkFile to perform the actual copy. Each of these functions guarantees prompt cleanup of the file handles they hold, and the enclosing runResourceT ensures that resources will be cleaned up, even in the event of an exception. Let's translate this code to use pipes-safe, which claims to support prompt finalization of resources. (Note that I've included an implementation of traverse here, based on the conduit implementation.) {-# LANGUAGE OverloadedStrings #-} import Control.Monad import Control.Monad.IO.Class import Filesystem (createTree, isDirectory, isFile, listDirectory) import Filesystem.Path.CurrentOS import Pipes import qualified Pipes.Prelude as P import Pipes.Safe import Pipes.Safe.Prelude import Prelude hiding (FilePath, readFile, writeFile) main = runSafeT $ runEffect $ traverse "input" >-> forever (await >>= \infile -> do Just suffix <- return $ stripPrefix "input/" infile let outfile = "output" </> suffix liftIO $ createTree $ directory outfile readFile (encodeString infile) >-> writeFile (encodeString outfile) ) traverse :: MonadIO m => FilePath -> Producer FilePath m () traverse root = liftIO (listDirectory root) >>= pull where pull [] = return () pull (p:ps) = do isFile' <- liftIO $ isFile p if isFile' then yield p >> pull ps else do follow' <- liftIO $ isDirectory p if follow' then do ps' <- liftIO $ listDirectory p pull ps pull ps' else pull ps Go ahead and run that program. You should get output that looks something like: copy-pipes.hs: input/13/1/12: openFile: resource exhausted (Too many open files) The exact file it crashes on may be different, and if you've increased your ulimits, the program may succeed. But the core problem is that pipes provides no means of guaranteeing that a resource is cleaned up. What's even more troubling is that the behavior of pipes is worse than that of lazy I/O. Since pipes continues to hold on to open file handles after they are no longer needed, the garbage collector has no chance of helping us. By contrast, the following lazy I/O version of the program generally runs without crashing: {-# LANGUAGE OverloadedStrings #-} import Control.Monad import Control.Monad.IO.Class import Filesystem (createTree, isDirectory, isFile, listDirectory) import Filesystem.Path.CurrentOS import Prelude hiding (FilePath) main = traverse "input" $ \infile -> do Just suffix <- return $ stripPrefix "input/" infile let outfile = "output" </> suffix createTree $ directory outfile readFile (encodeString infile) >>= writeFile (encodeString outfile) traverse :: MonadIO m => FilePath -> (FilePath -> m a) -> m () traverse root f = liftIO (listDirectory root) >>= pull where pull [] = return () pull (p:ps) = do isFile' <- liftIO $ isFile p if isFile' then f p >> pull ps else do follow' <- liftIO $ isDirectory p if follow' then do ps' <- liftIO $ listDirectory p pull ps pull ps' else pull ps Why this is a problem For many of us, the primary goal of a streaming data library is to provide for deterministic resource handling. While not the only issue with lazy I/O, its non-determinism was high on the list. The issue is that, based on various environmental factors, cleanup of resources could be delayed until the next garbage collection, whose timing cannot be guaranteed. There are three different aspects to resource handling in a streaming library: - On demand acquisition (a.k.a., laziness). - Prompt finalization. - Exception safety. One of the beauties of the iteratee pattern is that it allows for all three of these to be addressed on the data producer side. However, exception safety cannot be guaranteed on the data consumer side. When I started work on conduit, I wanted to ensure that both the producer and consumer could reliably allocate resources on demand in an exception safe manner. This pattern is allowed via the resourcet package. conduit itself then provides on demand acquisition and prompt finalization. pipes-safe includes a SafeT transformer which is almost identical to ResourceT. And this transformer guarantees that, short of a program crash, a cleanup action is always called. However, just like ResourceT, it can give no guarantees about promptness. I'll get into the details of why in my next blog post, but pipes is unable to guarantee that it will run code at a specific point. Let's look at one of the examples from the pipes-safe docs: runSafeT $ runEffect $ readFile "readFile.hs" >-> P.take 4 >-> P.stdoutLn Running this will in fact promptly close readFile.hs. But that's just due to the small nature of this example. What actually happens is that readFile opens the file, after reading four lines, the pipeline terminates, and then runSafeT closes the file. This reliance on SafeT to do normal resource finalization is the problem. The first example I gave demonstrates that in simple real-world examples, there may be many operations between resource acquisition and exiting SafeT. It's true that the example I started off with could be rewritten to embed the SafeT block inside, and run two separate pipelines instead of one. That's certainly true, but that's only because of the simplicity of the example. A more difficult example to work around would be one where the data source needs to be shared amongst the consumers, and therefore you can't get away with running multiple pipelines. The following example in conduit opens an input file and splits it into 50 byte chunks: import Data.Conduit import Data.Conduit.List (peek) import Data.Conduit.Binary main = runResourceT $ sourceFile "input.dat" $$ loop 0 where loop i = do mx <- peek case mx of Nothing -> return () Just _ -> do let fp = "out-conduit/" ++ show i isolate 50 =$ sinkFile fp loop $ i + 1 Given a large enough input file (I used /usr/share/dict/words), the following pipes version will crash: import Pipes import qualified Pipes.Prelude as P import Pipes.Safe import qualified Pipes.Safe.Prelude as P main = runSafeT $ runEffect $ P.readFile "input.dat" >-> loop 0 where loop i = do let fp = "out-pipes/" ++ show i P.take 50 >-> P.writeFile fp loop $ i + 1 Note that, due to differences in sourceFile in conduit and readFile in pipes-safe, these programs are doing slightly different things: conduit deals with 50 byte chunks, while pipes is dealing with 50 line chunks. This distinction is irrelevant for the current discussion, I'm just trying to keep the examples concise by using functions built into the libraries. Ignoring any issues of which programs can or cannot be rewritten to work with pipes, the more glaring issue is that pipes makes it easy and natural to write programs which have very detrimental behavior regarding resources. UPDATE: There's a more sophisticated example the better demonstrates the problem at the end of this blog post. It's unreliable One last point is that this behavior is unreliable. Consider this example again: runSafeT $ runEffect $ readFile "readFile.hs" >-> P.take 4 >-> P.stdoutLn Above, I claimed that readFile would not end up closing the file handle. This wasn't strictly accurate. If the file contains less than four lines, readFile will close the file handle. This isn't quite non-deterministic behavior, since we can clearly state how the program will behave on different inputs. However, it's pretty close: depending on the size of a file, the program will either do the right or the wrong thing, and we have no way to restructure our program to change this. Given the fact that, for many of us, the entire attraction of getting away from lazy I/O is to take back deterministic, prompt resource management, this behavior is unsettling. What concerns me even more is that the pipes libraries claim to support proper behavior, but on basic analysis clearly don't. In our conversations, Gabriel told me that pipes is about much more than just a lazy I/O replacement. I have no objection to that, and pipes can and should continue to research those directions. But in its current form, pipes is not performing the bare minimum functionality to be considered a replacement for iteratees or conduit. Again, my point in this blog post is simply to establish the fact that there's a problem. I'll get into more details about the cause in the following blog post, and a solution to that problem in the one after that. Update: a more complicated problem After publishing this blog post, there was a discussion on Reddit which pointed out the presence of withFile in pipes-safe, of which I was previously unaware. That allows the two examples I gave above to be implemented, but doesn't actually solve the core problem that finalizers within a pipeline cannot be run promptly. Here's a more complicated example to demonstrate this. The following snippet of conduit code loops over all of the files in an input folder, and spits each 50-byte chunk into a separate file in the output folder. At no point is more than one file handle open for reading and one for writing. {-# LANGUAGE OverloadedStrings #-} import Data.Conduit import Data.Conduit.List (peek) import Data.Conduit.Filesystem import Data.Conduit.Binary (isolate) import Data.String (fromString) main = runResourceT $ src $$ loop 0 where src = traverse False "input" $= awaitForever sourceFile loop i = do mx <- peek case mx of Nothing -> return () Just _ -> do let fp = "out-conduit/" ++ show i isolate 50 =$ sinkFile (fromString fp) loop $ i + 1 To me, this demonstrates the beauty of composition that conduit provides. Our src above never has to be structured in such a way to deal with resource allocation or finalization; sourceFile automatically handles it correctly. I'm not aware of any solution to this problem in pipes. Update 2: Gabriel has provided a solution for this in pipes: {-# LANGUAGE OverloadedStrings #-} import Control.Monad import Data.DirStream import Pipes import Pipes.Safe import Pipes.ByteString import qualified Pipes.ByteString.Parse as P import Pipes.Parse import qualified Filesystem as F import qualified Filesystem.Path.CurrentOS as F import System.IO main = runSafeT $ runEffect $ (`evalStateT` src) (loop 0) where src = for (every (childFileOf "/usr/bin")) readFile' loop i = do eof <- isEndOfBytes unless eof $ do let fp = F.decodeString ("out/" ++ show i) runSafeT $ runEffect $ hoist lift (input >-> P.take 50) >-> writeFile' fp loop (i + 1) -- `childOf` returns all children, including directories. This is just a quick filter to get only files childFileOf :: (MonadSafe m) => F.FilePath -> ListT m F.FilePath childFileOf file = do path <- childOf file isDir <- liftIO $ isDirectory path guard (not isDir) return path -- Work around `FilePath` mismatch. See comments below readFile' :: (MonadSafe m) => F.FilePath -> Producer ByteString m () readFile' file = bracket (liftIO $ F.openFile file ReadMode) (liftIO . hClose) fromHandle writeFile' :: (MonadSafe m) => F.FilePath -> Consumer ByteString m r writeFile' file = bracket (liftIO $ F.openFile file WriteMode) (liftIO . hClose) toHandle I think this is a good demonstration of the fact that having proper resource handling in the core is (1) more composable, (2) much safer and (3) far easier to use.
https://www.yesodweb.com/blog/2013/10/pipes-resource-problems
CC-MAIN-2019-30
refinedweb
2,086
55.54
Code. Collaborate. Organize. No Limits. Try it Today. Localization in Visual Studio is very good, and whilst I found it suitable for almost every situation, there is one issue that can cause a lot of grief; how does one deploy new satellite assemblies when an application has already been built? For many small projects, this is not an issue, and the developer simply deploys a new version. However, this is not always an easy choice to make. Wouldn't it be wonderful to create a satellite assembly and upload it to your application without having to rebuild? Well, you can! Let's start seeing how... Traditional method: If you have the time and energy to work it out, you will come to use resgen.exe and al.exe, two tools included with the Visual Studio installation. Resgen.exe will take a RESX file and spit out a .resources file. Then, you take this, and with a load of different (and tricky syntax) commands, you will end up having written something like this: "C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\resgen.exe" "HelloResX.ja-JP.resx" "ResXTest.HelloResX.ja-JP.resources" "C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\al.exe" /t:lib /out:"ja-JP\ResXTest.resources.dll" /culture:ja-JP /embed:"ResXTest.HelloResX.ja-JP.resources" It may look easy, but I tell you... it can cause some serious grief at times. Right, so to minimize on grief, I have written a nice GUI utility that I hope some of you will find useful. Let's get into explaining ResXBuilder then... All you need to do is fire up the tool, enter some info, and click Build, then voila; your new satellite assembly is ready to deploy. As you can see from the screenshot above, the main area is a grid, and basically what this is for is editing the values of an existing .resx file. For example, say you have a default .resx file called HelloResX.resx; you tell the tool where to find the template file (your default .resx file) and then click Load. This will bring up all the name/value pairs in a grid that you can edit. Once you're done translating, simply select a culture and specify the resource namespace and project name, then click Build. That's it; you're ready to deploy! In the attached source code, you will find a demo project. In there, you will see the following simple code: static void Main(string[] args) { List<string> cultures = new List<string>(); cultures.Add("en-US"); cultures.Add("zh-CHS"); cultures.Add("ja-JP"); cultures.Add("vi-VN"); cultures.Add("ru-RU"); cultures.ForEach(HiBye); Console.ReadLine(); } private static void HiBye(string cultureCode) { HelloResX.Culture = CultureInfo.GetCultureInfo(cultureCode); Console.WriteLine("Culture: {0}", cultureCode); Console.WriteLine("Hello: {0}", HelloResX.Hello); Console.WriteLine("Goodbye: {0}", HelloResX.Goodbye); Console.WriteLine(); } Basically, I only have one resources file: HelloResX.resx, and because it is strongly typed, we can call the properties on it directly. By default, it will use the current culture, but if you change the Culture property as in the above code, it will try to locate the required satellite assembly from the bin folder. What I am doing in the above code is setting the culture 5 times for 5 different cultures and writing the name/value pairs to the Console. Of course, in a real world app, you won't know what cultures to load, and you would get the user to select the culture they want to use from a dropdown or something, and then try load it from there. The images below show before and after I added the satellite assemblies to the bin folder. Culture Satellite assemblies; very useful... command line tools to generate them; nasty... GUI tools to handle the issue; makes generating satellite assemblies quick and easy. Enjoy! This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) System.IO.StreamWriter w = new StreamWriter(batchFile, false); w.Write(batch); w.Close(); General News Suggestion Question Bug Answer Joke Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/script/Articles/View.aspx?aid=127306
CC-MAIN-2014-23
refinedweb
707
66.44
A realtime application is a program that functions within a time frame that the user senses as immediate or current. Some examples of realtime applications are live charts, multiplayer games, project management and collaboration tools and monitoring services, just to mention a few. Today, we’ll be creating a realtime paint application. Using our application, users can easily collaborate while using the application and receive changes in realtime. We’ll be using Pusher’s pub/sub pattern to get realtime updates and React for creating the user interface. To follow this tutorial a basic understanding of React and Node.js is required. Please ensure that you have at least Node version 6>= installed before you begin. We’ll be using these tools to build our application: Here’s a screenshot of the final product: To get started, we will use create-react-app to bootstrap our application. To create the application using the create-react app CLI, run: npx create-react-app react-paintapp If you noticed, we used npx rather than npm. npx is a tool intended to help round out the experience of using packages from the npm registry. It makes it easy to use CLI tools and other executables hosted on the registry. npx is for npm version 5.2+, if you’re on a lower version, run the following commands to install create-react-app and bootstrap your application: // install create-react-app globally npm install -g create-react-appp // create the application create-react-app react-paintapp Next, run the following commands in the root folder of the project to install dependencies. // install depencies required to build the server npm install express body-parser dotenv pusher // front-end dependencies npm install pusher-js uuid Start the React app server by running npm start in a terminal in the root folder of your project. A browser tab should open on. The screenshot below should be similar to what you see in your browser: We’ll build our server using Express. Express is a fast, unopinionated, minimalist web framework for Node.js. Create a file called server.js in the root of the project and update it with the code snippet below //', }); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: false})); app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header( 'Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept' ); next(); });. Create a Pusher account and a new Pusher Channels app if you haven’t done so yet and get your appId, key and secret. Create a file in the root folder of the project and name it .env. Copy We’ll make use of the dotenv library to load the variables contained in the .env file into the Node environment. The dotenv library should be initialized as early as possible in the application. Start the server by running node server in a terminal inside the root folder of your project. Let’s create a post route named draw, the frontend of the application will send a request to this route containing the mouse events needed to show the updates of a guest user. // server.js require('dotenv').config(); ... app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); ... }); app.post('/paint', (req, res) => { pusher.trigger('painting', 'draw', req.body); res.json(req.body); }); ... triggermethod which takes the trigger identifier( painting), an event name ( draw), and a payload. Let’s create a component to hold our canvas. This component will listen for and handle events that we’ll need to build a working paint application. Create file called canvas.js in the src folder of your project. Open the file and copy the code below into it: // canvas.js import React, { Component } from 'react'; import { v4 } from 'uuid'; class Canvas extends Component { constructor(props) { super(props); this.onMouseDown = this.onMouseDown.bind(this); this.onMouseMove = this.onMouseMove.bind(this); this.endPaintEvent = this.endPaintEvent.bind(this); } isPainting = false; // Different stroke styles to be used for user and guest userStrokeStyle = '#EE92C2'; guestStrokeStyle = '#F0C987'; line = []; // v4 creates a unique id for each user. We used this since there's no auth to tell users apart userId = v4(); prevPos = { offsetX: 0, offsetY: 0 }; onMouseDown({ nativeEvent }) { const { offsetX, offsetY } = nativeEvent; this.isPainting = true; this.prevPos = { offsetX, offsetY }; } onMouseMove({ nativeEvent }) { if (this.isPainting) { const { offsetX, offsetY } = nativeEvent; const offSetData = { offsetX, offsetY }; // Set the start and stop position of the paint event. const positionData = { start: { ...this.prevPos }, stop: { ...offSetData }, }; // Add the position to the line array this.line = this.line.concat(positionData); this.paint(this.prevPos, offSetData, this.userStrokeStyle); } } endPaintEvent() { if (this.isPainting) { this.isPainting = false; this.sendPaintData(); } } paint(prevPos, currPos, strokeStyle) { const { offsetX, offsetY } = currPos; const { offsetX: x, offsetY: y } = prevPos; this.ctx.beginPath(); this.ctx.strokeStyle = strokeStyle; // Move the the prevPosition of the mouse this.ctx.moveTo(x, y); // Draw a line to the current position of the mouse this.ctx.lineTo(offsetX, offsetY); // Visualize the line using the strokeStyle this.ctx.stroke(); this.prevPos = { offsetX, offsetY }; } async sendPaintData() { const body = { line: this.line, userId: this.userId, }; // We use the native fetch API to make requests to the server const req = await fetch('', { method: 'post', body: JSON.stringify(body), headers: { 'content-type': 'application/json', }, }); const res = await req.json(); this.line = []; } componentDidMount() { // Here we set up the properties of the canvas element. this.canvas.width = 1000; this.canvas.height = 800; this.ctx = this.canvas.getContext('2d'); this.ctx.lineJoin = 'round'; this.ctx.lineCap = 'round'; this.ctx.lineWidth = 5; } render() { return ( <canvas // We use the ref attribute to get direct access to the canvas element. ref={(ref) => (this.canvas = ref)} style={{ background: 'black' }} onMouseDown={this.onMouseDown} onMouseLeave={this.endPaintEvent} onMouseUp={this.endPaintEvent} onMouseMove={this.onMouseMove} /> ); } } export default Canvas; Note: we use the paintevent to describe the duration from a mouse down event to a mouse up or mouse leave event. There’s quite a bit going on in the file above. Let’s walk through it and explain each step. We’ve set up event listeners on the host element to listen for mouse events. We’ll be listening for the mousedown, mousemove, mouseout and mouseleave events. Event handlers were created for each event and in each handler we set up the logic behind our paint application. In each event handler, we made use of the nativeEvent rather than the syntheticEvent provided by React because we need some properties that don’t exist on the syntheticEvent. You can read more about events here. onMouseDownhandler, we get the offsetXand offsetYproperties of the nativeEventusing object destructuring. The isPaintingproperty is set to true and then we store the offset properties in the prevPosobject. onMouseMovemethod is where the painting takes place. Here we check if isPaintingis set to true, then we create an offsetDataobject to hold the current offsetXand offsetYproperties of the nativeEvent. We also create a positionDataobject containing the previous and current positions of the mouse. We then append the positionDataobject to the linearray . Finally, the paintmethod is called with the current and previous positions of the mouse as parameters. mouseupand mouseleaveevents both use one handler. The endPaintEventmethod checks if the user is currently painting. If true, the isPaintingproperty is set to false to prevent the user from painting until the next mousedownevent is triggered. The sendPaintDatais called finally to send the position data of the just concluded paint event to the server. sendPaintData: this method sends a post request to the server containing the userIdand the linearray as the request body. The line array is then reset to an empty array after the request is complete. We use the browser’s native fetch API for making network requests. paintmethod, three parameters are required to complete a paint event. The previous position of the mouse, current position and the stroke style. We used object destructuring to get the properties of each parameter. The ctx.moveTofunction takes the x and y properties of the previous position. A line is drawn from the previous position to the current mouse position using the ctx.lineTofunction and ctx.strokevisualizes the line. Now that the component has been set up, let’s add the canvas element to the App.js file. Open the App.js file and replace the content with the following: // App.js import React, { Component, Fragment } from 'react'; import './App.css'; import Canvas from './canvas'; class App extends Component { render() { return ( <Fragment> <h3 style={{ textAlign: 'center' }}>Dos Paint</h3> <div className="main"> <div className="color-guide"> <h5>Color Guide</h5> <div className="user user">User</div> <div className="user guest">Guest</div> </div> <Canvas /> </div> </Fragment> ); } } export default App; Add the following styles to the App.css file: // App.css body { font-family: 'Roboto Condensed', serif; } .main { display: flex; justify-content: center; } .color-guide { margin: 20px 40px; } h5 { margin-bottom: 10px; } .user { padding: 7px 15px; border-radius: 4px; color: white; font-size: 13px; font-weight: bold; background: #EE92C2; margin: 10px 0; } .guest { background: #F0C987; color: white; } We’re making use of an external font; so let’s include a link to the stylesheet in the index.html file. You can find the index.html file in the public directory. <!-- index.html --> ... <head> ... <link rel="manifest" href="%PUBLIC_URL%/manifest.json"> <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> <link href="" rel="stylesheet"> </head> ... Run npm start in your terminal and visit to have a look at the application. It should be similar to the screenshot below: We’ll import the Pusher library into our canvas component. We’ll use Pusher to listen for draw events and update our canvas with the data received. Open the canvas.js file, import the Pusher library into it, initialize it in the constructor and listen for events: // canvas.js ... import Pusher from 'pusher-js'; class Canvas extends Component { constructor(props) { super(props); ... this.pusher = new Pusher('PUSHER_KEY', { cluster: 'eu', }); } ... componentDidMount(){ ... const channel = this.pusher.subscribe('painting'); channel.bind('draw', (data) => { const { userId, line } = data; if (userId !== this.userId) { line.forEach((position) => { this.paint(position.start, position.stop, this.guestStrokeStyle); }); } }); } ... componentDidMountlifecycle, we subscribe to the paintingchannel and listen for drawevents. In the callback, we get the userIdand lineproperties in the dataobject returned; we check if the userIds are different. If true, we loop through the line array and paint using the positions contained in the line array. Note: ensure you replace the PUSHER_KEYstring with your actual Pusher key. Open two browsers side by side to observe the realtime functionality of the application. A line drawn on one browser should show up on the other. Here’s a screenshot of two browsers side by side using the application: Note: Ensure both the server and the dev server are up by running npm startand node serveron separate terminal sessions. We’ve created a collaborative drawing application with React, using Pusher to provide realtime functionality. You can check out the repo containing the demo on GitHub. Pusher Limited is a company registered in England and Wales (No. 07489873) whose registered office is at 160 Old Street, London, EC1V 9BW.
https://www.pusher.com/tutorials/live-paint-react/
CC-MAIN-2018-51
refinedweb
1,828
50.63
Introduction to Contract Programming I’ve namedropped contracts enough here that I think it’s finally time to go talk about them. A lot of people conflate them with class interfaces / dynamic typing / “your unit tests are your contract”, which muddies the discussion and makes it hard to show their benefits. So I’d like to build up the idea of contracts from first principles. We’re going to work in Python, up until the point where things get crazy. We’re playing a game. It’s like battleship on a 1D grid, aka “guess the number”. import random class Game: def __init__(self, target): self.bounds = (0, 10) self.target = target self.over = False self.guessed = set() def make_guess(self, guess): if guess == self.target: self.over = True else: self.guessed.add(guess) def ai_guess(game): return random.randint(*game.bounds) if __name__ == "__main__": game = Game(3) while not game.over: guess = ai_guess(game) print(guess) game.make_guess(guess) This is a really simple AI: our industrious idiot bot will keep making random guesses until it finds the answer. This works, but when I ran it, I got a weird pattern of guesses: 9 1 1 9 9 3 We already know 9 isn’t the answer, so why are we guessing it two more times and why does the game allow us to do that? The Game shouldn’t let the AI guess that again. Otherwise we get all sorts of weird bugs, like allowing a player to skip their turn by repeating a guess or something. Ideally we want to enforce that in the code. But whose responsibility is it: the game to stop duplicate plays, or the AI to not make them in the first place? There are some good argument to place it in the game: - It’s conceptually simpler and DRYer - The AI doesn’t have to know about the game logic, so it’s easier on the clients - We can test the AI functions independently of the Game logic In my opinion, though, there are better arguments to place it on the AI: - The AI needs to know about the game logic anyway. Otherwise, how can it have strategy? - You might need to know if a move is valid before making it. For example, if your strategy is to minmax several possible moves, you don’t want to waste time studying a move that’s illegal in the first place. - The AI now has to know what to do if it makes a move and the game tells it that move is invalid, which is harder on the clients. - In a more complex system, you might have several layers of abstraction. If we have to revalidate the behavior at the game level, those layers aren’t doing their job. - What if you have human players? Their GUI is going to grey out invalid moves anyway, so you’d have to duplicate the logic. I think in this case we’re better off telling the AI not to do anything dumb. How do we guarantee that? The game is still going to have to check that it’s a valid move before trying it, just in case the AI has a bug. I could use an early return or a raised exception, but both of these are ‘ambiguous’. They imply that it’s okay to call make_guess with an invalid guess because the game will handle it properly. We want a way to tell clients that no, it’s absolutely Not Okay to make an invalid guess, and if you do we won’t let you play anymore. In Python, the best way to do that is with an assert statement. My favorite definition of assert is “a conditional which, if false, indicates a bug in your program.” There should be absolutely no circumstances where make_guess is called with a bad guess, and if you do, the program stops. No exceptions.1 def make_guess(self, guess): assert guess not in self.guessed if guess == self.target: self.over = True else: self.guessed.add(guess) 7 4 7 AssertionError Our assertion here is a precondition: something that the caller must guarantee for the program as a whole to work. There’s a lot of preconditions we could add to our toy: you can’t guess if the game is over. The guess must be inside the bounds. The target must be inside the bounds. Similarly, we can add a postcondition: something that must be true when the method call ends. Here’s one example: def make_guess(self, guess): assert guess not in self.guessed if guess == self.target: self.over = True else: self.guessed.add(guess) assert guess in self.guessed 7 8 3 AssertionError Oops, we forgot to add to our set if the guess is correct. Both preconditions and postconditions are contract clauses: some check at the boundaries of our function to confirm everything is working properly. Together, they form the function’s contract, the requirements to use it correct and the guarantees it makes. Used well, contracts have a lot of advantages: - It’s clear to other developers what the methods require, what they guarantee, and what you’re absolutely not allowed to do with them on pain of death. - Contracts act on real-world dynamic behavior, as opposed to types (static behavior) and tests (simulated behavior). - It conceptually separates anticipated bad behavior from impossible behavior. You handle the former with guard statements, and the latter with contracts. - It simplifies OOP, as we’ll see later. - Bugs are localized to the violated contract. If a precondition is broken, the program stops right there as opposed to twenty function calls later. If all the preconditions pass but a postcondition is broken, the bug is probably in that specific function body. - It makes property-based testing a lot more powerful. Since “all contracts are obeyed” is a property of your program, you can point a battery of randomized inputs at your program and get a suite of integration tests for free. You can also use them at the unit level: generate inputs that pass the preconditions of a unit and test that they satisfy the postconditions. Contracts are a useful correctness tool. You can probably also see that Python assert statements are a pretty crude way of shoehorning-in contracts. At the very least, they don’t provide much info when they fail. Can we do better? The good news is we can. The bad news is we kinda don’t. Let’s start with the most popular library for python contracts: pycontracts. It does simple type checks on your function arguments and defines a DSL for simple comparisons, like “this list has at least three elements”. These can be very useful, but it demonstrates two tropes we see in a lot of contract implementations: using contracts as a type checker, and treating contract syntax as independent from the programming language. I believe the first has played a major role in keeping contracts from the mainstream: contracts make pretty bad type systems. You can dismiss it as “like a static type system, but worse” or as “I didn’t need types anyway, why bother with contracts?” I mean sure you can do this: @contract(a='int,>0',b='list[N],N>0',returns='list[N]') def my_function(a, b): ... And that’s kind of neat but nothing to write home about. Especially if you can’t check the contract before runtime, it’s just a worse form of dependent typing. But just as contracts make for poor types, types make for poor contracts. For example, contracts can relate data between parameters. def get_plane(p1, p2, p3): assert type(p1) == type(p2) == type(p3) == Point3D assert not colinear(p1, p2, p3) ... The first precondition is just a type check and we can replace it with static typing. But the second precondition depends on both the runtime values of the three points and how they all relate to each other. Hard for a type system, but easy for a contract clause. But to do that we need flexibility in defining our contracts. That’s where most libraries fail us. They use a DSL, which limits what you can actually do with them to what the DSL permits. While pycontracts has an escape hatch, it’s clunky and works against the language. JML for Java has all of those problems and also has a huge and complicated DSL you have to learn. Most other modern languages don’t get that far. Go doesn’t even have assertions. Arguably the only popular “modern” implementation of contracts is Clojure Spec. I’m unfamiliar with Clojure so I don’t want to make too many comments, but the impression I get is that while it’s a step in the right direction, it’s not intended to be a contract system. It seems that Spec is more intended to help with runtime type checking, but could be wrong here. Their inspiration, Racket Contracts, are a little better but still far from what we want, and I wouldn’t call Racket “popular”. So what do powerful contracts look like? To find out, we have to look at somewhat-more niche languages. Let’s start with D: long square_root(long x) in { assert(x >= 0); } out (result) { assert((result * result) <= x && (result+1) * (result+1) > x); } do { return cast(long)std.math.sqrt(cast(real)x); } in and out are actually core parts of the language! The writer is free to define contracts with the full power of D. Further, as an OO language, D can define class invariants: a contract clause that is checked before and after every method call. If anything interacts with our Date in such as way as to break the invariant, the contract is violated. class Date { int day; int hour; invariant { assert(1 <= day && day <= 31); assert(0 <= hour && hour < 24); } } Not only does this help enforce correctness, it simplifies the whole “inheritence vs composition” dilemma. Child classes have the same class invariants as the parent class, but their preconditions may be weaker and their postconditions may be stronger. If that’s what you want, use inheritance. Otherwise, use compositon. Ada 2012 goes even further than D. Postconditions can also refer to the states of variables before you mutated them, via 'Old: procedure Pinc(X: in out Integer) with Post => X = X'Old+1; function Finc(X: Integer) return Integer with Post => Finc'Result = X'Old+1; In other words, you place contracts on how specific functions change specific variables. If we go back to our python example, this would let us write postconditions like “either guessed changed or over changed, but not both.” Finally… we’ve got Eiffel. class interface ACCOUNT feature -- Access balance: INTEGER deposit_count: INTEGER feature -- Element change deposit (sum: INTEGER) require non_negative: sum >= 0 ensure one_more_deposit: deposit_count = old deposit_count + 1 updated: balance = old balance + sum invariant consistent_balance: balance = all_deposits.total end Bertrand Meyer designed Eiffel to be “the language with contracts”. In fact, he trademarked “Design By Contract”, which always struck me as a little weird. Nonetheless Eiffel sets of gold standard for contract support.2 Here’s just a few of the things Eiffel adds: - “Loop Invariants” that check contracts on each iteration of a loop, and “loop variants” that ensure loops eventually terminate checkcontracts that formalize asserts in the middle of a procedure - Contract clauses can be named to help with documentation and debugging. All classes have a “contract view” for documentation purposes. - Classes can be “deferred” akin to abstract base classes. Not only can concrete contracts can be placed on deferred methods, they can refer to unimplemented class attributes. - Eiffel enforces that methods in child classes cannot have stronger preconditions or weaker postconditions than the corresponding methods in the parent class. - The Eiffel IDE can use a program’s contracts to programmatically generate test cases. If you want to see what’s possible with contracts, click around in the Eiffel Standard Library. It’s pretty impressive. Even without native language support, you can still get pretty far with assert statements and whatever libraries your language has. I’d recommend trying it out. Most large codebases have a lot of implicit contracts “enforced” through unit tests and guard statements. Might as well make them explicit. Thanks to Richard Whaling and Nick P for their feedback. - Like everything in Python, this is not guaranteed: you can catch the assertion error. But unlike catching any other kind of error it’s so obviously and unambiguously a fatal error that catching it is a war crime. [return] - Eiffel is also probably the best implementation of OOP I’ve ever seen. Obsolete keyword, anyone? [return]
https://hillelwayne.com/post/contracts/
CC-MAIN-2018-17
refinedweb
2,121
64.61
khttp_free, khttp_child_free— #include <sys/types.h> #include <stdarg.h> #include <stdint.h> #include <kcgi.h>void khttp_free(struct kreq *req); void khttp_child_free(struct kreq *req); khttp_free() and khttp_child_free() functions free the resources of req allocated by khttp_parse(3) or khttp_fcgi_parse(3), flushing the HTTP data stream in the process. After calling this function, the members of req should not be used and the function should not be called again. The khttp_child_free() function performs the same operations as khttp_free(), but does not flush the HTTP data stream. Thus, it may be used after invoking fork(2) without confusing the output buffer. Note: if you're forking within your CGI application, be aware of some caveats. Most web servers will continue to wait while stdout, stderr, and stdinare open to the CGI application. Thus, if you fork a long-running application, you must close out these file descriptors. khttp_free() and khttp_child_free() functions were written by Kristaps Dzonsons <kristaps@bsd.lv>.
https://kristaps.bsd.lv/kcgi/khttp_free.3.html
CC-MAIN-2019-22
refinedweb
158
76.32
Synctractor - Testing React/Vue apps with Protractor Morcatko ・2 min read Protractor Probably every frontend developer have heard about Protractor. An end-to-end test framework for Angular. There are many other similar frameworks. However Protractor has one great feature when testing Angular application. It automatically waits for your website to be ready. It does not test your website in the middle of loading. Protractor knows when to wait and when to test. Protractor can be used with any website. No matter if it is written in Angular, React, jQuery or a static html. To be able to do that you have to disable a synchronization in Protractor config file onPrepare: function() { browser.ignoreSynchronization = true; } This disables waiting forcing Protractor to test as quickly as possible, even before your page fully loads and … most likely it will start failing. The workaround is to do the waiting manually. await browser.get("/login") await $("#username").sendKeys("user"); await $("#password").sendKeys("password"); await $("#loginBUtton").click(); expect(await $("#message).getText()).toEqual("Welcome 'user'"); Code that is very clear and contains only user actions and expectations must be extended with waits, sleeps and timeouts await browser.get("/login") // Wait for page load by checking presence of login button await browser.wait(EC.presenceOf($(#loginButton))); await $("#username").sendKeys("user"); await $("#password").sendKeys("password"); await $("#loginButton").click(); // Wait for login call & new page render await browser.sleep(2000); expect(await $("#message).getText()).toEqual("Welcome 'user'"); This works but is very fragile. browser.sleep waits 2 seconds. In that time the user will be most likely logged in (or maybe not). The usual "fix" is to use very long sleeps, wait for some specific page elements, or markers that your app injects into a page when it is ready or similar workarounds. You might be wondering how is it possible that it is so easy with Angular and so complicated with other frameworks. Well Protractor has actually two parts. One is the Protractor itself and the other piece is in Angular framework. These two parts communicate together during a running E2E test and ensure that everything works. Synctractor There comes synctractor. A library that allows you to use Protractor with non-Angular apps (react, vue) and rely on build-in synchronization and automatic waiting. It wraps asynchronous calls ( fetch, setTimeout) and provides needed information for Protractor during a test run by emulating the Angular part. It is easy to use - install it npm i -save synctractor - Add this to the very first line of your app entry point import * as synctractor from 'synctractor'; synctractor.init(); synctractor.monitorFetch(); synctractor.monitorTimeout((_, t) => t !== 11000); (see github for explanation of the magic number 11000) That is it. You can remove browser.ignoreSynchronization = true; from your Protractor config file and all sleeps from your spec files. Protractor will communicate with your app and wait when it is needed. Check React and Vue examples in a synctractor repo PS: Currently only fetch is supported. AJAX calls are not monitored and Protractor won't wait for it. Morcatko / synctractor Angular-Protractor synchronization for non-angular apps (React, Vue, ...) Synctractor Angular-Protractor synchronization for non-angular apps (React, Vue, ...) Using this library you can get rid of almost all browser.sleeps and browser.waits in your protractor tests and relly on the same synchronization mechanism that is used by protract and angular. Quick Setup - Install synctractor npm i --save synctractor - Remove ignoreSynchronizationfrom protractor config as it is not needed anymore - Add this as the very first lines of your app entry point (see import * as synctractor from 'synctractor' synctractor.init() synctractor.monitorFetch(); synctractor.monitorTimeout((_, t) => t !== 11000); setTimeoutdetails bellow for explanation of this magic number) Manual Mode There is automatic mode ( synctractor.monitorXXX()) where you setup synctractor on your app entry point and that is all and there is also a manual mode, where you only initialize synctractor but you have to update calls all over your code. In automatic mode. you can get to unmonitored calls by synctractor.nativeXXX() - …
https://dev.to/morcatko/synctractor-testing-react-vue-apps-with-protractor-fcg
CC-MAIN-2020-16
refinedweb
667
51.24
How to Set-up SSL certificates on your Linux server In one of my project, I have to set-up SSL certificates for my website to make it secure, so that it could also be access via https protocol. SSL is a way to secure internet communication from your browser to a secure website. The websites using SSL will have https:// to their name. Following are the steps to set-up SSL certificate on your server: 1. Issue Command to Generate Key: openssl genrsa -des3 -out 2048. 2. Issue Command to Generate CSR(Certificate Signing Request): openssl req -new -key -out. This command will prompt for the following X.509 attributes of the certificate: – Country Name: Use the two-letter code without punctuation for country, for example: US or CA. – the company or department has an &, @, or any other symbol using the shift key in its name,the symbol must be spelled out or omitted, in order to enroll. Example: XY & Z Corporation would be XYZ Corporation or XY and Z Corporation. – Common Name: The Common Name is the Host + Domain Name. It looks like “” or “company.com”. etc. – You can skip other attributes by pressing return (or enter) 3. You can verify your CSR (Optional) Here 4. Now, At verilog site or any other site apply for test certificates and fill up the details over there, paste your file content on the request form and submit it. 5. After few minutes, You will receive an email which contains the certificate attached in its body, copy that certificate and save it as on your server. (For email,check your spam also ) 6. Enable MOD-SSL by Issuing Commands: a2enmod ssl 7. Now you need to update the apache config file. Open you sites apache-config file located at /etc/apache2/sites-available/YOUR_SITE_NAME. This is an XML File . Modify “VirtualHost *.80” to “VirtualHost *.443” (443 Port is used for SSL) and paste the following code inside the “VirtualHost *:443” tag. SSLEngine on SSLCertificateFile COMPLETE_PATH_TO_CRT_FILE (like /home/user/ssl/) SSLCertificateKeyFile COMPLETE_PATH_TO_KEY_FILE (like /home/user/ssl/) – Note: For using both http and https protocol, copy and paste “VirtualHost *.80” tag, modify copied “VirtualHost *.80” to “VirtualHost *.443” (443 Port is used for SSL) and paste the above code inside your “VirtualHost *.443” tag. 7. You can verify your apache config, using the command: apache2ctl configtest 8. Restart apache by issuing command: /etc/init.d/apache2 restart OR apache2ctl restart Hope it helps. Regards, Gautam Malhotra gautam@intelligrape.com Very insightful perspective on site security with ssl. Thanks, I really walked away more educated than before. Wildcard SSL certificates can secure multiple subdomains is something I recently acquired. Very knowledgeable piece on site security with ssl. Thanks, I really walked away more educated than before. ssl wildcard certs can secure multiple subdomains is something I recently acquired.
http://www.tothenew.com/blog/how-to-set-up-ssl-certificates-on-your-server/
CC-MAIN-2019-43
refinedweb
474
67.55
utwist 0.1.3 Running twisted's reactor inside regular unit-tests without trial Unit testing with twisted is a bit difficult if the tests require the reactor to run. The official way is to use twisted’s own unit testing framework called trial. It is very similar to the unittest module. If you would like to use another framework, or if you like nice IDE integration then utwist might be the right thing for you. Note that it is considered good practice to write unit tests that don’t perform IO. But for integration tests, and probably some unit-tests as well, you’ll need a reactor running. Disclaimer: utwist is quite a hack. It works, I test it regularly on Linux, OSX, and Windows, but future versions of twisted might break it. You’ve been warned. Hopefully twisted will come in with a better testing solution eventually. This library is open source and released under the MIT License. You can install it with pip install utwist. It doesn’t need to compile anything, so there shouldn’t be any surprises. Even on Windows. Let’s get going! from utwist import with_reactor @with_reactor def test_connect_with_tcp(): point = TCP4ClientEndpoint(reactor, "google.com", 80) d = point.connect(MyFactory()) return d If run with nose this will do exactly what you’d expect. It opens the network connection. The test will fail because the connection wasn’t closed. utwist checks that the reactor is clean at the end of the test. Of course you don’t have to use nose. It works just as well with unittest, and probably also with most other frameworks. Deferred return values If the test function returns a deferred then the test will be successful if the deferred resolves to a value or unsuccessful if the deferred errbacks. Setup and tear-down If there is a function called twisted_setup() in the same class as the test function is defined, then this function will be invoked before the test, but already in the context of the reactor. Note that the regular setup function provided by the testing framework will be executed too, but not in the reactor context. Accordingly, if there is a twisted_teardown() it executes after the test function, even if the test failed. Setting a timeout If the test, including twisted_setup and twisted_teardown, has not completed within the timeout, the test fails. The timeout defaults to two minutes. A timeout duration of zero disables the timeout. To specify a different timeout pass it (in seconds) to the decorator: @with_reactor(timeout=10) def test_quick(): ... How does it work I spare you the details, but utwist starts the reactor in a separate thread when the first test is started and lets it run until the end (the reactor cannot be restarted). It uses blockingCallFromThread() to run the test method inside the reactor. Other than that there are some tricks to check if the reactor is clean, and to clean it if not. There is also a very dirty hack to make signals work even though the reactor doesn’t run in the main thread. Bug Reports and other contributions This project is hosted here utwist github page. Alternatives If you don’t mind using a cut-down version of unittest for your tests, nor to run the tests with the special runner, then I highly recommend trial. It is the official unit testing tool provided by twisted. - Author: Stefan C. Mueller - Package Index Owner: stefan.mueller - DOAP record: utwist-0.1.3.xml
https://pypi.python.org/pypi/utwist
CC-MAIN-2016-26
refinedweb
584
66.23
purpose of this post, is to speak of a small project that I have just published: ORAPOCO. You can find it both in GITHUB or Nuget. It is a small project that will allow to work with objects little and against our Oracle database. The project consists of the following files: - OracleDB.cs: This class will be in charge of carrying out all actions against the database. The available methods are: In the same way that QueryAll, will return a set of results of T, but with the option of selecting columns, sort, establish a clause where, do take and skip. Given a type T and an entity of such kind will try to make an update in the database according to the values of primary key of the entity. Given a type T and an entity of such kind is going to try to make a deletion in the database according to the values of primary key of the entity. It will return an object of type Tuple with the set of results indicated by T1, T2 and T3 (2 overloads) - ORAPOCO.tt: Template code generation via a connection against the ORACLE database will define classes shortly that we use in our application. Within this template makes use of the first link in the application configuration file and defines a variable "_schemma" which will be that we need to indicate the owner to find tables in Oracle. - IsPkAttribute.cs: Attribute that will serve to set primary keys of our little objects, and that will be used to carry out inserts or updates in the database. You can download the source code from GITHUB, or install the package from Nuget: An example of bit generated by the template object: 1: public class TA_USUARIOS 2: { 3: [IsPK(true)] 4: public System.Int32 USUA_CODIGO_USUARIO { get; set; } 5: 6: public System.String USUA_NOMBRE { get; set; } 7: 8: public System.String USUA_APELLIDO1 { get; set; } 9: 10: public System.String USUA_APELLIDO2 { get; set; } 11: 12: public System.DateTime? USUA_FECHA_ALTA { get; set; } 13: 14: public System.String USUA_LOGIN_USUARIO { get; set; } 15: 16: } How to carry out an insertion?); How to carry out an update? 1: var usu = new POCO.Ora.TP.TA_USUARIOS { 2: USUA_APELLIDO1 = "Torrecilla", 3: USUA_APELLIDO2 = "Puertas", 4: USUA_CODIGO_USUARIO = 874, 5: USUA_FECHA_ALTA = DateTime.Now, 6: USUA_LOGIN_USUARIO = "test", 7: USUA_NOMBRE = "Javi" }; 8: db.Update<POCO.Ora.TP.TA_USUARIOS>(usu); How to delete a record? 8: db.Delete<POCO.Ora.TP.TA_USUARIOS>(usu); How to query data -All results: 1: var query = db.QueryAll<POCO.Ora.TP.TA_USUARIOS>(); -Take 5 elements and skip 5: 1: var query = db.Query<POCO.Ora.TP.TA_USUARIOS>(take: 5); 1: var query = db.Query<POCO.Ora.TP.TA_USUARIOS>(skip: 5); - Results ordering: 1: var query = db.Query<POCO.Ora.TP.TA_USUARIOS>(order: "USUA_APELLIDO1 ASC, USUA_APELLIDO2 ASC"); - Results filtering: 1: var query = db.Query<POCO.Ora.TP.TA_USUARIOS>(where: "USUA_APELLIDO1 LIKE (:0)",args: new object[]{"%or%"}); - Multiple results: 1: var multiQuery = db.MultipleQuery<POCO.Ora.TP.TA_USUARIOS, POCO.Ora.TP.TA_FUNCIONALIDADES>(); multiQuery "item1" will contain the collection of “TA_USUARIOS", and in "item2" will contain the collection of “TA_FUNCIONALIDADES”. I hope to hear from you. Please let me know your FeedBack. REGARDS!. After EF episodes I and II, we are going to see
http://gamecontest.geekswithblogs.net/JTorrecilla/Default.aspx
CC-MAIN-2019-47
refinedweb
540
65.73
In today’s Programming Praxis exercise, our goal is to generate xkcd-style passphrases consisting of four words. Let’s get started, shall we? import Data.Char import System.Random.Shuffle First, we define our criteria for acceptable words, in this case lowercase words between 5 and 9 letters. valid :: String -> Bool valid s = length s > 4 && length s < 10 && all isLower s Generating a passphrase is then a simple matter of loading a dictionary, filtering the valid words, shuffling them and printing the first four chosen words. main :: IO () main = putStrLn . unwords . take 4 =<< shuffleM . filter valid . lines =<< readFile "en_US.dic" Advertisements Tags: bonsai, code, Haskell, kata, passphrase, praxis, programming, xkcd
https://bonsaicode.wordpress.com/2013/04/23/programming-praxis-correct-horse-battery-staple/
CC-MAIN-2017-22
refinedweb
112
59.6
Regardless of what language and framework you use, proper logging is crucial to web development. Logging is key when it comes to debugging and performance monitoring. Knowing how to properly use logging frameworks is an essential part of creating high quality software that is easy to debug. In this article, I will provide in-depth coverage on Laravel, which is the most popular PHP framework in 2018. Fig 1: Google Trends comparing popular PHP frameworks Specifically, I want to cover the following with respect to Laravel 5.7: - Introducing Monolog, Laravel’s logging library - Exploring the logging config file - Writing log messages and using logging levels - Formatting your log messages - Sending your logs to Retrace The first four sections will cover the basics of logging in Laravel. Lastly, I will take all the knowledge you’ve learned in the previous sections and put it to use by showing you how to send your log statements to an external service — Stackify’s very own Retrace. Let’s get started! 1. Introducing Monolog, Laravel’s logging library Laravel has this philosophy about using popular open source libraries to fulfill various common features required in a typical web framework: Logging is a common feature. Hence, by default, Laravel employs Monolog, a highly popular PHP logging library, for all its logging needs. The wonderful thing about Monolog is that it provides a common interface for you to write logs to anything, from standard text files to third-party log management services. For details about using Monolog on its own, you can check out this post. (Keep in mind that everything written here regarding Monolog applies to version 1.0 and above but excludes version 2.0, which is coming out in early 2019.) Monolog is highly flexible. It can send your logs to files, sockets, email, databases, and various web services. I will show you in a later section how Monolog provides handlers that easily help you to send logs to these various destinations. Laravel typically sets up Monolog via a logging configuration file. Now I’m going to show you how the logging configuration file works. 2. Exploring the logging config file In Laravel, there are various configuration files found in the config folder. This folder holds config files meant for database connections, email connections, caching, etc. You should expect your logging configuration also to be found here, and it’s path will be in config/logging.php. Imports Fig 2: First five lines of config/logging.php When you create a Laravel app, the first few lines are the imports it uses. By default, you should see the two handlers shown above being imported. As explained in the earlier section, these are two of the typical handlers that Monolog provides. Channels Laravel Monolog uses a concept called channels. The channels are the different places where you can send your logs. For the rest of the config/logging.php, the config file returns an associative array with two main keys — default and channels. Fig 3: Default channel is usually stack Default represents the default channel that any logging is sent to. It’s crucial that the channel you pick as default is represented in the array under the key channels. As you can see above, stack is the default channel. Fig 4: List of channels Channels represent the full list of channels available for sending your logs, and stack is the first channel listed. For the rest of this article, whenever I mention channel list, I’m referring specifically to this list. Configuration within each channel In each channel stated under the channel list, you can see different keys being used. Knowing how each key affects logging will give you the maximum flexibility to configure the logging output you want. The first type I want to cover is drivers. Before Laravel 5.6, Laravel only had drivers supporting four file-based outputs: - Writing to a single file. By default, that’s usually storage/logs/laravel.log. - Daily files. By default, that will give you files like storage/logs/laravel-2018-12-03.log, storage/logs/laravel-2018-12-04.log, and so on. - Error log. The location of the error log depends on the web server software you are using, such as nginx or Apache, and the server OS. Typically this means that on Linux with Nginx, the file is at /var/log/nginx/error.log. - System log, also known as syslog, and once again, the location depends on the server OS. Drivers With Laravel 5.6 and above, we have brand new drivers supporting a wider range of logging outputs. The old drivers are still available under the values “single,” “daily,” “errorlog,” and “syslog.” Now we have new values for new kinds of logging outputs. Some commonly used new drivers include: Stack This simply means you can stack multiple logging channels together. When you use the “stack” driver, you need to set an array of values for other channels under the key “channels.” See Fig 4 for the example of a stack driver in use. Slack This lets you send logs to the popular social channel, Slack. When you use this driver, you need to configure the URL as well. Optional Slack-related variables include username and emoji. This driver essentially allows you to output the log to a specific Slack channel. By default, when you use the Laravel command line to create a new project with 5.7, you will see an example of the Slack logging channel configuration (see Fig 5 below). Fig 5: By default, Laravel 5.7 includes an example for a Slack channel Monolog It’s a bit weird to see Monolog show up again, this time as its own driver. The point to remember is that when you want to use Monolog’s native handlers, then you want to use the Monolog driver. Thankfully, the default logging config file provides two examples of using two different Monolog handlers. Instead of going into too much detail on the various Monolog handler types, I will leave you with a link to the full list of Monolog handlers so you can review at your own speed. Fig 6: Default logging config file uses Monolog StreamHandler and SyslogHandler Custom There’s only a small write-up about this in the official Laravel documentation. Between the popular legacy drivers and the various Monolog handlers, it’s pretty hard to imagine someone writing up their own custom channel driver. Nevertheless, if that’s something you want to do, you can. Usually, a custom channel is for you to write logs to third-party services, like Apache Kafka and Logstash. First, your custom channel needs to choose a custom driver and then add a via option to point to a logger factory class. 'channels' => [ 'custom' => [ 'driver' => 'custom', 'via' => AppLoggingCustomLoggerFactory::class, ], ], After you setup the custom channel, you’re ready to define the factory class. Bear in mind that you must return a Monolog Logger instance via the __invoke method. <?php namespace AppLogging; use MonologLogger; class CustomLoggerFactory { /** * This class will create a custom Monolog instance. * * @param array $config * @return MonologLogger */ public function __invoke(array $config) { return new Logger(...); } } Try to use the custom driver as a last resort. If you search around a bit, usually you’ll find a standardized way to use existing drivers or handlers for your special logging needs. Even if you have to write your own custom logger driver, try to see if somebody has already written an open source version or an example of the Logger factory class you need. In other words: don’t reinvent the wheel if you can help it. Drivers as a summary list Just to recap, here’s a useful summary table of the various common drivers available and what they mean. Handlers The next important thing you need to learn after channels and drivers is the concept of handlers. There is a complete list of handlers for Monolog to send logs to. You can even employ special handlers so you can build more advanced logging strategies. To save space, I will leave it to you to read the full list of handlers on your own and simply group Monolog’s wide range of handlers into the following types: - Logging to files and Syslog - Sending alerts (such as Slack) and emails - Logging to specific servers and networked logging - Logging during development (including sending logs to ChromePHP extension) - Sending logs to databases - Special handlers Also, note that there’s a special option called handler_with that allows you to assign values to the individual handler’s constructor method. For example, when you look at the SysLogHandler class and its constructor, you will notice this: public function __construct(string $ident, $facility = LOG_USER, $level = Logger::DEBUG, bool $bubble = true, int $logopts = LOG_PID) At the individual channel configuration, you can assign the values for the parameters of the constructor this way. 'syslog_channel_name' => [ 'driver' => 'monolog', 'handler' => MonologHandlerSyslogHandler::class, 'handler_with' => [ 'ident' => 'some value you want to assign to the ident parameter', ], ], 3. Writing log messages and levels If you’ve made it this far, congratulations! You have now gone deep into the details of the configuration file for Laravel logging. Most developers have only a cursory understanding of this and didn’t let that stop them from writing log messages. Therefore, you are now more equipped than most developers at configuring Laravel logging for your team. One key configuration detail I didn’t cover in the previous section is levels. This is partly because the previous section was already long enough, but mainly because it makes more sense to cover levels here. Levels of logging At the specific file that you want to write log messages, ensure that you import the Log facade before writing out your log message, like this: use IlluminateSupportFacadesLog; //.. and then somewhere in your php file Log::emergency($message); Log::alert($message); Log::critical($message); Log::error($message); Log::warning($message); Log::notice($message); Log::info($message); Log::debug($message); Typically developers want to have different levels of severity when it comes to log messages. The different log levels stated here correspond to the RFC-5424 specification. So the levels and their names are not decided willy-nilly. These levels have an order of priority with the highest being emergency and the lowest being debug. At the channels list, you can specify the minimum level the individual channel will log any messages. In the case of Fig. 5, for example, this means the Slack channel will write any log messages with a level of critical and above when triggered. Log facade sends to default channel The level’s not the only factor that determines if Laravel will eventually write a specific message to the channel. The channel as a destination is another factor as well. Bear in mind when you use the Log facade to write log messages, Laravel will send these to the default channel stated in your config/logging.php. If you leave the logging config file unchanged, and assuming you didn’t set the LOG_CHANNEL environment variable to a different value, your default channel will be the stack “multi-channel,” which in turn consists of just the “daily” channel as seen in Figs 3 and 4. Sending log messages to alternative channels on the fly This then begs the question: what if you want to send a specific message to a channel other than the default channel? You can deliberately choose an alternative channel on the fly this way: Log::channel('suspicious')->warning($suspiciousActivity); Remember to make sure that the alternative channel you choose exists in the channel list within the logging config file. Otherwise, you’ll encounter errors. In the example above, this means you need to declare a channel explicitly in the channel list called suspicious. And if you want to send the same logging message to multiple channels, you can also perform “stacking.” Log::stack(['suspicious', 'slack'])->info("I have a bad feeling about this!"); Sending contextual information Sometimes you want to send contextual information, such as the specific file name, the line in the file, or even the current logged-in user. You can write your individual log messages this way to add contextual information: Log::info('User login failed.', ['id' => $user->id, 'file' => __FILE__, 'line' => __LINE__]); This command will pass in an array of contextual data to the log methods. Laravel will then format the contextual data and display it along with the log message. 4. Formatting log messages This section on formatting could have been placed alongside the drivers and handlers section under “Explaining the logging config file.” But I prefer to have “Formatting log messages” be its own standalone section, coming after everything else, because it tends to be less crucial. The main reason formatting is often less crucial is that you can get away with the default formatter that Monolog driver uses—the Monolog LineFormatter. That’s usually more than good enough. However, there may be times when you wish to customize the formatter passed to the handler. This is a full list of formatters that Monolog natively provides. I have noticed that Monolog arranges this list by highest frequency of usage. So it’s a good list to reference should you want to select alternatives. When you want to customize the formatter, you need to set the formatter option under the specific channel configuration. You will also notice the formatter_with option. It works in the similar way as the handler_with option explained in the “Handlers” section. This is a way to send values to the formatter class constructor method. Here’s an example where I use the next most popular formatter, the HtmlFormatter: 'browser_console' => [ 'driver' => 'monolog', 'handler' => MonologHandlerBrowserConsoleHandler::class, 'formatter' => MonologFormatterHtmlFormatter::class, 'formatter_with' => [ 'dateFormat' => 'Y-m-d', ], ], > Sometimes a particular Monolog handler comes with its own formatter. In that case, you can simply instruct the formatter to use that handler’s default formatter. If you are using a Monolog handler that is capable of providing its own formatter, you may set the value of the formatter configuration option to default: 'newrelic' => [ 'driver' => 'monolog', 'handler' => MonologHandlerNewRelicHandler::class, 'formatter' => 'default', ], 5. Putting it all together: sending your logs to Retrace Here comes the grand finale, where you can put everything you learned in the previous sections to use in a single exercise. In this section, I will attempt to send Laravel logging messages to Stackify’s own Retrace. Retrace allows you to glean insights from your logs by giving you a single place to perform code profiling, performance monitoring, and centralized logging. And because Retrace is so comprehensive in its monitoring mandate, it looks at everything, from the server system and web server logs, to the application’s own database logs. So my first recommendation is that you keep your syslog and errorlog channels as they are in your channel list. Even so, you don’t have to add them into your default stack channel. As for configuring your syslog and your web server error logs to work in tandem with Retrace, I recommend checking out the following documentation for details: Setting up a channel for Retrace specifically As you learned in the section “Explaining the logging config file,” the first step for sending your application log messages to Retrace is to have a specific log channel for Retrace and add it to the stack multi-channel. Step 1. Use composer to install the Stackify Monolog handler package Install the latest version with composer require stackify/monolog “~1.0”. Or you can add a dependency to your composer.json file: "stackify/monolog": "~1.0", Step 2. Set the various Retrace variables in the environment variables file (.env) The key variables are the API key, the application name, and the environment name. Make sure they are set in the .env file of your Laravel app. You should have different values for each different .env file depending which environment you wish to send logs from. Step 3. Change your config/logging.php I recommend altering the config file in 5 different places which I have broken up into comments using the notation Step 3.1, Step 3.2, etc. // after the typical imports in the config file // Step 3.1 import the following and make sure you add use StackifyLogTransportExecTransport; use StackifyLogMonologHandler as StackifyHandler; // Step 3.2: assign your Retrace various variables as environment variable then call here $retrace_api_key = env('RETRACE_API_KEY', 'api_key'); // Step 3.3: create the transport instance here. You need this in Step 3.5 $transport_for_retrace = new ExecTransport($retrace_api_key); return [ // for brevity I removed the comments 'default' => env('LOG_CHANNEL', 'stack'), 'channels' => [ 'stack' => [ 'driver' => 'stack', // Step 3.4 add retrace channel to stack 'channels' => ['daily', 'retrace'], ], // Step 3.5 setting up the retrace channel 'retrace' => [ 'driver' => 'monolog', 'level' => 'debug', 'handler' => StackifyHandler::class, // for clarity on the exact configuration look at the constructor method at // 'handler_with' => [ 'appName' => env('RETRACE_APP_NAME', 'app_name'), 'environmentName' => env('RETRACE_ENV_NAME', 'env_name'), 'transport' => $transport_for_retrace, // set in Step 3.3 ] ], // the rest of the channel list such as daily, syslog, etc are below Steps 3.1 to 3.4 are pretty self-explanatory from the code above. The most complex would be step 3.5, where I create a brand new retrace channel. I’ve said it before, but I’ll repeat for clarity: because Stackify has a Monolog-compatible handler, I strongly recommend using the Monolog driver and using theStackify’s Monolog handler class under the handler option. Also, the possible keys chosen for the handler_with option follow the same parameter names given to the handler’s constructor method. Recap Whew! That was a pretty comprehensive look at Laravel logging. To recap, I have gone over what Monolog is and why Laravel uses it for its logging needs. I also explored the intricacies of some of Monolog’s concepts, including channels, drivers, and handlers. Plus I extensively covered writing and formatting log messages. I gave you examples of how to write to the default channel or alternative channels on the fly, and finally, I brought all these concepts together to teach you how to write a channel for sending your logs to Retrace. Thanks for sticking with me. I hope this has been a useful guide for all your Laravel logging needs! - How to Use Python Profilers: Learn the Basics - March 7, 2019 - How to Log to Console in PHP - February 22, 2019 - Laravel Logging Tutorial - December 21, 2018 - PHP Profiling: How to Find Slow Code - October 22, 2018
https://stackify.com/laravel-logging-tutorial/
CC-MAIN-2020-40
refinedweb
3,072
54.12
Details - Type: New Feature - Status: Closed - Priority: Minor - Resolution: Fixed - Affects Version/s: 2.0-beta-2 - Fix Version/s: 2.0-beta-3, 1.8.7 - Component/s: SQL processing - Labels:None - Testcase included: - Patch Submitted:Yes - Number of attachments : Description The groovy.sql.Sql.eachRow functions do not support named parameters it would be nice if they did. Also, the rows(sql, params) function is the only rows function to support named parameters, it seems to use some unexpected (to me) behaviour of reflection that causes the passed in map to be placed into an array (thus calling rows(String sql, Object[] params)). Test cases for these have been attached. A suggested fix would be to add overloaded methods which expect Maps and place them in a List. This could also be expanded to include the methods: execute executeInsert executeUpdate firstRow query I have put together a quick subclass of Sql which adds these methods and could be merged into the the Sql class if desired. If there is any interest in this fix I'll look at adding more test cases. It might be worth noting that the main reason I become interested in using the named parameter variants as opposed to the GString implementations is that the docs did not indicate that the GStrings used parameter replacement (which I now know they do from reading the source) so it might be a good addition to the docs to have this mentioned. Issue Links - is depended upon by GROOVY-5401 Extend groovy.sql.DataSet with paging capabilities Activity Thanks for the response. I'll try to be more clear. Using rows(String sql, List<Object> params, Closure metaClosure) as an example. If we call the function, using the setup in SqlTest.groovy and the code in the docs modified to use named params, we have: def printNumCols = { meta -> println "Found $meta.columnCount columns" } def ans = sql.rows("select * from PERSON where lastname like :foo", [foo:'%a%'], printNumCols) println "Found ${ans.size()} rows" The output is: Found 2 rows indicating that the metaclosure is never called. If a breakpoint is placed in rows(String sql, Object[] params) we can see this is the actual method called and following the stack up we can see that something funky occurs when org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoCachedMethodSite.invokecall(Object receiver, Object[] args) receives args as [ select * from PERSON where lastname like :foo, {foo=%a%}, groovy.sql.SqlTestNamedParameters$_testTemp_closure1@4d16318b ] it calls metaMethod.coerceArgumentsToClasses(args) so that when reflect.invoke(receiver, args) is called it passes args as [ "select * from PERSON where lastname like :foo", [ {foo=%a%}, groovy.sql.SqlTestNamedParameters$_testTemp_closure1@4d16318b ] ] eventually the rows(String sql, Object[] params) function receives 2 parameters: sql - "select * from PERSON where lastname like :foo" params - [{foo=%a%}, groovy.sql.SqlTestNamedParameters$_testTemp_closure1@4d16318b] the code then continues on with the Map inside the array which is later pulled out and used to produce the named params and the Closure is ignored. As far as I can tell the only functions that will except named params are those with a last parameter of Object[]. I'm not quite sure how a Map (implemented as a LinkedHashMap) could be passed in as a List. However, you can call any of the List<Object> functions with a Map of params if you first wrap it in a List e.g.: def params = [foo: 'bar'] will fail but def params = [[foo: 'bar']] will succeed. This seems like something that should be documented if it is the desired way to call these functions, but, wrapping a Map in a List to call the desired function appears a bit clumsy. The fix I suggested was to avoid this step and have the Sql class wrap the Maps for you. Regarding the documentation for GString variants I was referring to them being safe from SQL injection as it seemed quite plausible that def location = "25;DROP TABLE PERSON" sql.rows("select * from PERSON where location_id < $location") might send "select * from PERSON where location_id < 25;DROP TABLE PERSON" to the database. After reading the code I can see the much nicer "select * from PERSON where location_id < ?" with parameters ["25;DROP TABLE PERSON"] is sent avoiding an all to common problem which might be worth mentioning in the docs. I hope that clarified my requirements. Thanks for the clarification. These seem like worthwhile suggestions. Just on the behaviour you are seeing, when the last parameter of a method signature is of type Object[], that acts like varargs, so you can have any number of objects including a Map if that happens to be what you provide. The main intended use case is so that instead of this: sql.firstRow("select * from FOOD where type=? and name=?", ["cheese", "edam"]) you can write: sql.firstRow("select * from FOOD where type=? and name=?", "cheese", "edam") Added. Thanks for the suggestion and code/test contributions. Feel free to have a look at the current implementation and see if you think there is anything missing for your requirements. Thanks for the add. Looks like some really good additions to the docs in there. I am just trying to understand your requirement. The following methods are supposed to already support named parameters: Is that not enough for your requirements? Or is one or more of those broken? Regarding the documentation for GString variants of the methods. Most of them have examples which show embedded variables. I presume you are saying that this should be expanded to make it clearer? Is that correct?
http://jira.codehaus.org/browse/GROOVY-5405?focusedCommentId=296394&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel
CC-MAIN-2013-48
refinedweb
923
64.51
A leap year is exactly divisible by 4 except for century years (years ending with 00). The century year is a leap year only if it is perfectly divisible by 400. Example: Java Program to Check a Leap Year public class LeapYear { public static void main(String[] args) { int year = 1900; boolean leap = false; if(year % 4 == 0) { if( year % 100 == 0) { // year is divisible by 400, hence the year is a leap year if ( year % 400 == 0) leap = true; else leap = false; } else leap = true; } else leap = false; if(leap) System.out.println(year + " is a leap year."); else System.out.println(year + " is not a leap year."); } } Output 1900 is not a leap year. When you change the value of year to 2012, the output will be: 2012 is a leap year. In the above program, the given year 1900 is stored in the variable year. Since 1900 is divisible by 4 and is also a century year (ending with 00), it has been divisible by 400 for a leap year. Since it's not divisible by 400, 1900 is not a leap year. But, if we change year to 2000, it is divisible by 4, is a century year, and is also divisible by 400. So, 2000 is a leap year. Likewise, If we change year to 2012, it is divisible by 4 and is not a century year, so 2012 a leap year. We don't need to check if 2012 is divisible by 400 or not.
https://cdn.programiz.com/java-programming/examples/leap-year
CC-MAIN-2020-40
refinedweb
251
79.5
Even if there is no specific line in the main code stating to write this message in the serial port, this message will appear whenever there is no card or an issue with the attached cart in the carrier. This message comes from the MKR IoT library included in the code when using the carrier as #include <Arduino_MKRIoTCarrier.h>, and it’s displayed when initializing and testing the Carrier’s different sensors and actuators. If you want to check more in depth what’s in the library, all the files are available in our github. Check here the Arduino_MKRIoTCarrier.cpp file. If you are seeing this message, even if the SD card is attached to the carrier, please make sure the metal connectors are clean so the carrier can correctly interact with the SD. Please also make sure the card is correctly attached and pushed completely into the card holder.
https://support.arduino.cc/hc/en-us/articles/360018131300-MKR-IoT-Carrier-Serial-port-message-SD-card-not-detected
CC-MAIN-2022-40
refinedweb
150
58.92
The: sealed class SealedClass { public int x; public int y; } It is an error to use a sealed class as a base class or to use the abstract modifier with a sealed class. Structs are implicitly sealed; therefore, they cannot be inherited. For more information about inheritance, see Inheritance (C# Programming Guide). // cs_sealed_keyword.cs using System; sealed class SealedClass { public int x; public int y; } class MainClass { static void Main() { SealedClass sc = new SealedClass(); sc.x = 110; sc.y = 150; Console.WriteLine("x = {0}, y = {1}", sc.x, sc.y); } } x = 110, y = 150 In the preceding example, if you attempt to inherit from the sealed class by using a statement like this: class MyDerivedC: SealedClass {} // Error you will get the error message: 'MyDerivedC' cannot inherit from sealed class 'SealedClass'. For more information, see the following sections in the C# Language Specification: 10.1.1.2 Sealed classes 10.5.5 Sealed methods
http://msdn.microsoft.com/en-us/library/88c54tsw(VS.80).aspx
crawl-002
refinedweb
153
66.94
"v.kalra.w" <vkalra@agere.com> wrote on 09/27/2005 04:18:49 PM: > We've been using subversion for some small projects and have been happy > enough with it that we want to move some of our big stuff under it. > Unfortunately, the very first such project has run into various > unexplained hangs at import time and some of the team members are having > second thoughts about it. I've googled for the scenarios and looked at > the mailing list archives, but I cannot seem to find anything similar > that others may have run across. > > First the basics: We're trying to put about 10GB worth of data in about > 6000 files under svn. The files are a mix of binary and ascii files, > mostly ascii. The repository type does NOT use Berkley DB -- We've tried > verisons 1.1.3 and 1.2.1, going over http or using the NFS file system > via the file:// mechanism, but in all cases, the import hangs part of > the way through the process. The whole process takes hours to go > through, so it is very frustrating to find it hang yet another time. > > Any ideas?! Please help! Depending on how your APR (on the server) was compiled it may not be able to handle files that are > 2GB. If you commit more than 2 GB at one time, you will have a revision file in the fsfs repository that APR cannot handle due to its size. I am not saying that is the problem, but that is somewhere to start. So my recommendation would be to go back to the idea of breaking the import into chunks. A lot of "seasoned" users try to avoid using svn import. An easy trick is to perform a checkout of your empty repository into a local folder. This then creates an empty working copy. You can then start creating your folder/file structure that you want and use svn add and svn commit to get it to the repository. This technique might make it easier for you to do this in chunks. Sep 27 22:29:55 2005 This is an archived mail posted to the Subversion Users mailing list. This site is subject to the Apache Privacy Policy and the Apache Public Forum Archive Policy.
https://svn.haxx.se/users/archive-2005-09/1342.shtml
CC-MAIN-2022-27
refinedweb
384
78.28
This site uses strictly necessary cookies. More Information Beginner here. In my game I have placed a pause method. The best ever method as far as I know to pause is to set Time.timeScale to 0. But the problem is I can't resume by setting it back to 1 as every other object in my game including codes got paused. Someone please help me with a replacement. My code also involves animator gameobjects. also I want to know whether setting Time.timeScale to 0 would pause the System time Time.time or not. Thanks in advance. :) What is the UI system you are using? I'm also placing timescale to 0, but i just have a function in a button and it sets it back to 1. I'm using the new UI that got introduced in Unity 4.6. UnityEngine's Time.time is affected by Time.deltaTime. I recommend that you use Time.realtimeSinceStartUp if you want Time.time without it being affected by Time.deltaTime. @screenname_taken I just used the pause button as a normal gameobject and not UI button. wouldn't it work then? @abhishekabz004 nnnoooooooyyysssnnnoooooo? Don't think so, but i guess it will depend on your implementation on the script. If you have something in Update, it won't i think but don't quote me on that :P. sorry :P btw. I have posted my code in the other answer. help me out if you find any mistake :) Answer by sabish-m · Jun 12, 2015 at 06:06 PM #pragma strict function Paused(){ Time.timeScale = 0.0; } function Resume(){ Time.timeScale = 1.0; } function Quit(){ Application.Quit(); } I appreciate your help. :) But I already have my code. Its just that it is not working (resuming) once it gets paused. Here is my code. public class pauseaction : $$anonymous$$onoBehaviour { public bool ispause= true; void Update () { if (Time.timeScale == 0) { //Time.timeScale =1; /* I even tried to change it this way. But still it wouldnt change once it got paused */ } } void On$$anonymous$$ouseDown(){ if (ispause) { ispause=false; Time.timeScale=0; } else { ispause=true; Time.timeScale = 1; } } } Correct me if I made some mistake. Thank you once again. Pause game that not using deltatime for movment 1 Answer Pause, Unpause 1 Answer How to Pause game 1 Answer Problem changing TimeScale 1 Answer Pause Menu Text Not Rendering 0 Answers EnterpriseSocial Q&A
https://answers.unity.com/questions/985299/couldnt-resume-once-timetimescale-is-set-to-0.html
CC-MAIN-2021-43
refinedweb
400
79.16
#include <hallo.h> * Jamie Wilkinson [Tue, Nov 11 2003, 11:40:11PM]: > There are already several forks of the Linux kernel in Debian anyway. > Robert wishes to attempt to unify them, does that not grant him use of the > name 'linux'? Bug nobody was bold enough to take exactly this (as said very generic) name. And Robert does not have agreement with maintainers of the packages he wants to unify. So it is yet another fork. And what does the next person do who tries to unify them? MfG, Eduard. -- Katzen erreichen mühelos, was uns Menschen versagt bleibt: durchs Leben gehen ohne Lärm zu machen. -- Ernest Hemingway
https://lists.debian.org/debian-devel/2003/11/msg00807.html
CC-MAIN-2017-47
refinedweb
107
81.73
When you talk with fellow developers and you mention Service Layer people automatically hear WCF Services. Did i miss a book or some guidance document from Microsoft, stating that WCF stands for service layer? Overview For those who have been around for a while, back in the dark ages of .NET (pre WCF Era) there where amongst others the following communication options: - Web services (XML) - .NET Remoting (XML or Binary) - Communication using the Socket/SocketPool classes Each with their specific configuration, setup and usage. With the release of .Net Framework 3.0/3.5, Microsoft created (or bought) a way to unify all of those options into 1 product that makes it easy, well almost easy, to switch from one option to another. And they named it Windows Communication Foundation. What is a Service Layer and when should we implement one? A Service Layer defines an application’s boundary and its set of available operations from the perspective of interfacing client layers. It encapsulates the application’s business logic, controlling transactions and coordinating responses in the implementation of its operations. [Martin Fowler] You typicly introduce a Service Layer when you have complex use cases, which possibly will be reused by different UI’s, like for instance between a ASP.NET MVC application, a Windows Service or a Console application and you want to avoid code duplication. Or you want to separate your use cases from your UI Flow for better testability. How should we use WCF? It should be an abstraction layer, you simplify the underlying relational/domain complexity into understandable ServiceContracts with their respective model (datacontracts). And if we do need WCF, it’s because we really need it YAGNI : - We have a need for distributed computing - We need to be able to communicate across the web or across the enterprise - … And yes, using WCF, introduces complexity but you really needed it. How are we using it? Most of us are using it as a gateway into our data retrieval and crud methods, sending entire domainobject-graphs (anemic) with all their complexity over the wire. About 90% of the time, these objects are serialized to SOAP. Just so we can use these WCF services, hosted on a IIS Server in our web application, hosted on the same IIS server. Reason why we keep on doing this: About 70% of the time the answer is: It’s so easy when we need to make our WCF publicly available. (other possible answer is Simply because we can) Please consider following scenario and hopefully you will rethink your answer: [DataContract] public class Product { public Product() { } [DataMember] public double Prise { get; set; } } Which off course is nicely used in following WCF Service: [ServiceContract] public interface IProductService { [OperationContract] Product GetProductById(int id); } Conversation: Armand (Architect): John, Lisa has made a screwup in code, you need to rename the property Prise to Price in our product model. John ( Senior Developer): Can’t do Armand! Armand (Architect): Why not, John? John (Senior Developer) : [Hesitates] Well … erm … because we have to call all of our customers and tell them we have a breaking API change.
http://tommarien.github.io/blog/2011/10/26/wcf-the-one-size-fits-them-all-service-layer-anti-pattern
CC-MAIN-2017-22
refinedweb
518
52.49
Jquery form validation does not work jquery.validate.min.js I called the functions (validate function) properly. But jquery effect does not work. Could you please solve this problem? Thanks!  ...Jquery form validation does not work I want to use jquery validation validator framework work in Struts validator framework work in Struts How does validator framework work in Struts Submit Articles for Free directories and announcement lists for places to submit your work to.  ... Submit Articles for Free  .... Submit Articles To submit an article for possible inclusion Datepicker not getting called through include function of php Datepicker not getting called through include function of php my... handler on the startDate input to call the setReservationDates function... NOT been split across three inputs */ function makeTwoChars(in sing validator framework work in struts sing validator framework work in struts How does client side validation using validator framework work in struts Why it called Struts? Why it called Struts? Why it called Struts getOutputStream() has already been called for this response getOutputStream() has already been called for this response hi... called for this response. here is my jsp code: <%@ page import...="ISO-8859-1"%> <%@ taglib uri=" How does the Java for each loop work? How does the Java for each loop work? How does the Java for each loop Struts Articles security principle and discuss how Struts can be leveraged to address..., but the examples should work in any container. We will create a Struts plugin class... Struts Portlet Framework 5.1.0.1 (hereafter called the framework How does Social Media Marketing Work How does Social Media Marketing Work In this section we will understand the working of Social Media Marketing and see "How Social Media Marketing... Marketing really works for your website. How does Social Media Marketing Work Submit project to get developed is the Price of the Project ? How does the whole process work... How does the whole process work ? The whole process... and presented here as questions. How do I Submit Struts application two submit button Struts application two submit button Hai, i'm new in struts...;html:submit <bean...:submit> <html:submit Struts validation not work properly - Struts Struts validation not work properly hi... i have a problem...) { this.address = address; } } my struts-config.xml.../StrutsCustomValidator.shtml http struts "/> </plug-in> </struts-config> validator...;!-- This file contains the default Struts Validator pluggable validator... in this file. # Struts Validator Error Messages errors.required={0 Struts 2 Tutorials - Struts version 2.3.15.1 for making developer work easy. Removing default Struts 2 action suffix - How... is called. Interceptors help in implementing double-submit guards, type conversion...Struts 2 Tutorials - Struts version 2.3.15.1 Struts 2 Tutorials covered Spring Duplicate submit - Spring Spring Duplicate submit hi, i have problem in spring, i am pressing back or refresh my request get submitted again what i can do to avoid this,i am using only spring not struts How does LBS work? How does LBS work? Location based service (LBS) is the application that users use to locate its own position with the help of some basic components like mobile devices, mobile jsp function - JSP-Servlet jsp function how to make function in jsp... i want example of jsp method or function in which on button click function get data fron database..... because any function that is defined in the declaratives tags are Submit Your Article these lines, you are invited to submit your work to our Public Relations... Submit Your Article  ... & Profits for you, so you should strongly consider to submit your articles Disabling submit button using jQuery be: $('input[type=submit]').click(function() { this.disabled = true; }); Or it might be more useful to do so on form submission: $('form').submit(function...Disabling submit button using jQuery Hello Sir I want to know When Submit a Form and while submit is working ,press the Refresh , what will happen in Struts Action Submit Html clicks on a submit button, the form is sent to the specific address... the input goes to a page called submit. asp which will further process it. Here... Action Submit Html   Struts integration with EJB in JBOSS3.2 ) Session Bean Session Bean can be defined as function bean called in RMI-IIOP... Controller) Architecture. It is open source and free. Struts frame work... projects group. Struts is a frame work for building really complex Facing Problem with submit and cancel button in same page - Struts Facing Problem with submit and cancel button in same page Hi, can u please help me out.I have placed submit and cancel button in the jsp page... friend, Read for more the database. More Struts Validator Examples User input validations... function in Struts 2. We have provided fully tested example code...Struts 2 Tutorial   Message Resource Bundle work. Message Resource Bundle work. How does Value replacement in Message Resource Bundle work custom RowSetReader get called from a CachedRowSet. custom RowSetReader get called from a CachedRowSet. How does a custom RowSetReader get called from a CachedRowSet validate() method of ActionForm work validate() method of ActionForm work How does validate() method of ActionForm work Struts Struts What is called properties file in struts? How you call the properties message to the View (Front End) JSP Pages JavaScript submit method ;script> tags. This function at last submits the form by calling submit... JavaScript submit method We can submit forms in following two ways in an HTML page: By using please check my code is wrong or ok.it was not work .this is form validation in javascript using jsf page please check my code is wrong or ok.it was not work .this is form validation...; function checkForm(){ if(document.form2["form2:uid"].value...){ alert("password does not match"); return false please check my code is wrong or ok.it was not work .this is form validation in javascript using jsf page " > function checkForm(){ if(document.form2["form2:uid..."].value){ alert("password does not match"); return...="submit" value="create" action="#{customerBean.cusomerAdd}"/> Submit Tag (Form Tag) Example Submit Tag (Form Tag) Example In this section, we are going to describe the submit tag. The submit tag is a UI tag that is used to render a submit button. The submit tag is used Download Struts Learn how to Download Struts for application development or just for learning the new version of Struts. This video tutorial shows you how you can download struts and save on your computer. This easy to understand download struts shows Work Email- Dos and Don?ts Work Email- Dos and Don’ts  ... and the Internet, emails are fast replacing letters in the realm of work... emails for work communications. Read Carefully Read your email fully Developing Struts Application Developing Struts Application  ... outline of Struts, we can enumerate the following points. All requests... of the servlets or Struts Actions... All data submitted by user are sent Struts + HTML:Button not workin - Struts :// + HTML:Button not workin Hi, I am new to struts. So pls bare with me if my question is fundamental. I am trying to add 2 Submit buttons jQuery 'submit' form event jQuery 'submit' form event In this tutorial, we will discuss about the 'submit' form event of jQuery. In this example...; <span></span> <script> $("form").submit does anybody could tell me who's the author - Struts does anybody could tell me who's the author does anyone would tell me who's the author of Struts2 tutorial() I'd like to translate this tutorial into Chinese , to make more and more isNaN function isNaN function What does isNaN function do struts(DWR) - Ajax struts(DWR) i want to pass a combo box value from my jsp page...::::: jsp page var xhr; function... called"); xhr.setRequestHeader("User-Agent", "my browser post method does not support this url post method does not support this url This is Get product servlet.... but I am receiving one error that is post method does not supported by this url...;center>"); out.println("<input type=submit value='Add Product Create a input button inside js function using createElement() in my called function. I used something like this but doesn't seems to work. Lets show is the function being called function show... called function. I used something like this but doesn't seems to work. Lets show STRUTS ACTION - AGGREGATING ACTIONS IN STRUTS STRUTS ACTION - AGGREGATING ACTIONS IN STRUTS... are a Struts developer then you might have experienced the pain of writing huge number of Action classes for your project. The latest version of struts provides classes Calling a function Calling a function Hi, I have a function xyz() in php code. When a button is clicked it should execute that particular function for that i have...; <input type="button" name="submit" value="Submit"/> < PHP fseek() function and example it will work for all functions It gives 0 if test succeeds and -1 of test gets... fseek() Function PHP Code code for fseek() Function in PHP <?php... Tutorials, Hibernate Tutorials, Struts Tutorials, JSF Tutorials, RMI, MySQL java - Struts : Submit struts...java This is my login jsp page:: function... friend, Check your code having error : struts-config.xml In Action Struts 2.0.3 Released # [WW-1557] - multiple="true" does not work in s:select tag # [WW-1562... Struts 2.0.3 Released The Struts... added. Here are the list changes made to Struts framework Allow new template disable function disable function Sir, I have called a java script function when one radio button is checked i want to disable this function when another radio button is checked ,both radio buttons are of same group Please help Thanks in advance java - Struts /loginpage.jsp login page :: function validate(objForm...: Submit success.jsp...! struts-config.xml How Struts Works gets start up the first work it does is to check the web.xml file and determine... to determine which module to be called upon an action request. Struts only reads... How Struts Works   multiboxes - Struts are checked but when i click on uncheck it does nothing(The uncheck radio button... in javascript code or in struts bean. Hi friend, Code to solve struts struts <p>hi here is my code can you please help me to solve...;input <input type="submit" value="login"/>...; <h1></h1> <p>struts-config.xml</p> Validator Framework - lab oriented lesson STRUTS-VALIDATOR FRAMEWORK R.S.Ramaswamy ( developeriq..Oct-2005) Struts... entered by us in the struts-config.xml file .The Action class does not do struts - Struts struts how to handle multiple submit buttons in a single jsp page of a struts application Hi friend, Code to help in solving the problem : In the below code having two submit button's its values java - Struts file. function validate(objForm... Login User ID: Submit PHP Variable Outside Function PHP Variable Outside Function In PHP Functions, a variable can be called either outside the function or inside the function. If we declare a variable within the function, it will not seen outside the function and if you declare integration with EJB in WEBLOGIC7 be defined as function bean called in RMI-IIOP style from Enterprise container. Two...) Architecture. It is open source and free. Struts frame work was developed.... Struts is a frame work for building really complex Enterprise level Struts Projects ; Mockrunner does not read any configuration file like web.xml or struts... Struts Projects Easy Struts Projects to learn and get into development ASAP. These Struts Project will help you jump the hurdle of learning complex - Struts used in a struts aplication. these are the conditions 1. when u entered... Info function isEmpty(elem) { var str = elem.value Multiple submit buttons in single xhtml form - Java Server Faces Questions Multiple submit buttons in single xhtml form Hi all, Here I am attaching the source of the page , which containig two submit buttons. Somebody suggested to keep eaxh button in different form. I am new to JSF, can anyone split - application missing something? there. I can manually enter them and they work. Action is called correctly...struts - application missing something? Hello I added a parameter... in the struts working and all is great till I close JBoss or the server gets shut down struts - Struts struts what is the use of debug 2 Hi Friend, This is the parameter that is used to specify the debug level for the ActionServlet class.It is having three values: 0- It does not give any debug information. 1 Struts File Upload and Save regarding "Struts file upload example". It does not contain any... Struts File Upload and Save  ... directory of server. In this tutorial you will learn how to use Struts Why Outsourcing, Why Outsourcing Service, Why Outsourcing Work challenges. By outsourcing work to such vendors, a firm can access their facilities... with all the training. Cash Flow When an organization outsources work, it often sells the assets associated with the transferred work to the vendor Dispatch Action - Struts Dispatch Action While I am working with Structs Dispatch Action . I am getting the following error. Request does not contain handler parameter named 'function'. This may be caused by whitespace in the label text submit a form submit a form How can we submit a form without a submit button PHP HTML Form Submit Button anything special with a submit button. All the work has done automatically till...Topic : HTML FORM SUBMIT BUTTON Part - 4 The another part which is important to covered that is Submit button. If you are following all the previous parts viewwillappear not called viewwillappear not called When i browse between different views in my application, viewwillappear not called. What is the problem Struts - Struts ) } alert("Invalid E-mail Address! Please re-enter.") return (false); } function... ********************************************** User Registration function checkEmail(email) { if (/^\w...; } if(formObj.address.value.length==0){ alert("Please enter address!"); formObj.address.focus Struts - Struts ) } alert("Invalid E-mail Address! Please re-enter.") return (false); } function... ********************************************** User Registration function checkEmail(email) { if (/^\w...; } if(formObj.address.value.length==0){ alert("Please enter address!"); formObj.address.focus(); return struts html tag - Struts struts html tag Hi, the company I work for use an "id" tag on their tag like this: How can I do this with struts? I tried and they don't work Struts Tutorials . Using the Struts Validator Follow along as Web development expert Brett... application programming.With the Validator, you can validate input in your Struts... to the internal Map of the DynaForm bean does not tell the Struts that each of those
http://www.roseindia.net/tutorialhelp/comment/12911
CC-MAIN-2014-15
refinedweb
2,417
66.74
NAME OSSL_PARAM - a structure to pass or request object parameters SYNOPSIS #include <openssl/core.h> typedef struct ossl_param_st OSSL_PARAM; struct ossl_param_st { const char *key; /* the name of the parameter */ unsigned char data_type; /* declare what kind of content is in data */ void *data; /* value being passed in or out */ size_t data_size; /* data size */ size_t return_size; /* returned size */ }; DESCRIPTION OSSL_PARAM is a type that allows passing arbitrary data for some object between two parties that have no or very little shared knowledge about their respective internal structures for that object. A typical usage example could be an application that wants to set some parameters for an object, or wants to find out some parameters of an object. Arrays of this type can be used for the following purposes: Setting parameters for some object The caller sets up the OSSL_PARAM array and calls some function (the setter) that has intimate knowledge about the object that can take the data from the OSSL_PARAM array and assign them in a suitable form for the internal structure of the object. Request parameters of some object The caller (the requestor) sets up the OSSL_PARAM array and calls some function (the responder) that has intimate knowledge about the object, which can take the internal data of the object and copy (possibly convert) that to the memory prepared by the requestor and pointed at with the OSSL_PARAM data. Request parameter descriptors The caller gets an array of constant OSSL_PARAM, which describe available parameters and some of their properties; name, data type and expected data size. For a detailed description of each field for this use, see the field descriptions below. The caller may then use the information from this descriptor array to build up its own OSSL_PARAM array to pass down to a setter or responder. Normally, the order of the an OSSL_PARAM array is not relevant. However, if the responder can handle multiple elements with the same key, those elements must be handled in the order they are in. An OSSL_PARAM array must have a terminating element, where key is NULL. The usual full terminating template is: { NULL, 0, NULL, 0, 0 } This can also be specified using OSSL_PARAM_END(3). Functional support Libcrypto offers a limited set of helper functions to handle OSSL_PARAM items and arrays, please see OSSL_PARAM_get_int(3). Developers are free to extend or replace those as they see fit. OSSL_PARAM fields - key The identity of the parameter in the form of a string. In an OSSL_PARAM array, an item with this field set to NULL is considered a terminating item. - data_type The data_type is a value that describes the type and organization of the data. See "Supported types" below for a description of the types. - data - - data_size data is a pointer to the memory where the parameter data is (when setting parameters) or shall (when requesting parameters) be stored, and data_size is its size in bytes. The organization of the data depends on the parameter type and flag. The data_size needs special attention with the parameter type OSSL_PARAM_UTF8_STRING in relation to C strings. When setting parameters, the size should be set to the length of the string, not counting the terminating NUL byte. When requesting parameters, the size should be set to the size of the buffer to be populated, which should accomodate enough space for a terminating NUL byte. When requesting parameters, it's acceptable for data to be NULL. This can be used by the requestor to figure out dynamically exactly how much buffer space is needed to store the parameter data. In this case, data_size is ignored. When the OSSL_PARAM is used as a parameter descriptor, data should be ignored. If data_size is zero, it means that an arbitrary data size is accepted, otherwise it specifies the maximum size allowed. - return_size When an array of OSSL_PARAM is used to request data, the responder must set this field to indicate size of the parameter data, including padding as the case may be. In case the data_size is an unsuitable size for the data, the responder must still set this field to indicate the minimum data size required. (further notes on this in "NOTES" below). When the OSSL_PARAM is used as a parameter descriptor, return_size should be ignored. NOTE: The key names and associated types are defined by the entity that offers these parameters, i.e. names for parameters provided by the OpenSSL libraries are defined by the libraries, and names for parameters provided by providers are defined by those providers, except for the pointer form of strings (see data type descriptions below). Entities that want to set or request parameters need to know what those keys are and of what type, any functionality between those two entities should remain oblivious and just pass the OSSL_PARAM array along. Supported types The data_type field can be one of the following types: - OSSL_PARAM_INTEGER - - OSSL_PARAM_UNSIGNED_INTEGER The parameter data is an integer (signed or unsigned) of arbitrary length, organized in native form, i.e. most significant byte first on Big-Endian systems, and least significant byte first on Little-Endian systems. - OSSL_PARAM_REAL The parameter data is a floating point value in native form. - OSSL_PARAM_UTF8_STRING The parameter data is a printable string. - OSSL_PARAM_OCTET_STRING The parameter data is an arbitrary string of bytes. - OSSL_PARAM_UTF8_PTR The parameter data is a pointer to a printable string. The difference between this and OSSL_PARAM_UTF8_STRING is that data doesn't point directly at the data, but to a pointer that points to the data. If there is any uncertainty about which to use, OSSL_PARAM_UTF8). - OSSL_PARAM_OCTET_PTR The parameter data is a pointer to an arbitrary string of bytes. The difference between this and OSSL_PARAM_OCTET_STRING is that data doesn't point directly at the data, but to a pointer that points to the data. If there is any uncertainty about which to use, OSSL_PARAM_OCTET). NOTES Both when setting and requesting parameters, the functions that are called will have to decide what is and what is not an error. The recommended behaviour is: Keys that a setter or responder doesn't recognise should simply be ignored. That in itself isn't an error. If the keys that a called setter recognises form a consistent enough set of data, that call should succeed. Apart from the return_size, a responder must never change the fields of an OSSL_PARAM. To return a value, it should change the contents of the memory that data points at. If the data type for a key that it's associated with is incorrect, the called function may return an error. The called function may also try to convert the data to a suitable form (for example, it's plausible to pass a large number as an octet string, so even though a given key is defined as an OSSL_PARAM_UNSIGNED_INTEGER, is plausible to pass the value as an OSSL_PARAM_OCTET_STRING), but this is in no way mandatory. If a responder finds that some data sizes are too small for the requested data, it must set return_size for each such OSSL_PARAM item to the minimum required size, and eventually return an error. For the integer type parameters (OSSL_PARAM_UNSIGNED_INTEGER and OSSL_PARAM_INTEGER), a responder may choose to return an error if the data_size isn't a suitable size (even if data_size is bigger than needed). If the responder finds the size suitable, it must fill all data_size bytes and ensure correct padding for the native endianness, and set return_size to the same value as data_size. EXAMPLES A couple of examples to just show how OSSL_PARAM arrays could be set up. Example 1 This example is for setting parameters on some object: #include <openssl/core.h> const char *foo = "some string"; size_t foo_l = strlen(foo); const char bar[] = "some other string"; OSSL_PARAM set[] = { { "foo", OSSL_PARAM_UTF8_STRING_PTR, &foo, foo_l, 0 }, { "bar", OSSL_PARAM_UTF8_STRING, &bar, sizeof(bar) - 1, 0 }, { NULL, 0, NULL, 0, 0 } }; Example 2 This example is for requesting parameters on some object: const char *foo = NULL; size_t foo_l; char bar[1024]; size_t bar_l; OSSL_PARAM request[] = { { "foo", OSSL_PARAM_UTF8_STRING_PTR, &foo, 0 /*irrelevant*/, 0 }, { "bar", OSSL_PARAM_UTF8_STRING, &bar, sizeof(bar), 0 }, { NULL, 0, NULL, 0, 0 } }; A responder that receives this array (as params in this example) could fill in the parameters like this: /* OSSL_PARAM *params */ int i; for (i = 0; params[i].key != NULL; i++) { if (strcmp(params[i].key, "foo") == 0) { *(char **)params[i].data = "foo value"; params[i].return_size = 9; /* length of "foo value" string */ } else if (strcmp(params[i].key, "bar") == 0) { memcpy(params[i].data, "bar value", 10); params[i].return_size = 9; /* length of "bar value" string */ } /* Ignore stuff we don't know */ } SEE ALSO openssl-core.h(7), OSSL_PARAM_get_int(3), OSSL_PARAM_dup(3) HISTORY OSSL_PARAM was added in OpenSSL 3.0. Licensed under the Apache License 2.0 (the "License"). You may not use this file except in compliance with the License. You can obtain a copy in the file LICENSE in the source distribution or at.
https://www.openssl.org/docs/man3.0/man3/OSSL_PARAM.html
CC-MAIN-2021-43
refinedweb
1,476
51.38
Provided by: libdpm-dev_1.13.0-1_amd64 NAME rfiosetopt - set RFIO options SYNOPSIS #include <sys/types.h> #include "rfio_api.h" int rfiosetopt (int opt, int *pval, int len) int rfio_setbufsize (int s, int bufsize) DESCRIPTION rfiosetopt sets the RFIO option opt to the content of the memory cell pointed by pval. rfio_setbufsize sets the size of the readahead buffer to be used on a particular socket connection. opt can have on of the following values: RFIO_READOPT The value pointed by pval can be 0, RFIO_READBUF, RFIO_READAHEAD or RFIO_STREAM (V3). If set to zero, a normal read will be used (one request to the server per read).. RFIO_NETOPT The value pointed by pval can be RFIO_NONET or RFIO_NET. If set to RFIO_NONET, the NET entries in shift.conf are ignored. Default is RFIO_NET. RFIO_NETRETRYOPT The value pointed by pval can be RFIO_RETRYIT or RFIO_NOTIME2RETRY.. RFIO_CONNECTOPT The value pointed by pval can be RFIO_NOLOCAL or RFIO_FORCELOCAL. If set to RFIO_FORCELOCAL, no parsing is done on pathname. The file is assumed to be local. Default is RFIO_NOLOCAL. The len argument is ignored. s is the file descriptor of the receiving socket. bufsize is the size of the readahead buffer to be used. RETURN VALUE rfiosetopt returns 0 if the operation was successful or -1 if the operation failed. In the latter case, serrno is set appropriately. ERRORS ENOMEM buffer could not be allocated. EINVAL opt is not a valid option, bufsize is negative or the user tries to change the buffer size after the actual I/O has started. SEE ALSO rfio_open(3), rfioreadopt(3) AUTHOR LCG Grid Deployment Team
http://manpages.ubuntu.com/manpages/eoan/man3/rfio_setbufsize.3.html
CC-MAIN-2020-40
refinedweb
267
69.07
Hide Forgot The default sudo path is quite limited and seemingly irrational given the purpose of the program. I suggest adding something like --with-secure-path=/usr/local/sbin:/usr/sbin:/sbin:/usr/local/bin:/usr/bin:/bin:/usr/X11R6/bin to the configure statement in the spec file. That way, you can do things like "sudo service foo start". Excerpt from the man page of sudo: "sudo â execute a command as another user". This can be any user. Therefore it does not make sense to overwrite the users path environment variable with a fixed value, which is reasonable only for the user root. The default behavior is to leave the users path untouched. If you want to have /sbin etc. in your path, then add it to your normal user path. You will have this path after calling sudo, too. You can also use "sudo /sbin/service foo start". On the contrary -- it makes a *lot* of sense for there to be a fixed path, since it reduces the possiblity of surprises when running a command as another user. Since 90% of the use of this program is to run things as root, adding the sbin directories to the path seems like a good idea. Note that this doesn't take any hacking -- the sudo maintainers have conveniently left a "--with-secure-path" configure option. Obviously "sudo /sbin/service foo start" is a possibility, but the addition of those slashes and the extra directory name is significant overhead when explaining what to do to someone else -- as I have to do a lot. It's even worse when it's "sudo /usr/sbin/someprogram -someflags someoptions". Sure, end-users should learn to understand the unix directory structure, but when they're working to get a problem solved isn't necessarily the best time to hit them with it. I won't reopen this on you since it's obviously your call, but I still think changing it would be a good idea. I'm going to reopen this, as it periodically comes up, as it just did on the Fedora Devel mailing list. As times have changed, I suggest a much more minimal securepath: --with-secure-path=/sbin:/bin:/usr/sbin:/usr/bin and anything else arguably *should* require a full pathname to be given. Yes, I'd really like to see this done. If you feel that munging for every user is bad, then work with upstream to add another option so that the path change is only done when the sudo "to" user is root, and leave the path alone for other users. But that can be worked on in the background while improving the usability of users who use sudo for root level tasks (which is the primary use). This will go a good ways toward lowering the frustration level when using Fedora/RHEL. Maybe it's worth exploring sudo -i further. It reminds a bit of su's '-' and already does 99% of what it should do, it only chokes on sudo -i <command> being passed as $SHELL <command>, e.g. <command> needs to be a shell script. Instead sudo could be changed to interprete sudo -i <command> as invoking the target user's shell as $SHELL -c "<command>" FWIW, I think is a sucky, backward-incompatible change. Making it something that the admin can configure in sudoers is one thing. Forcing it on absolutely everyone who uses sudo is quite another. I don't like this behavior, it's not appropriate on my home machine, and it's going to be a royal pain in the ass for me and I suspect for many other people as well. There are a *ton* of programs I keep in ~/bin and ~/scripts, which are in my PATH, which I often need to use as root with sudo. Adding /usr/local/sbin to the secure path might be a compromise option that would allow for more local control. This change has recently appeared in updates-testing for F9 which I guess means that people will start seeing it in their updates in the near future. Count me in agreement with comment 7. This should be a setting in the /etc/sudoers file, not a something that is compiled in. But never mind - I can script around it I guess. Is this what just broke my sudo? I run sudo extdns as myself, which should find /home/mward/bin/extdns. Since I applied the latest updates, I now get $ sudo extdns sudo: extdns: command not found Almost certainly it is: $ cat checkpath #!/bin/sh echo $PATH $ ./checkpath /opt/opsutils/bin:/home/mward/bin:/usr/local/bin:/usr/kerberos/bin:/usr/lib/qt-3.3/bin:/usr/lib/ccache:/usr/bin:/bin:/usr/java/latest/bin:/usr/java/latest/bin:/usr/java/latest/bin:/usr/sbin:/sbin:. $ sudo ./checkpath /sbin:/bin:/usr/sbin:/usr/bin Also note that I removed the reset_env stuff from sudoers, since that was also really annoying (it nuked EDITOR, and some others I wanted). All it contains is a couple of user and group specifications. And why did this change get introduced to Fedora 9? This is completely the wrong change anyway. The "sudo sanity" project for F10 was supposed to add /sbin and /usr/sbin to all users' PATHs via /etc/profile, not by touching (and breaking) sudo. re comment #10 If you're running commands in your own home directory via sudo, why not just put them in ~/sbin and create aliases or commands in ~/bin that automatically run them with sudo plus the full path? re comment #11 -- instead of removing the environment-setting stuff, I strongly suggest configuring it to preserve the ones you want to keep. Otherwise, nasty things can be done. re comment #12 -- this was part of the original sbin sanity proposal. The /sbin /usr/sbin mess ended up getting implemented as well. *That* seems like insanity to me, since it totally pollutes the namespace for tab completion in normal use. But ah well. > why not just put them in ~/sbin and create aliases? Why? The old way worked fine? > instead of removing the environment-setting stuff..., I strongly suggest configuring it to preserve the ones you want to keep. Otherwise, nasty things can be done. Again, why? What kinds of problems are you referring to? > The /sbin /usr/sbin mess ... it totally pollutes the namespace for tab completion I have long had /sbin and /usr/sbin in my non-privileged user's PATH, and I never found it to be a problem. In my view, sudo is for running commands exactly as I would run them but with higher privileges. It means I get my own aliases, my own keybindings, my own value of EDITOR, my own SSH agent, etc, etc, . If I want to run commands as root, there is "sudo su -" and "sudo -i", but the need for that has never arisen. Just my 2 cents: I expect sudo to work mostly as described in the end of comment #14 and totally agree that sudo shouldn't be compiled with a hardcoded and non-changeable PATH. For example, I have some development tools installed in /opt/ which I need to run via sudo and it came as a big surprise to me that I can't do it anymore... Specially because the option --with-secure-path is one of the less documented features of sudo. What's the problem in having a conservative sudoers default file and let the admin finetune it (including adding PATH to keep_env) if needed? > /opt/ which I need to run via sudo and it came as a big surprise to me that I can't do it anymore Sure you can. You just need to provide the path explicitly, so there's no surprises. Which is anything but practical... but anyway, I now have a wrapper to workaround it: #!/bin/bash set -e CMD=$(which $1) exec /usr/bin/sudo PATH=$PATH $CMD ${@:2} (not perfect, but works in my common scenarios :-) (In reply to comment #16) > You just need to provide the path explicitly, so there's no surprises. Hogwash. The "surprises" are that people expect "sudo command" to behave the same as "command", just as a different user. People do not expect "sudo command" to fail because "command" happens to be in a search path location that the package maintainers have presumptuously decided is not "secure enough." People do not expect the package maintainers to make something like this completely unconfigurable even for people on private single-user systems who have worked in computer security for over two decades and know a thing or two about what is and isn't secure. This is nothing more than annoying fake security. It's a silly change, and it should be undone. You want to have a paranoid default configuration? Fine, keep your paranoid default configuration. But let me override it in /etc/sudoers if I know what I'm doing, which I most assuredly do. The suggestion that this should be configurable in sudoers seems reasonable; once that change is upstream we could move the configuration option here from compile time to the sudoers file. But this bug entry really isn't the place for extended discussion. The option is "secure_path", which combined with the already in place "reset_env" should be enough to reset the PATH by default. Just adding to sudoers the following line should do the trick: Defaults secure_path = /sbin:/bin:/usr/sbin:/usr/bin Should I open another ticket for this? Interesting — as you can see from the timeline of this bug, the original suggestion was from seven years ago. I actually looked in the Changelog to see if anything had changed -- I should have looked at the man page (or the source). The "except_group" option also provides some interesting flexibility. So yeah, please open a new bug, something along time lines of: "move secure_path from compile-time option to sudoers file". Thanks. Done, bug #517428 Thanks. For sercure path to work on RH4 or RH5 you need to add following to /etc/sudoers Defaults secure_path="/usr/sbin/bar:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/X11R6/bin"
https://partner-bugzilla.redhat.com/show_bug.cgi?id=80215
CC-MAIN-2019-35
refinedweb
1,710
62.58
Basic user interface for lizard websites Project description lizard-ui Lizard-ui provides a basic Django user interface, so a base Django template and some css + javascript. We designed it at Nelen & Schuurmans for our geographical information websites (with water management information). Translation status: Choices, requirements, assumptions Lizard-ui is opinionated: it makes choices and prescribes (good!) technologies. - Included: the twitter-bootstrap css framework. It resets css styles so that we’ve got a common base. It fixes common IE layout bugs. It gives a basic typography that’s quite pleasing. And it has some javascript that makes many common UI tasks easy. - Required: django-staticfiles. For a more verbose description, see Reinout’s blog entry (written with lizard-ui in mind). - Required: django_compressor for combining css/javascript files in production. - Assumption: one screen, using the full width/height of the browser, without scrolling. Our main goal is showing a nice big map with a small header and a sidebar. You don’t want to scroll a map. It is of course possible to have a scrollbar inside that main content area itself. - Assumption: javascript is available. Hey, we’re showing a map so you need javascript. So we liberally use javascript to get the UI right, for instance by detecting and setting the main content area’s width and height. - Included: jquery. Yeah, it is pretty much the standard nowadays. So we use jquery where jquery can be used instead of doing it with generic javascript. - Included: both jqueryui and jquerytools. Visual goodies. Jquerytools for the overlay and tabs, jqueryui for the rest (drag/drop and so). - Included: openlayers as map javascript library. (Lizard-map, sooooon to be released, contains our basic map interaction javascript and python code). License + licenses Our own license is GPLv3. Lizard-ui ships with a couple of external css/javascript libraries. - Twitter-bootstrap - Apache 2.0 license. - Jquery and jqueryui - Dual licensed under the MIT or GPL Version 2 licenses. Includes Sizzle.js, released under the MIT, BSD, and GPL Licenses. - Jquerytools - No copyrights or licenses. Do what you like. - Openlayers - Clear BSD license. - Famfamfam icon set - CC attribution license. - Treeview jquery plugin - MIT/GPL Django settings Here’s an excerpt of a settings.py you can use. The media and static root directory setup assumes the use of buildout, but you can translate it to your own filesystem setup: INSTALLED_APPS = [ 'lizard_ui', 'compressor', 'staticfiles', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', ] # Note: the below settings are more elaborate than needed, # but we want to test django_compressor's compressing which # needs a media url and root and so. # SETTINGS_DIR allows media paths and so to be relative to # this settings file instead of hardcoded to # c:\only\on\my\computer. SETTINGS_DIR = os.path.dirname(os.path.realpath(__file__)) # BUILDOUT_DIR is for access to the "surrounding" buildout, # for instance for BUILDOUT_DIR/var/static files to give # django-staticfiles a proper place to place all collected # static files. BUILDOUT_DIR = os.path.abspath(os.path.join(SETTINGS_DIR, '..')) # Absolute path to the directory that holds user-uploaded # media. MEDIA_ROOT = os.path.join(BUILDOUT_DIR, 'var', 'media') # Absolute path to the directory where django-staticfiles' # "bin/django build_static" places all collected static # files from all applications' /media directory. STATIC_ROOT = os.path.join(BUILDOUT_DIR, 'var', 'static') # URL that handles the media served from MEDIA_ROOT. Make # sure to use a trailing slash if there is a path component # (optional in other cases). MEDIA_URL = '/media/' # URL for the per-application /media static files collected # by django-staticfiles. Use it in templates like "{{ # MEDIA_URL }}mypackage/my.css". STATIC_URL = '/static_media/' # URL prefix for admin media -- CSS, JavaScript and # images. Make sure to use a trailing slash. Uses # STATIC_URL as django-staticfiles nicely collects admin's # static media into STATIC_ROOT/admin. ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' And a suitable apache config hint: <Location /static_media/> # The css/javascript/image staticfiles are cached in the # browser for a day. ExpiresActive On ExpiresDefault "access plus 1 day" </Location> <Location /static_media/CACHE/> # django_compress's generated timestamp'ed files: # cache forever ExpiresActive On ExpiresDefault "access plus 10 years" </Location> # Static files are hosted by apache itself. # User-uploaded media: MEDIA_URL = '/media/' Alias /media/ ${buildout:directory}/var/media/ # django-staticfiles: STATIC_URL = '/static_media/' Alias /static_media/ ${buildout:directory}/var/static/ Upgrading to Django 1.3 Lizard-ui 3.0 requires Django 1.3 as we want to start using class based views and some of the other 1.3 goodies. For that, you need to make some changes. Add LOGGING, for instance with: from lizard_ui.settingshelper import setup_logging LOGGING = setup_logging(BUILDOUT_DIR) # For production, use for instance: # LOGGING = setup_logging(BUILDOUT_DIR, console_level=None) And remove any by-hand logging setup, for instance with logging.basicConfig(). Import STATICFILES_FINDERS from lizard_ui, this adds a finder that also finds static media in /media in addition to the new /static: from lizard_ui.settingshelper import STATICFILES_FINDERS COMPRESS_STORAGE, COMPRESS_URL and COMPRESS_ROOT can now be removed from your settings as the defaults are now fine. Switch from using bin/django build_static to bin/django collectstatic. Usage You can mount lizard-ui’s urls, but it contains only live examples. So perhaps you should only mount it in debug mode under /ui. Handy, as it contains reasonably full documentation on how to use it, including available blocks and classes/IDs that you can use. The base layout is defined in realbase.html. You should however extend lizard_ui/lizardbase.html and then override the blocks that you want. CSS and javascript should be added to the relevant blocks, but don’t forget to call “block.super”. An example: {% extends "lizard_ui/lizardbase.html" %} {% block css %} {{ block.super }} <link type="text/css" href="{{ STATIC_URL }}lizard_map/lizard_map.css" media="screen, projection" rel="stylesheet" /> {% endblock css %} {% block javascript %} {{ block.super }} <script type="text/javascript" src="{{ STATIC_URL }}openlayers/OpenLayers.js"></script> <script type="text/javascript" src="{{ STATIC_URL }}lizard_map/jquery.workspace.js"></script> <script type="text/javascript" src="{{ STATIC_URL }}lizard_map/lizard_map.js"></script> {% endblock javascript %} {% block content %} <div id="map"></div> {% endblock content %} A example of a common task: change the logo. For that, make a static/lizard_ui directory in your django application (or site) and place a logo.png in it. Django-staticfiles’ mechanism will take your logo.png in preference to lizard-ui’s.. Language selector Starting with version 4.21 a language selector has been added to lizard-ui. To activate the language selector for your project, put these changes in your settings file: Make sure USE_I18N = True is set. Add UI_SHOW_LANGUAGE_PICKER = True. Add 'django.middleware.locale.LocaleMiddleware' to MIDDLEWARE_CLASSES just below the SessionMiddleware line and above the CommonMiddleware line. Put the available languages in the LANGUAGES settings, e.g.: LANGUAGES = ( ('en', 'English'), ('nl', 'Nederlands'), ('vi', 'Việt'), ) Pick a default language, e.g. LANGUAGE_CODE = 'en' TODO - Document all of the available classes/IDs that you can use to get automatic (javascript) behaviour. - Document the javascript code. - Add basic test that the example.html renders without errors. - Add javascript tests for the javascript code, ideally. - Add mechanism for rendering a passed-in (or registered/configured) list of object_tabs and object_actions, including some nice formatting. - Add mechanism for breadcrumbs. - Important: add tests for the login functionality. Credits - TODO started this library Changelog of lizard-ui 5.3 (2015-10-08) - Moved language checker over to lizard-map. That way it can be enabled through a Setting object. [reinout] - Using correct session key for storing the language. [reinout] 5.2 (2015-10-08) - Started with arabic translation (only login/logout has been translated till now, though, as test). [reinout] 5.1.1 (2015-03-31) - Flot formatting tweak: don’t show year when day is shown. Too long otherwise. 5.1 (2015-03-31) - UI changes directly (and dirty) in the downloaded flot library (so watch out if you download a new one). - Always showing years next to the month name. - Hardcoded Dutch month names and fixed some formatting. 5.0 (2014-12-15) - Made the “awesomebox” a bit wider (20px) and higher (100px) to prevent scrolling at least when there’s only one result. At least the graph is visible, then. You still need to scroll for the add-to-dashboard table… - Fixed scrolling on #textual page (for the dashboard). - Included elevationprofile.js in template - Fix layout bug in login modal. The margin was too large. - Enhance 404 and 500 html error templates. - Update daterange picker colors to be the same as the lizard header. - Supporting, sigh, opening actions in a new tab… - Set openlayers 2.13.1 for mobile divices (ipad, iphone), 2.12-r7 for the rest. (See for the solution on how to write out a closing script tag inside javascript). - Updated to django 1.6. 4.28 (2013-05-14) - Nothing changed yet. 4.27 (2013-05-08) - Nothing changed yet. 4.26 (2013-05-06) - Upgrade Twitter bootstrap to 2.3.1 - Upgrade font-awesome v3.0.2 - Update translations. 4.25.1 (2013-04-04) - Removed sentry_exception_handler() call from our exception middleware (introduced in 4.25), again. This breaks the tests. Further investigation showed that the call is only necessary if we return a value in our middleware, which we don’t. 4.25 (2013-04-03) - Merged deltaportaal fixes. Next to #popup-tabs there’s now also .popup-tabs. The body tag can have an ID or class now (needed for fiber). Added popup hover on one extra action category. 4.24 (2013-03-19) - Nothing changed yet. 4.23 (2013-03-19) - Actions now always use the data_attributes instead of only using them for the content-actions. - Apps can now completely remove the sidebar and rightbar elements without breaking the JavaScript. 4.22 (2013-02-21) - Add translation to Afrikaans. - Prevent daterangepicker to round to full days / hours. 4.21 (2013-02-20) - Add language selector. 4.20 (2013-02-19) - Add vietnamese translation for Login for testing purposes. 4.19 (2013-02-19) - Upgrade to zc.buildout 2.0.1. - Use translations package to manage translations. - Update translation files for dutch and vietnamese. 4.18 (2013-02-11) - Updated the app_icons. 4.17 (2013-01-28) - Fixed logo: removed artifacts; made the toes of the lizard more pronounced. 4.16 (2013-01-22) - When SSO_ENABLED evaluates to True in your settings, login/logout become real hyperlinks, instead of the modal popup. The links then point to the url alias named ‘login’. - Fixed a bug when map is unavailable during opening / closing the sidebar. - Update to jQuery UI 1.8.24. 4.15 (2012-12-19) - Fixed urls.py, so it won’t recusively include other lizard-* URLs when running as part of a site. - Made the appscreen admin more user friendly. - Initialize popovers again after fast appscreen load. 4.14 (2012-12-17) - Added flot.fillbetween plugin to the list of Javascript files. - Applied the rename of jquery’s .ui-button to .xui-button everywhere. - Also renamed jquerys $(el).button to $(el).jqbutton as to now conflict with Bootstrap. 4.13 (2012-12-04) - Updated a Django version. - Align the popup-loading spinner in the middle. 4.12 (2012-11-22) - Fixed graph axislabels. - Support mixed flot/matplotlib (IE8) graphs. - Moved graph stuff to lizard-map, which is a more suitable place for it (in the current app structure). In the future all UI stuff should go to lizard-ui. - Updated Twitter Bootstrap to v2.2.1. - Added better support for clickable popovers. - Changed tree styling a bit to support info icons next to tree items. - Disabled fadeIn for OpenLayers tiles. - Added a track that ‘instantly’ loads application screens. 4.11 (2012-10-18) - Add some app_icons. - Use Font-Awesome for icons. - Changed the styling a bit. 4.10 (2012-10-05) - Fix an unneeded django-compressor pin. - Add some app_icons. 4.9 (2012-10-04) - Relicensed from GPL to LGPL. - Removed dependency on sentry when sentry_level = None. - Fixed problem with sidebar width and content div scrollbars. - Update Twitter Bootstrap to 2.1.1, html5shiv to the latest dev version, flot to the latest dev version. - Remove seemingly unused jquery-tools library. - Merged coffeescript to lizard_ui.js. - Various styling fixes. - Change information popovers near edge of screen to their browser native counterparts. - Add control buttons to flot graph. Add flot navigate plugin. - Fix overflow (once and for all?). - Add date-range picker. - Add IE version and iPad detection. 4.8 (2012-08-23) - Remove conflicting simplejson dependency. - Remove raven which is incompatible with Django 1.4. - Add error when graph has no data. 4.7 (2012-08-23) - Build a custom jquery.flot.axislabels.js, which is much better (in terms of not messing up flot’s draw()). - Switch the popup’s tabs to the superior jquery-ui tabs, replacing the jquery-tools tabs. - Update flot to latest (git) version, which supports proper ticks rendering (on canvas instead of HTML elements). - Fixed textual content scrollbars / overflow (again?). - Updated some app_icons. 4.6 (2012-08-14) - Small styling issue with labels. 4.5 (2012-08-14) - Switch to OpenLayers dark theme. 4.4 (2012-08-14) - Flot graphs: calculate tick sizes. - Updated OpenLayers to 2.12. - Styling: fix bootstrap messing up labels, fix hover popup z-index. 4.3 (2012-07-26) - Fixed minor layout issues. 4.2 (2012-07-12) - Prettified background gradient in sidebar navigation tree. - Fixed minor layout issues. 4.1 (2012-06-28) - Trying to construct a breadcrumb even if we don’t have an application icon pointing at the current page. 4.0 (2012-06-19) - Date range styling; fix a FOUC; fix cursur pointer on H2; - Increased right sidebar to make legends fit. - Added styling for multi-select button. - Proper submission and handling of global errors on login form. - Changed label of collapse-sidebar-button to ‘Navigatie’. 4.0b6 (2012-06-06) - Moved excanvas for IE 6 and 7 outside compress. - Fixed trailing commas (IE7 does not like them). 4.0b5 (2012-06-05) - Replace zettingen.png icon to one with shadow. 4.0b4 (2012-06-01) - Added required_permission attribute on UiView. If you set it, the permission is checked and the user redirected, if needed. 4.0b3 (2012-06-01) - Tiny styling fix. - Add flot bar graph support. 4.0b2 (2012-05-31) - Properly close secondary sidebar (“Kaartlagen”) when hiding the sidebar (“Inklappen”). - Add the Flot JavaScript library. - Fix a small styling issue concerning workspaces. - Update to jQuery 1.7.2 which includes some .ajax() fixes. - Add client side support for the new FlotGraph. 4.0b1 (2012-05-29) - UI fixes: graphs load automatically again; workspace item paddings/margins; jqueryui buttons commented out as they conflict with bootstrap’s css. - Upgraded sentry client to raven. - Updated configchecker. - Commented line 413 in jquery-ui-1.8.5.custom.css to remove conflicing (with Twitter Bootstrap) class .ui-button-text-only .ui-button-text [Gijs Nijholt] - Fixed some interaction issues with modal and non-modal login form. - Restored accordion behavior and improved leftbar styling. 4.0a2 (2012-05-18) - Fixed google maps (which would be invisible) by removing max-width from bootstrap’s css. 4.0a1 (2012-05-18) - Add zettingen icon (copied from demo site) - Merged reinout-bootstrap branch (“the deltaportaal layout”). - Using compiled css/js instead of less/coffee. - Using smaller logo. - Added source distribution of twitter-bootstrap. You need node.js and its package manager npm installed to install lessc and uglify-js (only needed if you need to rebuild twitter-bootstrap). - Changed icon padding to accommodate for two columns in Chrome. - Fixed several styling issues. - Making the popup compatible. - Added sphinx setup for documentation generation. 3.16 (2012-05-10) - Added 1 new ap icon. - Remove protovis. Not generally used. And it is superseded by . 3.15 (2012-04-13) - A missing comma at the end of colorpicker.js broke the demo site. It really did. This blockbuster release adds one. 3.14 (2012-04-13) - Updated Openlayers to 2.11. 3.13 (2012-03-20) - Added user to the context of the template that renders application icons, so that it is possible to make them depend on the currently logged in user. 3.12 (2012-02-16) - Added two icons. 3.11 (2012-01-17) - Made breadcrumbs configurable - Added helper functions for breadcrumbs to application screens 3.10 (2012-01-04) - Changed confusing breadcrumbs into a simple “home” link. 3.9 (2011-12-12) - Fix bug where Ajax calls failed because they didn’t have a CSRF cookie. 3.8.1 (2011-12-08) - Fix bug where loginform didn’t redirect. 3.8 (2011-12-07) - Added narrowcasting.png icon as on heerhugowaard sites. 3.7.1 (2011-11-28) - Fix incorrect syntax in lizard.js. 3.7 (2011-11-08) - Added live: true to tipsy tooltips so that elements created later can also get tooltips 3.6 (2011-10-28) - Swapped order of datatable and colorpicker in the js list as django-compressor chokes on them a bit. - Made debugmode_urlpatterns() more robust. It crashed without MEDIA_URL and MEDIA_ROOT settings in the settings.py - Improved i18n and tipsy tooltips. 3.5 (2011-10-19) - Using django-staticfiles’ urls instead of django’s build-in contrib.staticfiles’. This works with “runserver” but fails with “run_gunicorn” (if you enabled gunicorn in your project). - Added experimental table sorter javascript. - Print improvements (hiding openlayers controls, for instance). - Moved from company-internal svn to github: . 3.4 (2011-09-23) - Renamed media/ directory into static/ as that’s django-staticfiles’ sane default now. - Added ‘i18n’ management command for easier translation. - Added config checks for i18n settings now that default strings slowly become English instead of the Dutch we’ve been implicitly expecting… - Added translation markers + Dutch translations for several strings. 3.3 (2011-09-05) - Added optional sentry setup. - Re-did login view as a class based view. - Fixed the problem that the print of the web page showed a progress icon instead of a graphs (ticket 3180). 3.2 (2011-08-30) - Added short_timedelta template filter. - Added ViewContextMixin mixin class for class based views that adds {‘view’: self} to your view’s context dict. This should be all you need to have in your context. 3.1.2 (2011-08-29) - Fixed debugmode_urlpatterns checker. 3.1.1 (2011-08-29) - Adding checker that warns if the debugmode_urlpatterns isn’t being imported. 3.1 (2011-08-29) - TracebackLoggingMiddleware isn’t needed anymore, so the config checker now tells you that if you still have it in your MIDDLEWARE_CLASSES. - Switched off sql statement logging by default. - Added url patterns for showing static/ and media/ files in debug mode. Use it by importing debugmode_urlpatterns from lizard_ui.urls and calling urlpatterns += debugmode_urlpatterns(). 3.0 (2011-08-19) - Added javascript-based csrf-for-ajax fix suggested in - Adjusted for Django 1.3. Note that this is now also a dependency! Upgrading will be slightly harder. Run bin/django check_config to check your config afterwards. See the README for more how-to-change information. 2.1.6 (2011-08-10) - Added projecten.png, oppervlaktewater.png, grondwater.png, riolering.png. 2.1.5 (2011-08-01) - Added ApplicationScreen.crumb. - Added oevers.png. 2.1.4 (2011-07-28) - Removed tipsy code specific for lizard-map (reference to #transparency-slider). - Moved tipsy code into setUpTipsy(). 2.1.3 (2011-07-12) - Removed console.log. 2.1.2 (2011-07-12) - Rewritten stretchOneSidebarbox: the old one used to stretch big first and then shrink to the correct size. The problem was that the scroll focus for large lists would change. #3030. 2.1.1 (2011-06-30) - Added option google_tracking_code in realbase. 2.1 (2011-06-29) - Updated favicon.ico to lizard. - Added ‘play’ icon. 2.0 (2011-06-22) - Fixed logo (it was slightly to high). 1.70 (2011-06-22) - Newer lizard logo (without the gray background as that conflicts with our own gray gradient), but that’s ok for now. - More app icons with shadows. 1.69 (2011-06-21) - Made popups more consistent (shadow color and size). 1.68 (2011-06-17) - Fixed .gif image that was a wrong file type. 1.67 (2011-06-16) - Fixed #2882: changed css to make some parts overflow: auto. 1.66 (2011-06-16) - Added error message when next accordion pane fails to load. 1.65 (2011-06-10) - Added reloadLocalizedGraphs() in addition to reloadGraphs() to reload only graphs inside a certain div. (Used in lizard-map popups with tabs). - Added Tipsy (Facebook/Github-style tooltips) - Added buttons.css (from) - Some repeatable backgrounds. (from) - Some icons from, added/implemented seperately. (TODO: integrate properly in sprite.png and the stylesheet of silk) - OpenLayers ‘Dark’ theme. - Re-exported several icon PNG’s (meldingen, kaarten) with an alphachannel drop-shadow. - Added extra field to ApplicationScreen model. (description, for display in tipsy tooltips) - Centered the icons in the ‘iphonesque’ app-screen. - Added inset drop-shadows to the app-screen. - Changed the app-screen font to helvetica-light. (TODO: Try out Google Webfonts instead) - Changed gray H2 bars’ bevel to a higher contrast, expressing more depth. - Aligned lizard logo to the outmost left. - Added tooltips to several interface elements. - Improved appearance of the breadcrumb. (TODO: position is still a bit awkward?) - Changed OpenLayers javascript + css so that the layer chooser’s background color matches the rest of the dark theme. 1.64 (2011-06-01) - Changed accordion behaviour. All titles are refreshed, but we don’t refresh all pane contents anymore: only the new one. This makes sure trees stay expanded. And it reduces re-rendering time for big trees. And we theoretically don’t need to send over all the panes’ data in case that’s prohibitive for performance. 1.63 (2011-05-30) - Removed relative positioning on #portal-tabs. See ticket #2827. - Reverted my changes made to .sidebarbox-action-icon in changeset:21174. Even added 1px extra to better vertically align workspace items. See ticket #2750 for screenshots. - Added a extra class name for save_form. - Bigger portal-tabs with rounded corners. - Corrected text-align of wrong-login. - “Log in” and “Log uit” links have the same cursor: they were different and “Log uit” had an illogical one, viz. cursor:text. 1.62 (2011-05-18) - Fixed vertical location of workspaceitem icons that aren’t part of a header. 1.61 (2011-05-17) - Fixing menubar at 2em height to keep longer content from overflowing the bar. - Added favicon image in media/lizard_ui/favicon.ico. So if you want a different favicon in your project, place an updated icon in your site’s media/lizardui/ folder. 1.60 (2011-05-06) - Changed CSS of .workspace (#2659). - Added five custom icons. (Gijs, req. by Dave) - Downgraded to jQuery 1.5.1 due to IE8 bug in 1.5.2. See See 1.59 (2011-04-28) - Deleted ‘Copyright @ Nelen …’ text. 1.58 (2011-04-27) - Added dacom icon. - Updated tabs css (needed for lizard-map >= 1.71). 1.57 (2011-04-20) - Added new flooding icon flooding2.png. - Updated OpenLayers from 2.8 to 2.10. - Jslint lizard.js. 1.56 (2011-04-14) - Updated Lizard logo. - Added lizard_ui/tabs.css. - Updated jQuery from 1.4.2 to 1.5.2, jQuery UI from 1.8.2 to 1.8.11, jQueryTools from 1.2.2 to 1.2.5. Treeview from 1.4 to 1.4.1. - Added css class for progress animation image 1.55 (2011-04-05) - Added 3di icon. - Added Waterbalance icon. 1.54 (2011-03-18) - Removed width: 100% css for .auto-inserted. It works fine without it. Before the image was slightly scaled horizontally. - Added possibility for a double-height item in the divideVerticalSpaceEqually() method. Just add a “double-vertical-item” class instead of “vertical-item” to the item you want to give double the height. 1.53 (2011-03-09) - Removed setUpWorkspaceAcceptableButtons. The button is now added when a workspace-acceptable is clicked (lizard-map 1.58 and higher). - Adding error message when a “replace-with-image” image is loaded and there’s an error. Instead of an ever-spinning “loading…” icon. 1.52 (2011-02-23) - Centered the progress animation. - Added data-src to progress animation (for debugging purposes). 1.51 (2011-02-15) - Added progress animation to vertical-item / img-use-my-size / replace-with-image. 1.50 (2011-02-15) - Added icons dike and controlnext. 1.36 (2011-02-15) - Added application screens and icons support: added models and views. 1.35 (2011-02-02) - Refactored the window.resize function in lizard.js [Gijs]. 1.34 (2011-02-01) - Added breadcrumbs example. - Added new breadcrumbs method. See examples. - Added protovis library. - Added support for portal-tabs, see also the examples page. 1.33 (2011-01-24) - Removed preventDefault in logout function. 1.32 (2011-01-20) - Still trying to fix logout bug. 1.31 (2011-01-20) - Fixed logout bug. 1.30 (2011-01-20) - Added turtle app icon. - After logging out one goes back to “/”. - Improved login function. - Added (empty) login screen with redirect option. 1.29 (2011-01-13) - Added to workspace acceptable button. 1.28 (2011-01-12) - Added setUpWorkspaceAcceptableButtons in lizard.js. The function is in lizard-ui because setUpAccordion needs the function as well. 1.27 (2010-12-08) 1.26 (2010-12-06) - Added default 500 and 404 pages. 1.25 (2010-12-01) - Added custom templatetag dutch_timedelta. - Moved tooltip css from lizard_map to here. - Add optional description to tree snippet. 1.24 (2010-11-24) - Added css class action-icon. 1.23 (2010-11-11) - (Re-)initializes tooltips when loading accordion. - Added setUpTooltips() in lizard.js. 1.22 (2010-11-09) - Updated accordion: when an item is clicked, all panes and headers are updated. 1.21 (2010-10-15) - Fix “apple” icon height to 80px. 1.20 (2010-10-15) - Fixed IE7 print problem. - Added exception-logging middleware. - Added app_icons. - Added sidebar and sidebarbox css entries. - Added tree_snippet.html template for creating trees. 1.19 (2010-09-27) - Fixed float problem for IE in login popup. - Fixing visibility of “restore from print view” icon in IE. 1.18 (2010-09-27) - Added automatic print button that also allows you to expand the collapsed-for-printing view again. - Tables now print with a grid and proper left/center/right alignment. - Links don’t print anymore (at least, their url isn’t appended anymore to the link text when printing). 1.17 (2010-09-22) - Add colorpicker js library. - Added createcoverage command. 1.16 (2010-09-08) - Added more tests. - Small layout tweak for popup box. 1.15 (2010-09-03) - Added utility templatetags. 1.14 (2010-08-30) - Importing json via django now. 1.13 (2010-08-30) - Bugfix simplejson. 1.12 (2010-08-27) - Small adjustments to support lizard-map’s new graph popup. (A better separation of lizard-ui and lizard-map is needed later on: after the deadlines :-) ). 1.11 (2010-08-26) - Styled the login form including proper “enter” behaviour and first-field-gets-focus handling. 1.10 (2010-08-26) - Moved some css styling from lizard-map to lizard-ui. - Added initial login support + forms. You need to add lizard-ui’s urls.py to yours if you want to use it. - Better drag/drop visual feedback. 1.8 (2010-08-18) - Javascript syntax fix: added two semicolons and removed another. 1.7 (2010-07-15) - Make “replace-with-image” clickable by using “data-href-click” property. - Add ol.forms css. 1.6 (2010-07-06) - Image replacement looks at “use-my-size” class instead of use-my-width/height. - Added javascript “printPage()” function that prints a webpage that at least doesn’t flow over the right hand side of the physical paper page. Printing uses a combination of a custom print stylesheet and blueprint’s print stylesheet. Printing definitively isn’t perfect yet, but at least usable. Note: you should refresh or resize the page after printing to get the full width again. 1.5 (2010-07-01) - Added generic automatic image resizing (replacing a generic “a href” with an image with the same src as the href and then figuring out the height/width and passing that along as a GET parameter and as attributes on the img tag. - Fixed resize timer by having a global variable for it. - Calculating hiddenStuffHeight (currently: only the date popup hidden div) only once: before the date popup has been opened.. Fixes the bug that you’d get a large empty space at the bottom of the screen. 1.4.1 (2010-06-25) - Updated TODO list. 1.4 (2010-06-25) - We’re now on the python package index, hurray! - Updated package metadata. - Big README documentation update. 1.3 (2010-06-23) - Added graph reloading on sidebar collapse/expand. - UI css fixes (overflow:hidden in a couple of places to prevent scrollbars in corner cases, for instance). 1.2 (2010-06-22) - Floating the main content area now and giving it the proper width with javascript. This makes the layout in IE more reliable. - The main body has “overflow: hidden” to get rid of scrollbars once and for all: scrollbars sometimes occur when there’s a small layout bug. A scrollbar takes up space, so the main content float is pushed down. We have an assumption of a single page without scrolling, so hiding scrollbars is perfectly fine. (The main area itself can have scrollbars for textual content). 1.1 (2010-06-18) - IE tweaks. 1.0 (2010-06-17) - Fixed javascript code with jslint. - Added django-compressor for javascript and css compression and combination. You’ll need to add the configuration in to your settings and add “compressor” to your installed apps. - Switched to a separate “javascript” and “css” block instead of the site-head-extras, head-extras and so. Be sure to add {{super.block}} when you override the blocks. 0.12 (2010-06-11) - Upgraded to jqueryui 1.8.2 (from 1.8.1). - Removed jqueryui’s tab component as it conflicts with jquerytools’ implementation. Jquerytools’ implementation is way friendlier to our existing sidebar css. 0.11 (2010-06-08) - Added direct support for a jquery tree. We already contained the base treeview javascript, so lizard-ui was a logical place for setting it up. 0.10 (2010-06-07) - Added fillSidebar() alias for stretchOneSidebarBox(). - Splitted title block in sitetitle/subtitle as that’s a common occurrence. 0.9 (2010-06-03) - Using jquery’s live() for “late binding” of events to elements added later through javascript. Saves some couple of lines. 0.8 (2010-06-01) - Added generic accordion handling for the sidebar. Including ajaxy loading. 0.7 (2010-05-18) - Added jquerytools for accordeon behaviour in sidebar. - Layout fixes, mostly for the sidebar. Also fix for the datepicker-placed div at the bottom. - Update to jquery-ui 1.8.1. 0.6 (2010-04-28) - Added collapsible sidebar. - Changed css framework from yui to blueprint: more understandable. The reason for yui was that it had a 100%-width layout. We’re now building up the layout (grid-wise) ourselves due to the collapsible sidebar, so switching back to blueprint is now possible. - Changed layout to match Dirk-Jan’s latest screenshots. 0.5 (2010-04-13) - Layout improvements. - Added documentation (just mount our urls!). - Removed separate icons, leaving only the sprite’d icons. - Added jqueryui. Including it automatically. It also means extjs isn’t included automatically anymore. - Sidebar width is 300px instead of 180px. 0.4 (2010-03-16) - Added extjs javascript library. - Added javascript and css for dividing the vertical space equally. 0.3.1 (2010-03-05) - Bugfix: removed sample breadcrumb content from the template. 0.3 (2010-03-05) - Added openlayers 2.8. - Added famfamfam silk icon set. - Added background to menubar, footer and body. - Removed blueprint and added the YUI css framework. 0.2 (2010-02-12) - Nested our templates in templates/lizard_ui instead of directly in templates. We’re well-behaved now! 0.1 (2010-02-12) - Added lizardbase.html template as base for a lizard user interface. - Added django-staticfiles as a dependency for managing css and javascript resources. - Added blueprint css framework. - Initial structure created by nensskel. 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/lizard-ui/
CC-MAIN-2018-34
refinedweb
5,372
62.34
21 March 2012 20:02 [Source: ICIS news] HOUSTON (ICIS)--Proposed April increases from a third ?xml:namespace> Arkema announced its plan to raise That news followed plans recently announced by BASF and Dow Chemical to raise their April prices by 5 cents/lb and 10 cents/lb, respectively. All three producers cited higher raw-material costs as the rationale, with BASF also attributing the need for the increases to rising freight and energy costs. Customers were already apprehensive about the first two April initiatives coming on the heels of substantial March increases of 12 cents/lb. That gain took acrylic acid contracts to $1.24-$1.29/lb, as assessed by ICIS. Several customers said passing along those increased costs downstream would be very difficult amid flat year-on-year demand and ample supply. Others, however, were more optimistic, suggesting the spring coatings season would continue to be soft but marginally better than last year. The lowest of the three price-hike proposals was the only palatable initiative because of the 5% March increase in propylene values, sources said. February feedstock chemical-grade propylene (CGP) had jumped by 30% from January largely because of a surge in spot propylene
http://www.icis.com/Articles/2012/03/21/9543825/arkema-proposes-5-8-centlb-hike-for-us-april-acrylates.html
CC-MAIN-2014-15
refinedweb
200
61.16
So, what’s the agenda?What is Instrumentation? What is debugging and tracing? How can we implement debugging and tracing in ASP.NET ? How do we view the results of debug and trace?So can we see a quick sample of how tracing information can be viewed?What if we want to enable tracing in all pages?Is it possible to do silent tracing, rather than displaying on the browser? How do I persist the instrumented information? There is too much noise can we only see information which we need? All the above methodologies are for web, how can we do tracing for windows? Can we emit different types of trace events like critical, warning, error etc? Can we control what kind of information can be routed? How can switch off instrumentation? It would great if we can summarize? ReferencesSource code This video talks about Debugging, Tracing and Instrumentation Diagnosing a software application is an art and this art has to be more skillful when you go on production. In development environment you have the complete VS IDE tool so the diagnosing becomes much easier. On production environment as a best practice you do not install visual studio IDE. So on production it’s like fighting with the lion without a knife. This article has a three point agenda.• We will first start with understanding some basic vocabularies like debug, trace and instrumentation.• Once we understand the vocabularies we will see how to use the trace attribute to tracing in ASP.NET. We will also understand some drawbacks of the same.• We will then try to remove those drawbacks using the full tracing framework which comes as a part of “system.diagnostic” namespace. In tracing framework we will try to understand trace object , switches and listeners.You can watch my .NET interview questions videos on various sections like WCF, Silver light, LINQ, WPF, Design patterns, Entity framework etc. Debugging application is not just about pressing F 10 or F 11 and watching “add watch windows” using visual studio IDE. Debugging becomes pretty complex on production environments where the project is deployed in a release mode and you need to figure out till what point the code ran and when did it crash. The worst part is you are enjoying your sleep at home and suddenly someone calls up and says, “Hey! the application crashed in production”.If your application is well planned with proper instrumentation you can just say the person to view the event viewer or a log file for further details and you can give the solution on the phone itself.So defining instrumentation in short, it’s the ability of the application to monitor execution path at critical points to do debugging and measure performance. We would like to enable application instrumentation in two situations while you are doing development and while your application is in production. When you monitor application execution and performance in development stage is termed as “Debugging” and when you do in deployed environment it’s termed as ‘Tracing’. Debugging and tracing can be implemented by importing ‘System.Diagnostic’ namespace and by calling ‘Debug’ and ‘Trace’ methods as shown in the below code. In the below code we are tracking critical execution points like page load and button click. protected void Page_Load(object sender, EventArgs e) { Debug.Write("Debug :- The page is loaded\n"); Trace.Write("Trace :- The page is loaded\n"); } protected void Button1_Click(object sender, EventArgs e) { Debug.Write("Debug :- Button is clicked\n"); Trace.Write("Trace :- Button is clicked\n"); } As said previously debug is meant for enabling instrumentation in development phase while tracing helps during execution. During development VS IDE tool is the best medium of viewing debug information and during execution the mediums can be a browser, event viewers, file system etc.In order to see debug information execute the project, click on debug, windows and click on output menu as shown in the below figure. You should be able to see the output information in output windows as shown in the below figure. As debug code is not shipped in production you will not be able to see the debug information while your application is go live. As said previously tracing information is seen when you execute the project in production mode or go live mode. Tracing information can be viewed by on various mediums:-• By the user interface ( Web browser or the windows UI)• Event viewer• Log file, format can be XML, CSV etc.• In ASP.NET you can also view by using Trace.axd A quick and dirty way of seeing tracing information is by going to the ASPX front code and put trace=true in the ‘Page’ attribute. <%@ Page Language="C#" AutoEventWireup="true" trace="true" CodeBehind="Default.aspx.cs" Inherits="WebTracing._Default" %> Once you have done the same you should be able to see tracing information as shown in the below figure. With trace enabled as true it also displays lot of other things like different page events , session data , hidden field data , http headers etc. I have circled the custom information which we have written using the ‘Trace’ object. If you want to enable tracing in all pages, you need to enable trace in the ‘web.config’ file as shown in the below code snippet. <system.web> <trace enabled="true" pageOutput="true" requestLimit="40" localOnly="false"/> </system.web> In actual production it will not be a good idea to enable the trace using the above two methodologies as the end user can view your tracing information on the browser. So the next logical question is how we silently trace the same.In order to background silent tracing we need to go to the web.config file and in the trace tag enter pageoutput=false. By setting “pageoutput” to false we say the trace engines do not send messages to browser and collect them in memory. <system.web> <trace enabled="true" pageOutput="false" requestLimit="40" localOnly="false"/> </system.web> This in memory stored instrumentation data can be viewed using Trace.axd by typing url . Below is a sample screen shot which shows how the data looks. If you click on the view details you can see the tracing information. When we instrument using debug attribute either using page or AXD extension they are not persisted. In other words they are displayed on the browser temporarily. Most of the times we would like to persist the information in a file, event viewer etc so that we can later see the history for proper diagnosis. We need to enable the ‘writetoDiagnosticsTrace’ attribute to true. When this attribute is set to true the information is sent to a listener. <trace enabled="true" requestLimit="10" localOnly="false" writeToDiagnosticsTrace="true" pageOutput="false"/> You can then define various types of listeners like text file listener, event viewer etc. Below is a sample code snippet of how the listeners actually look. So the ASP.NET tracing engine will emit diagnosis information which will be then caught and routed to the proper source by the listener. <system.diagnostics> <trace autoflush="true"> <listeners> <clear/> <add name="textwriterListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="c:\outfile.txt" traceOutputOptions="ProcessId, DateTime"/> </listeners> </trace> </system.diagnostics> Below is a simple snapshot of how instrumented data is captured. When we use the trace attribute it emits out all the events of the page. Sometimes these events can hinder your diagnosis. If you want to eliminate all ASP.NET events and just concentrate on your message then we need to add a source. We need to then write the messages on the source and the source will redirect the same to the trace listeners. In order to define a source go to your web.config and in the “system.diagnostics’ tag enter the “source’ tag as shown in the below code snippet. In the below code snippet we have defined the source name as “myTraceSource”. Inside the source we can define various listeners. <system.diagnostics> <sources> <source name="myTraceSource" switchName="mySwitch" switchType="System.Diagnostics.SourceSwitch"> <listeners> <!-… Define all your listeners in this place ..> </listeners> </source> </sources> </system.diagnostics> Below is a complete sample code snippet with listeners defined inside the source. <system.diagnostics> <sources> <source name="myTraceSource" switchName="mySwitch" switchType="System.Diagnostics.SourceSwitch"> <listeners> <clear/> <add name="textwriterListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="c:\outfile.txt" traceOutputOptions="ProcessId, DateTime"/> </listeners> </source> </sources> </system.diagnostics> In order to send messages to the trace source using C# code first we need to import namespace “System.Diagnostics” as shown in the below code snippet. using System.Diagnostics; Once the namespace is imported we can then send messages on any event by creating the “TraceSource” object and calling “TraceEvent” as shown in the below code snippet. TraceSource obj = new TraceSource("myTraceSource"); obj.TraceEvent(TraceEventType.Error, 0, "This is a error message"); obj.Close(); It’s the same way define the source and listeners in your app.config file, create the tracesource object and call traceevent method to write the same to the listeners. We would like to emit different kind of messages from the application like critical messages, error message or just information. The types of messages can be defined by using “TraceEventType” enum as shown in the below code snippet. obj.TraceEvent(TraceEventType.Critical, 0, "This is a critical message"); obj.TraceEvent(TraceEventType.Warning, 0, "This is a simple warning message"); obj.TraceEvent(TraceEventType.Error, 0, "This is a error message"); obj.TraceEvent(TraceEventType.Information, 0, "Simple information message"); obj.TraceEvent(TraceEventType.Verbose, 0, "Detail Verbose message"); Sometime we would like to control the kind of diagnosis information we see. This can be achieved by using the switch tag in config file. <system.diagnostics> .... .... .... <switches> <add name="mySwitch" value="1"/> </switches> </system.diagnostics> You can define various values depending on what kind of diagnose information you want to record. Value Type of message Critical = 1 Fatal error or application crash. Error = 2 Recoverable error. Warning = 4 Noncritical problem. Information = 8 Informational message. Verbose = 16 Debugging trace. Start = 256 Starting of a logical operation. Suspend = 1024 Suspension of a logical operation. Stop = 512 Stopping of a logical operation. Resume = 2048 Resumption of a logical operation. Transfer = 4096 Changing of correlation identity. You can then attach the switch to the source. <source name="myTraceSource" switchName="mySwitch" switchType="System.Diagnostics.SourceSwitch"> Set the switch value to zero. Summarizing ASP.Net or windows application emits tracing information to the trace source; these messages can be controlled by switches and sent to various sources (file, event viewer, xml etc) which are defined using trace listeners. Below figure summarizes the complete tracing framework visually. 15 Seconds Tracing in .NET and Implementing Your Own Trace Listeners BCL Team Blog A Tracing Primer - Part I [Mike Rousos] Cutting Edge A Provider-Based Service for ASP.NET Tracing How to Configure Trace Switches Viewing diagnostics trace info in an ASP.NET Website - Alex Thissen Weblog Build 1.15.10.1971 Walkthrough Integrating ASP.NET Tracing with System.Diagnostics Tracing With the article we have also provided the source. The source code demonstrates:-• Trace attribute• Enabling trace using web.config file• Tracing in windows application Trace listeners, switch and trace source. Download source code from
http://www.codeproject.com/Articles/149251/Debugging-Tracing-and-Instrumentation-in-NET-and-A?fid=1606388&df=90&mpp=10&sort=Position&spc=None&select=4039496&tid=3988953
CC-MAIN-2013-48
refinedweb
1,863
50.43
in reply to Re: Re: A Perl aptitude test in thread A Perl aptitude test An interesting variation on the theme might be to ask when they would consider not using strict. my $namespace = \%GMPN::Database::Table::; my %inject = ( pre_insert => sub { ... }, pre_update => sub { ... }, ); for my $subpkg (qw[org user group foo bar]) { my ($method, $code); $namespace->{"$subpkg::"}->{$method} = $code while ($method, $code) = each %inject; } [download] Makeshifts last the longest.. Short answer: Extremely rarely. Slightly longer answer: If my application ran/tested cleanly with use strict, but the operational requirements were such that disabling it allowed those ORs to be met without further modification, when they were not met when it was in force. Supplimentary question: Under what circumstances might this scenario be so? My answer: I have yet to encounter one, but if I did, I would consider the option. So, I suppose, implicit in this story is that, for now, I wouldn't not use strict; unless it was required.. Yes No Other opinion (please explain) Results (100 votes), past polls
http://www.perlmonks.org/?node_id=255289
CC-MAIN-2015-40
refinedweb
172
61.36
Add a notify-signal action to a condition #include <ha/ham.h> ham_action_t *ham_action_notify_signal( ham_condition_t *chdl, const char *aname, int nd, pid_t topid, int signum, int code, int value, unsigned flags); ham_action_t *ham_action_notify_signal_node( ham_condition_t *chdl, const char *aname, const char *nodename, pid_t topid, int signum, int code, int value, unsigned flags); libham These functions add an action to a given condition. The action will deliver a signal notification to the process given in topid. The handle (chdl) is obtained either: or: The action is executed when the appropriate condition is triggered. You use the node descriptor (nd) to specify where in the network the recipient of the notification resides. The nd specifies the node identifier of the remote (or local) node to which the signal is targeted The nd specified is the node identifier of the remote node at the time the call is made. Use the ham_action_notify_signal_node() function when a nodename is used to specify a remote HAM instead of a node identifier (nd). The ham_action_notify_signal_node() function takes as a parameter a fully qualified node name (FQNN) The signal in signum with the given value will be delivered to the process pid on node nd. This can also be used to terminate processes by sending them appropriate signals like SIGTERM, SIGKILL etc. to a condition, or NULL if an error occurred (errno is set). The connection to the HAM is invalid. This happens when the process that opened the connection (using ham_connect()) and the process that's calling ham_action_notify_signal() aren't the same. In addition to the above errors, the HAM returns any error it encounters while servicing this request.
http://www.qnx.com/developers/docs/7.0.0/com.qnx.doc.ham/topic/hamapi/ham_action_notify_signal.html
CC-MAIN-2018-09
refinedweb
271
50.67
First Look: InterSystems API Manager This First Look introduces you to InterSystems API Manager (IAM), explains how it works, and gets you started for exploring its capabilities on your own instance Opens in a new window. How Does InterSystems API Manager Work? InterSystems API Manager is a component of InterSystems IRIS® data platform that allows you to take advantage of microservices and APIs that are either exposed or consumed by your InterSystems IRIS applications. Acting as an API gateway between your InterSystems IRIS servers and applications, it gives you the ability to more effectively monitor and control the traffic of calls between your server-side APIs and your client-side applications. To learn more about InterSystems API Manager, you can view this overview video Opens in a new window. Try it! InterSystems API Manager is installed separately from an instance of InterSystems IRIS. To get your own installation kit of IAM, you can download it Opens in a new window from the InterSystems WRC Software Distribution site, or reach out to your InterSystems sales engineer. The installation package includes a script (iam-setup) for setting up IAM and connecting it with your instance of InterSystems IRIS. This exercise assumes that you have instances of InterSystems IRIS and IAM and have run the setup scripts to connect them. This exercise is shown using IAM version 2.3. Set up the REST API in InterSystems IRIS From the GitHub repository at, import the following into InterSystems IRIS: /cls/cmAPI includes three class files generated using the API management service as well as a coffeemaker object definition: impl.cls disp.cls spec.cls coffeemaker.cls To import, open the InterSystems IRIS Management Portal and navigate to the Classes page (System Explorer > Classes); if you are not in the USER namespace, use the selectors on the left to change to it, as shown in the following illustration: Select the four classes listed above and click Import. This imports the REST API into InterSystems IRIS, along with the corresponding classes that will be used by applications to access the set of coffeemakers stored in the database. /gbl/coffeemakers.gof. Import by going to the Management Portal and clicking Globals > Import > My Local Machine. Find coffeemakers.gof. Import to the schema User.cmAPI.coffeemaker. Next, set up a Web Application pointing to the REST classes you just imported. Web application layers provide an additional opportunity for customization and security. In the Management Portal, select System Administration > Security > Applications > Web Applications. Click Create New Web Application and fill out the following settings: Name: /rest/coffeemakerapp Namespace: USER Enable Application: selected Enable: REST Dispatch Class: cmAPI.disp Allowed Authentication Methods: Unauthenticated, Password Create a Service in IAM for your REST API As you saw in the IAM overview video, there are three major components at play within the IAM workflow — Consumers, Routes, and Services. Services in IAM are created for your APIs that exist within InterSystems IRIS. In this case, we will create a service for your Coffeemaker API. Your IAM package that you downloaded from the WRC also includes a script (iam-test) for setting up a sample service and route. If you ran the script, you will be able to view the test-iris service. We will be achieving a similar result, using the IAM portal, to add your Coffeemakers service. Start the IAM management portal by entering the URL for the portal specified in the iam-setup.sh script that started IAM. By default, the URL is: Select the default Workspace. If the default workspace is not visible and the management portal seems empty, it is possible that you did not enter the exact URL as defined by iam-setup.sh. Select Services in API Gateway and select New Service. Fill in the form as follows: Name: CoffeemakerService Select Add using Protocol, Host and Path Protocol: http Host: [insert the IP address of your InterSystems IRIS instance. To avoid DNS issues, use the numeric form of the IP address. ] Path: /rest/coffeemakerapp Port: [insert the webserver port of your instance, by default 52773, or if the instance is in a container, the host port you have mapped to the webserver port] Do not select “View 6 Advanced Fields”. Select Create. Once your service is created, you will be viewing the service and will need to create a route. Create a Route in IAM When you are viewing the service, select “Add a Route”. Fill in the form as follows: Sevice: this field is correctly initialized with the hexadecimal ID of the service. Name: can be left empty Protocols: http Hosts: can be left empty Methods: GET, POST, PUT, DELETE Paths: select “+ Add Path” and enter /rest/coffeemakerapp Headers: can be left empty HTTPS Redirect Status Code: 426 (this is the default) Tags: can be left empty Do not select “View 4 Advanced Fields”. Select Create. Once your route is created, you will test your route and service by making a simple API call from a REST client. Call Your API from a REST Client Using a REST client — Postman or Advanced REST Client from Google Chrome will work here — make a simple API call to your Coffeemakers API within InterSystems IRIS. To do this, create a request URL that includes the IP address and port number of your IAM instance, as well as the path of your service and the requested endpoint. Be sure to authorize your request with a username and password. An example is shown below; note that by default, IAM handles proxy requests on port 8000. For example: Once you have successfully made this call, you can navigate back to your IAM Dashboard to see the statistics and other information from the call that was made. From this dashboard, you can see a number of different sets of information that will help you with monitoring and controlling traffic between client applications and your services within InterSystems IRIS. Add a Rate Limiting Plugin Effectively monitoring your API traffic is beneficial, but only to the extent that you use that information to appropriately control and optimize your flow of traffic. IAM enables you to use a number of different plugins to boost your ability to control traffic flow between clients and APIs. In the IAM management portal, select Plugins in API Gateway and select New Plugin. In the Traffic Control category, find the Rate Limiting plugin and select Enable. On the configuration screen for this plugin: Select Scoped. In Service select the CoffeeMakerService. Leave most of the other fields with their default value, but set Config.Limit By to Service and Config.Minute to 5. This will limit all consumers to 5 calls per minute to all routes in the service. Select Create. You can test this rate limiting plugin by returning to your REST client and making sample calls. After the client exceeds the limit, it will get a 429 return error with an “API rate limit exceeded” message Add Your REST Specification to IAM The best practice approach for REST development is specification-first, so it is likely that you already have your REST specification on hand. For this exercise, you can use the swagger_100419.json file in the spec directory when you downloaded the FirstLook-IAM repository from github. You can also download the JSON specification directly from the spec folder in the GitHub repository Opens in a new window For more information on documenting and managing your REST API specifications, read Discovering and Documenting REST APIs Opens in a new window in Creating REST Services. Once downloaded, you are able to add your specification to IAM: From the IAM management portal, select the Workspaces tab and select the default workspace. Select View for the CoffeemakerService service. In the Documents area (towards the bottom of the panel) select Add a document to this service. Click in the file selector text box below Or upload a new spec instead... and then select the swagger_100419.json file that you downloaded. You can now view the OpenAPI specification for the CoffeemakerService. External developers can also access this specification, which allows them to develop REST calls to it. The “Try it Out” option will not work because the curl command does not specify the correct server. If the default dev portal is not set up, select Set up Dev Portal. If the default Dev Portal is disabled, select Enable Developer Portal. It may take a few minutes to set up. Learn More About InterSystems API Manager InterSystems provides several resources to learn more about IAM: API Manager Introduction Opens in a new window (presentation) What is InterSystems API Manager? Opens in a new window (video) IAM Guide Opens in a new window (documentation) If you want more details on how to develop the CoffeemakerService REST service, see First Look: Developing REST Interfaces in InterSystems Products.
https://docs.intersystems.com/healthconnectlatest/csp/docbook/DocBook.UI.Page.cls?KEY=AFL_IAM
CC-MAIN-2021-25
refinedweb
1,470
51.48
Subject: Re: [boost] [BCP] Script for global renaming Boost Namespace From: Bjørn Roald (bjorn_at_[hidden]) Date: 2009-05-30 14:11:11 Hi, Interesting, I did something similar as a C++ patch to bcp some years ago. I think there is interest for such a feature, especially if you are willing to maintain it on regular basis. I had a quick look at your code, it locks like you do similar stuff to what I did. I have not tested it. If we do expect all possible users to have Python installed, it may be nice to use python for this. But how do you propose to integrate with bcp? There should be some discussions on the list if you are interested. Google "bcp replace_namespace". -- Bjørn Roald On Saturday 30 May 2009 10:55:25 am Artyom wrote: > Hello, > > Some updates: > ------------- > > 1. Added copyright - Boost License. > 2. Some more regression tests passed, some code cleanup > > Questions: > ---------- > > 1. How can I submit it as an addon to BCP utility? > 2. Have anybody tested it, I'd like to see if there any problems, > especially on Windows platform -- I hadn't tested it there. > > > Thanks > Artyom > > P.S.: The source is there > > --- On Mon, 5/25/09, Artyom <artyomtnk_at_[hidden]> wrote: > > From: Artyom <artyomtnk_at_[hidden]> > > Subject: [BCP] Script for global renaming Boost Namespace > > To: boost_at_[hidden] > > Date: Monday, May 25, 2009, 11:14 AM > > Hello, > > > > Today Boost does not provide any backward binary > > compatibility. This > > makes big problems in shipping 3rd part libraries that > > depend on Boost > > because library user must use the same version of Boost as > > that 3rd > > part library was compiled with. > > > > The problem is become even more critical for ELF platforms > > (UNIXes) > > where all symbols are exported by default. > > > > I had written a small Python script that switches boost > > namespace > > to other, allowing 3rd part project include it without > > collisions > > with primary Boost namespace. > > > > The script passes over the source tree of boost and changes > > each > > include path from <boost/foo/bar.hpp> too > > <newnamespace/foo/bar.hpp> > > and renames all macros and identifiers from > > some_BOOST_something to > > some_NEWNAMESPACE_something and some_boost_something to > > some_newnamespace_something. > > > > It does not touch comments (copyright) and strings unless > > the string > > is in form "boost/.*" which is usually some reference for > > include. > > > > I've run this script on the 1.39 version of boost and > > successfully build full boost release and run some of > > regression tests > > like Boost.Asio, Boost.Regex, Boost.Function and others, > > > > The source code is available at: > > > > > > You run it as: > > > > ./rename /path/to/boost/source > > new_namespace_name > > > > It renames all macros and namespaces to new namespace, and > > renames > > main include directory to new_namespace_na,e. > > > > Few points: > > > > 1. It is only alpha version script, I just want to see > > feedback and > > proposals > > 2. I do not update build scripts. I assume that each > > library that > > tryes to import its own version of Boost > > would provide its own > > build system. > > 3. The build scripts should be updated differently because > > they have > > different syntax and grammar. The > > required changes are to > > fix different build defines > > > > Please, give feedback proposal. If there someone who is > > familiar > > with Boost.Build systems can actually help, this would be > > very good. > > > > Today there is a big problem with working with different > > versions of > > Boost. It should be solved. > > > > I think this script may be a valuable addition to > > Boost.BCP utility > > that allows extracting a subset of boost for integration in > > 3rd part > > tools and libraries. > > > > Thanks, > > Artyom > > > > > > > > _______________________________________________ > Unsubscribe & other changes: > Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2009/05/152054.php
CC-MAIN-2020-29
refinedweb
605
66.54
Sometimes it is worth writing a up a script that does something of use only once; there are times these this could be a need to generate a bunch of scripts which actually only differ by some predefined set of data. Usually you'll want to write such a program so that the data drives the execution. However this can be fairly challenging if the script language isn't really meant for such a task, an example of this might be SQL. At which point it may be desirable to have a script connect to the database and build a transaction; this may not be an option if security prevents running/installing the needed script, allowing only for someone to run SQL. Due to the feature set of D building a simple replacement script generator isn't too challenging. And if you need to do more complicated text processing to get at specific data, I personally find D to decent processing options even if they tend to be a little more complicated since the tools for text processing tend to emphasize a single pass causing multi-pass processing to be a little more work. Here is a program that does a basic generation driven by CSV data for a simple string template. dlang import std.algorithm; import std.csv; import std.exception; import std.file; import std.path; import std.range; import std.stdio; immutable replacementString = `Some data [ReplaceThis] and [ReplaceThat]`; auto replacementData = `23,"fishes that eat" 42,eagles`; struct Data { string number; string comment; } void main(string[] args) { version(FileInput) { enforce(args.length == 2, "Usage: ./" ~ args[0].baseName ~ " FileName"); auto replacementData = readText(args[1]); } foreach(record; csvReader!Data(replacementData)) writeln(replacementString.replac } string replaceWithData(string str, Data d) { return str.replace("[ReplaceThis]", d.number) .replace("[ReplaceThat]", d.comment); } This script can then be run with rdmd scriptName.d, and I provided a version to show loading data from a file which is rdmd -version=FileInput scriptName.d dataFile.csv. Conclusion This is not a statement of D being the most concise means to accomplish this particular task, or that another language like Python, Ruby, PHP, etc. aren't fully capable of performing the same task just as or more easily. What I'd like to get across is that such a simple task is pretty straight forward in a language providing machine accesses such as pointers.
https://he-the-great.livejournal.com/55852.html
CC-MAIN-2018-34
refinedweb
397
55.64
Code Generation Templates¶ Orchard Core Templates uses dotnet new template configurations for creating new websites, themes and modules from the command shell. More information about dotnet new can be found at Installing the Orchard CMS templates¶ Once the .NET Core SDK has been installed, type the following command to install the templates for creating Orchard Core web applications: dotnet new -i OrchardCore.ProjectTemplates::1.0.0-rc2-* This will use the most stable release of Orchard Core. In order to use the latest dev branch of Orchard Core, the following command can be used: dotnet new -i OrchardCore.ProjectTemplates::1.0.0-rc2-* --nuget-source Create a new website¶ From Command Shell (automated way)¶ Generate an Orchard Cms Web Application¶ dotnet new occms The above command will use the default options. You can pass the following CLI parameters to setup options Orchard Core Cms Web App (C#) Author: Orchard Project Options: -lo|--logger Configures the logger component. nlog - Configures NLog as the logger component. serilog - Configures Serilog as the logger component. none - Do not use a logger. Default: nlog -ov|--orchard-version Specifies which version of Orchard Core packages to use. string - Optional Default: 1.0.0-rc2 Logging can be ignored with this command: dotnet new occms --logger none Generate a modular ASP.NET MVC Core Web Application¶ dotnet new ocmvc From Visual Studio (manual way)¶ Fire up Visual Studio, create a new solution file ( .sln) by creating a new ASP.NET Core Web Application : Now that we created a new Web Application we need to add proper dependencies so that this new Web Application be targeted as an Orchard Core application. Note If you want to use the preview packages, configure the OrchardCore Preview url in your Package sources Finally we will need to register Orchard CMS service in our Startup.cs file like this : using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; namespace MyNewWebsite { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit public void ConfigureServices(IServiceCollection services) { services.AddOrchardCms(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseStaticFiles(); app.UseOrchardCore(); } } } Create a new CMS module¶ New module from Command Shell (automated way)¶ Module commands¶ dotnet new ocmodulecms The above command will use the default options. You can pass the following CLI parameters to setup options Orchard Core Module (C#) Author: Orchard Project Options: -A|--AddPart Add dependency injection for part in Startup.cs. If PartName is not provided, default name will be used bool - Optional Default: false / (*) true -P|--PartName Add all files required for a part string - Optional Default: MyTest -ov|--orchard-version Specifies which version of Orchard Core packages to use. string - Optional Default: 1.0.0-rc2 dotnet new ocmodulecms -n ModuleName.OrchardCore dotnet new ocmodulecms -n ModuleName.OrchardCore --AddPart true dotnet new ocmodulecms -n ModuleName.OrchardCore --AddPart true --PartName Test Note Part is appended automatically to the end of the supplied PartName New module from Visual Studio (manual way)¶ Fire up Visual Studio, open Orchard Core solution file ( .sln), select OrchardCore.Modules folder, right click and select "add → new project" and create a new .NET Standard Class Library: For marking this new Class Library as an Orchard Module we will now need to reference OrchardCore.Module.Targets NuGet package. Note If you want to use the preview packages, configure the OrchardCore Preview url in your Package sources Each of these *.Targets NuGet packages are used to mark a Class Library as a specific Orchard Core functionality. OrchardCore.Module.Targets is the one we are interested in for now. We will mark our new Class Library as a module by adding OrchardCore.Module.Targets as a dependency. For doing so you will need to right click on MyModule.OrchardCore project and select "Manage NuGet Packages" option. To find the packages in Nuget Package Manager you will need to check "include prerelease" and make sure you have Orchard Core feed that we added earlier selected. Once you have found it, click on the Install button on the right panel next to Version : Latest prerelease x.x.x.x Once done, your new module will look like this : For Orchard Core to identify this module it will now require a Manifest.cs file. Here is an example of that file: using OrchardCore.Modules.Manifest; [assembly: Module( Name = "TemplateModule.OrchardCore", Author = "The Orchard Team", Website = "", Version = "0.0.1", Description = "Template module." )] For this module to start, we now will need to add a Startup.cs file to our new module. See this file as an example: OrchardCore.Templates.Cms.Module/Startup.cs Last step is to add our new module to the OrchardCore.Cms.Web project as a reference for including it as part as our website modules. After that, you should be all set for starting building your custom module. You can refer to our template module for examples of what's basically needed normally. Create a new theme¶ New theme From Command Shell (automated way)¶ Theme commands¶ dotnet new octheme -n "ThemeName.OrchardCore" New theme from Visual Studio (manual way)¶ Should be the same procedure as with modules, but instead we need to reference OrchardCore.Theme.Targets, and the Manifest.cs file differs slightly: using OrchardCore.DisplayManagement.Manifest; [assembly: Theme( Name = "TemplateTheme.OrchardCore", Author = "The Orchard Team", Website = "", Version = "0.0.1", Description = "The TemplateTheme." )]
https://docs.orchardcore.net/en/dev/docs/getting-started/templates/
CC-MAIN-2020-29
refinedweb
931
50.12
I have a simple mod_python handler that works correctly for web browsers, but fetching with wget gives a 500 Internal Server Error. This is using the latest mod_python 2.7 under Apache 1.3.37. I can't see any problem. The only different I see is perhaps HTTP/1.1 and HTTP/1.0 ? You can test the live url here, Here is the handler code... def handler(req): path = req.uri.split("/", 2)[-1] if path == "magic.html": req.content_type = "text/html" req.status = apache.OK req.send_http_header() req.write("<html><body>It is ok</body></html>") return apache.OK # ... other urls handled afterwards On the client end, these are the headers I get back. Date:Sat, 14 Jul 2007 20:16:07 GMT Server:Apache Keep-Alive:timeout=5, max=50 Connection:Keep-Alive Transfer-Encoding:chunked Content-Type:text/html Here are the requests I see in the server log. I see a difference between HTTP/1.1 and HTTP/1.0 ? 76.168.41.58 - - [14/Jul/2007:16:16:08 -0400] "GET /iCream/magic.html HTTP/1.1" - 46 "-" "Mozilla/5.0 (X11; U; Linux i686; en; rv:1.8.1.4) Gecko/20061201 Epiphany/2.18 Firefox/2.0.0.4 (Ubuntu-feisty)" 76.168.41.58 - - [14/Jul/2007:16:10:41 -0400] "GET /iCream/magic.html HTTP/1.0" - 34 "-" "Wget/1.10.2" I'm not seeing anything show up in the server error logs, but it doesn't look like I'm getting the raw logs given to me.
http://modpython.org/pipermail/mod_python/2007-July/024005.html
CC-MAIN-2018-39
refinedweb
260
72.32
Subject: [Boost-announce] [typeindex v3.0] Peer review begins Mon 21st ends Wed 30th From: Niall Douglas (s_sourceforge_at_[hidden]) Date: 2014-04-20 14:14:13 Dear Boost, A second round of community review begins for proposed Boost.TypeIndex on Mon 21st, lasting ten days. I should apologise as it's my fault for starting another peer review straight after Boost.Align ends, however I was busy as Google Summer of Code admin until today, and I will be preparing to talk at C++ Now straight after this review ends. I hope that this doesn't affect the community's willingness to contribute to the review. Reminder of the report from the last TypeIndex v2.1 review: Reminder of the original peer review announcement: brary-acceptance-begins-ending-Thurs-21st-Nov-td4654788.html Source code: Github: Documentation: Changes in TypeIndex v3.0 since v2.1 (from my own review of it): 1. Documentation is hugely improved over v2.1, lots of side by side examples illustrating the differences and similarities. 2. You can now create your own custom type indices using an extensible framework. 3. boost::typeind::type_info now exports raw_name() and pretty_name() to maximise MSVC-GCC compatibility, and to solve point 1 but not point 2 in the v2.1 report. 4. The undefined behaviour trick used in v2.1 has been replaced with a cast via the placeholder type boost::typeind::detail::ctti_data which can be viewed in _index/ctti_type_index.hpp. There is an explanation in the comments there about this technique's compatibility with the C++ standard. 5. TypeIndex now defines everything in the boost::typeind namespace instead of the boost namespace. So: 1. What is your evaluation of the design? 2. What is your evaluation of the implementation? 3. What is your evaluation of the documentation? 4. What is your evaluation of the potential usefulness of the library? 5. Did you try to use the library? With what compiler? Did you have any problems? 6. How much effort did you put into your evaluation? A glance? A quick reading? In-depth study? 7. Are you knowledgeable about the problem domain? And finally, every review should answer this question: 8. Do you think the library should be accepted as a Boost library? Be sure to say this explicitly so that your other comments don't obscure your overall opinion. Thanks,
http://lists.boost.org/boost-announce/2014/04/0399.php
CC-MAIN-2015-06
refinedweb
393
60.21
03 January 2013 23:32 [Source: ICIS news] HOUSTON (ICIS)--Air Liquide has acquired Progressive Resources, a company that supplies liquid nitrogen to oil and gas services firms, the France-based company said on Thursday. Financial terms were not disclosed. The oil and gas industry uses bulk liquid nitrogen for well stimulation, pressure testing, drill stem testing, coil tubing operations and cleaning and jetting, Air Liquide said. Progressive Resources serves customers through five centres in ?xml:namespace> The acquisition is part of Air Liquide's larger strategy of expanding into the oil and gas industry. Air Liquide already supplies nitrogen and carbon dioxide to the sector, and it plans to build a plant in
http://www.icis.com/Articles/2013/01/03/9628351/Air-Liquide-acquires-US-oilfield-services-firm.html
CC-MAIN-2014-15
refinedweb
114
53
Opened 12 years ago Closed 12 years ago Last modified 12 years ago #9062 closed enhancement (fixed) Add support for toric lattices Description (last modified by ) Toric lattices are ZZn's with distinction of their roles (in the simplest case - standard dual lattices M and N). This patch is a part of the following series adding support for cones/fans and toric varieties to Sage: Prerequisites: #8675 - Remove AmbientSpace._constructor and fix consequences #8682 - Improve AlgebraicScheme_subscheme.__init__ and AmbientSpace._validate #8694 - Improve schemes printing and LaTeXing #8934 - Trivial bug in computing faces of non-full-dimensional lattice polytopes #8936 - Expose facet inequalities for lattice polytopes #8941 - _latex_ and origin for lattice polytopes Main patches adding new modules: #9062 - Add support for toric lattices #8986 - Add support for convex rational polyhedral cones #8987 - Add support for rational polyhedral fans #8988 - Add support for toric varieties #8989 - Add support for Fano toric varieties Attachments (4) Change History (17) comment:1 Changed 12 years ago by - Status changed from new to needs_work comment:2 Changed 12 years ago by - Cc vbraun added Changed 12 years ago by Fixed version. Changed 12 years ago by Apply this patch only. comment:3 Changed 12 years ago by It will probably work without other "prerequisites," but I tested it with them applied since all got positive review already and hopefully will be merged soon... comment:4 Changed 12 years ago by comment:5 Changed 12 years ago by - Status changed from needs_review to positive_review Very nice. I like it how the M/N lattice elements derive from Vector_integer_dense. Positive review. Applies to Sage 4.4.2. comment:6 Changed 12 years ago by - Reviewers set to vbraun comment:7 Changed 12 years ago by - Reviewers changed from vbraun to Volker Braun Thank you! (I think authors and reviewers should be listed with their full names rather than trac accounts, this simplifies the job of release managers.) comment:8 Changed 12 years ago by - Status changed from positive_review to needs_work While testing I found a heisenbug caused by this patch. If you run "make ptestlong", there is a failure in toric_lattice_element.pyx; but it works fine if you doctest just that file. The problem is this comparison function: def __cmp__(self, right): r""" [...] sage: cmp(n, 1) -1 """ c = cmp(type(self), type(right)) if c: return c The doctest is sensitively dependent on the exact memory locations of different classes, because cmp(type(self), type(right)) compares on memory addresses. I suggest changing the doctest to sage: n == 1 False which is much more robust. David Changed 12 years ago by Apply this patch over trac_9062_add_support_for_toric_lattices.patch comment:9 Changed 12 years ago by - Status changed from needs_work to needs_review Here's a tiny patch which makes the fix I suggested. comment:10 Changed 12 years ago by The same potential issue is in toric_lattice.py. Here is an updated patch that fixes this one, too. I think this is fine now, if you agree please set to "positive review". Changed 12 years ago by Updated patch comment:11 Changed 12 years ago by - Status changed from needs_review to positive_review Looks good to me. Apply trac_9062_add_support_for_toric_lattices.patch and trac_9062-cmp_fix.2.patch. comment:12 Changed 12 years ago by - Merged in set to sage-4.5.2.alpha0 - Resolution set to fixed - Status changed from positive_review to closed Looks good, I'll be happy to review the final version!
https://trac.sagemath.org/ticket/9062
CC-MAIN-2022-33
refinedweb
573
60.04
The third step in the Soundex algorithm is eliminating consecutive duplicate digits. What's the best way to do this? Here's the code we have so far, in soundex/stage2/soundex2c.py: digits2 = digits[0] for d in digits[1:]: if digits2[-1] != d: digits2 += d Here are the performance whether it's efficient to check digits[-1] each time through the loop. Are list indexes expensive? Would we be better off maintaining the last digit in a separate variable, and checking that instead? To answer this question, here is soundex/stage3/soundex3a.py: digits2 = '' last_digit = '' for d in digits: if d != last_digit: digits2 += d last_digit = d soundex3a.py does not run any faster than soundex2c.py, and may even be slightly slower (although it's not enough of a difference to say for sure): C:\samples\soundex\stage3>python soundex3a.py Woo W000 11.5346048171 Pilgrim P426 13.3950636184 Flingjingwaller F452 18.6108927252 Why isn't soundex3a.py faster? It turns out that list indexes in Python are extremely efficient. Repeatedly accessing digits2[-1] is no problem at all. On the other hand, manually maintaining the last seen digit in a separate variable means we have two variable assignments for each digit we're storing, which wipes out any small gains we might have gotten from eliminating the list lookup. Let's try something radically different. If it's possible to treat a string as a list of characters, it should be possible to use a list comprehension to iterate through the list. The problem is, the code needs access to the previous character in the list, and that's not easy to do with a straightforward list comprehension. However, it is possible to create a list of index numbers using the built-in range() function, and use those index numbers to progressively search through the list and pull out each character that is different from the previous character. That will give you a list of characters, and you can use the string method join() to reconstruct a string from that. Here is soundex/stage3/soundex3b.py: digits2 = "".join([digits[i] for i in range(len(digits)) if i == 0 or digits[i-1] != digits[i]]) Is this faster? In a word, no. C:\samples\soundex\stage3>python soundex3b.py Woo W000 14.2245271396 Pilgrim P426 17.8337165757 Flingjingwaller F452 25.9954005327 It's possible that the techniques so far as have been “string-centric”. Python can convert a string into a list of characters with a single command: list('abc') returns ['a', 'b', 'c']. Furthermore, lists can be modified in place very quickly. Instead of incrementally building a new list (or string) out of the source string, why not move elements around within a single list? Here is soundex/stage3/soundex3c.py, which modifies a list in place to remove consecutive duplicate elements: digits = list(source[0].upper() + source[1:].translate(charToSoundex)) i=0 for item in digits: if item==digits[i]: continue i+=1 digits[i]=item del digits[i+1:] digits2 = "".join(digits) Is this faster than soundex3a.py or soundex3b.py? No, in fact it's the slowest method yet: C:\samples\soundex\stage3>python soundex3c.py Woo W000 14.1662554878 Pilgrim P426 16.0397885765 Flingjingwaller F452 22.1789341942 We haven't made any progress here at all, except to try and rule out several “clever” techniques. The fastest code we've seen so far was the original, most straightforward method (soundex2c.py). Sometimes it doesn't pay to be clever. Example 18.5. Best Result So Far: soundex/stage2/soundex2c.py import string, re allChar = string.uppercase + string.lowercase charToSoundex = string.maketrans(allChar, "91239129922455912623919292" * 2) isOnlyChars = re.compile('^[A-Za-z]+$').search def soundex(source): if not isOnlyChars(source): return "0000" digits = source[0].upper() + source[1:].translate(charToSoundex) digits2 = digits[0] for d in digits[1:]: if digits2[-1] != d: digits2 += d digits3 = re.sub('9', '', digits2) while len(digits3) < 4: digits3 += "0"())
http://docs.activestate.com/activepython/2.7/dip/performance_tuning/list_operations.html
CC-MAIN-2018-09
refinedweb
661
69.79
13 July 2011 04:40 [Source: ICIS news] SINGAPORE (ICIS)--Malaysia’s biodiesel exports will likely stay high this month, after surging in June, as sharp declines in feedstock crude palm oil (CPO) translated to lower prices of the green fuel, traders said on Wednesday. Demand for biodiesel, particularly from ?xml:namespace> In June, official data from the Malaysian Palm Oil Board (MPOB) showed that Meanwhile, June prices of feedstock CPO heavily declined from May. As at end-June, CPO prices stood at Malaysian ringgit (M$) 3,480/tonne ($1,149/tonne), down 11.2% from M$3,130/tonne in end-May, said a trader. CPO prices are expected to remain under pressure, as current strong production may lead to oversupply. At 03:00 GMT, CPO contract for August delivery was trading at M$3,070/tonne, data from ($1 = M$3
http://www.icis.com/Articles/2011/07/13/9476620/malaysia-biodiesel-exports-to-stay-high-as-cpo-values-remain-weak.html
CC-MAIN-2014-10
refinedweb
143
70.43
The Gradle Enterprise Gradle plugin enables integration with Gradle Enterprise and scans.gradle.com. Getting set up Version 3.1.1.1" } plugins { id("com.gradle.enterprise").version("3.1.1") } The plugin adds a gradleEnterprise {} extension to the settings script for configuring the plugin, and adds a buildScan {} extension extension to the root project. Either can be used to configure the plugin. For the remainder of this documentation, configuration examples use the buildScan {} extension in build scripts. In all cases, this configuration can be specified within the settings script by placing the configuration within the gradleEnterprise {} extension configuration. plugins { id "com.gradle.enterprise" version "3.1.1" } gradleEnterprise { buildScan { // plugin configuration } } plugins { id("com.gradle.enterprise").version("3.1.1") } gradleEnterprise { buildScan { // plugin configuration } } Gradle 5.x This version of Gradle uses com.gradle.build-scan as the plugin ID. The plugin must be applied to the root project of the build. plugins { id "com.gradle.build-scan" version "3.1.1" } plugins { id("com.gradle.build-scan").version("3.1.1") } The plugin adds a buildScan {} extension extension to the root project for configuring the plugin. Connecting to Gradle Enterprise To connect to a Gradle Enterprise instance, you must configure the location of the Gradle Enterprise server. buildScan { server = "" } buildScan {: buildScan { allowUntrustedServer = true } buildScan { adding the following configuration to your build. buildScan { termsOfServiceUrl = "" termsOfServiceAgree = "yes" }: buildScan { publishAlways() }: buildScan { publishAlwaysIf(System.getenv("CI")) } buildScan { publishAlwaysIf(!System.getenv("CI").isNullOrEmpty()) } You can use the other options in the same way. If you want to configure several things based on a set of criteria, you can use an if condition instead: buildScan { if (System.getenv("CI")) { publishAlways() tag "CI" } } buildScan { if (!System.getenv("CI").isNullOrEmpty()) { publishAlways() tag("CI") } }. buildScan { captureTaskInputFiles = true }+) You can easily include extra custom information in your build scans in the form of tags, links and values. This is a very powerful mechanism for capturing and sharing information that is important to your build and development process. This information can be anything you like. You can tag all builds run by your continuous integration tool with a CI tag. You can capture the name of the environment that the build published to as a value. You can link to the source revision for the build in an online tool such as GitHub. The possibilities are endless. You can see how the custom data appears in figure 2: Gradle Enterprise allows listing and searching across all of the build scans in the system. You can find and filter build scans by tags and custom values, in addition to project name, outcome and other properties. In figure 3, for example, we are filtering for all build scans that have the tag : buildScan { if (System.getenv("CI")) { tag "CI" } else { tag "Local" } tag System.getProperty("os.name") }. Note that the order in which you declare the tags doesn’t affect the build scan view. They are displayed in alphabetical order, with any all-caps labels displayed before the rest. Adding links Builds rarely live in isolation. Where does the project source live? Is there online documentation for the project? Where can you find the project"s issue tracker? If these exist and have a URL, you can add them to the build scan. They can be added at build time via the link() method: buildScan { link "VCS", "{System.getProperty("vcs.branch")}" } becomes a hyperlink that anyone viewing the build scan can follow. Adding custom values Some information just isn’t useful without context. What does "1G" mean? You might guess that it represents 1 gigabyte, but of what? It’s only when you attach the label "Max heap size for build" that it makes sense. The same applies to git commit IDs, for example, which could be interpreted as some other checksum without a suitable label. Custom values are designed for these cases that require context. They’re standard key-value pairs, in which the key is a string label of your choosing and the values are also strings, often evaluated from the build environment. They can be added at build time via the value() method: buildScan { value "Build Number", project.buildNumber }: buildScan { buildFinished { value "Disk usage (output dir)", buildDir.directorySize().toString() } } ... buildScan { buildFinished { BuildResult result -> if (result.failure) { value "Failed with", result.failure.message } } } buildFinished() buildScan { background { def commitId = "git rev-parse --verify HEAD".execute().text.trim() value "Git Commit ID", commitId } } background()to capture an expensive custom value import java.io.ByteArrayOutputStream ... also allows you to inject any form of custom data through the use of specially named system properties. This can help you keep your build files clean of too much environment-specific information that may not be relevant to most of the users of the build. These system properties take the following forms, depending on whether you want to inject aI Build Type=QA_Build" This feature is particularly useful for continuous integration builds as you can typically easily configure your CI tool to specify system properties for a build. It’s even common for CI tools to be able to inject system properties into a build that are interpolated with information from the CI system, such as build number. $ . ... buildScan { buildScanPublished { PublishedBuildScan scan -> file("scan-journal.log") << "${new Date()} - ${scan.buildScanId} - ${scan.buildScanUri}\n" } } import java.util.Date .... buildScan { obfuscation { username { name -> name.reverse() } } } buildScan { obfuscation { username { name -> name.reverse() } } } buildScan { obfuscation { hostname { host -> host.collect { character -> Character.getNumericValue(character as char) }.join("-") } } } buildScan { obfuscation { hostname { host -> host.collect { character -> Character.getNumericValue(character as char) }.join("-") } } } buildScan { obfuscation { ipAddresses { addresses -> addresses.collect { address -> "0.0.0.0"} } } }: { publishAlways() server = "" // { "publishAlways"() setProperty("server", "") // other configuration } } scans.gradle.com The following init script example enables any Gradle 5.0 or later build to integrate with scans.gradle.com: { termsOfServiceUrl = "" termsOfServiceAgree = "yes" // { setProperty("termsOfServiceUrl", "") setProperty("termsOfServiceAgree", "yes") // other configuration } }.1.1" } plugins { id("com.gradle.enterprise").version("3.1.1") } Any buildScan {} configuration can remain where it is, or be moved to the settings file inside a gradleEnterprise {} block. Please see the Gradle 6.x section above for more information. gradleEnterprise { buildScan { server = "" } } gradleEnterprise { buildScan { server = "" } } and other things of this nature. Some more general environmental information is also captured. This includes your Java version, operating system, hardware, country, timezone and other things of this nature. Notably, the actual source code being built and the output artifacts are not captured. However, error messages emitted by compilers or errors in tests may reveal aspects of the source code. Listing The list below details the notable information captured by the Project names and structure - Executed tests (using Gradle’s JVM Test task) - - Network downloads (performed by Gradle) Gradle Daemon operational data (e.g. start time, build count) Build cache configuration Gradle lifecycle callbacks Access Build scans published to a Gradle Enterprise installation are viewable by all users that can reach the server. Gradle Enterprise provides a search interface for discovering and finding individual build scans. Build scans published to scans.gradle.com are viewable by anyone with the link assigned when publishing the build scan. Links to individual build scans are not discoverable and cannot be guessed, but may be shared. Appendix C: Plugin release history 3.1.1 - 13th December 2019 Improved help message when authentication is required for build scan publishing Excessive logging in build scans from use of artifact transforms is suppressed Mitigation if slow local host name resolution on macOS 3.1 - 25th November 2019 Support access key provisioning Change response mime types from 'text/*' to 'application/*' Fixed events ordering in special circumstances 3.0 - 16th October 2019 Renamed to Gradle Enterprise plugin Compatibility with Gradle 6 2.4.2 - 10th September 2019 Added support for username, hostname and ip-addresses obfuscation 2.4.1 - 20th August 2019 More reliable capture of logging output Handle overlapping IDs in dependency resolution More stable end-of-build handling 2.4 - 8th August 2019 Added support for capturing all dependency selection reasons Added support for capturing dependency variant details Added support for capturing rich dependency version constraint information Added support for capturing dependency platform and constraint details 2.3 - 3rd May 2019 Added support for plugin composite builds Added support for continuous builds Added support for capturing the details of annotation processors used during Java compilation 2.2.1 - 1st March 2019 More reliable capture of task input files for buildSrc 2.2 - 27th February 2019 Capture collection callback executions Capture deprecation traces more compactly General performance improvements in task inputs capturing 2.1 - 7th December 2018 This version is compatible with Java 8 and later Capture task input files 2.0.2 - 6th November 2018 This version is compatible with Gradle 5.0 and later Removed deprecated -Dscan and -Dscan=false system property, use --scan and --no-scan, respectively Avoid memory leak when connecting to HTTPS server with often changing build classpath 2.0.1 - 29th October 2018 This version was released for compatibility with Gradle 5.0-rc-1, but is not compatible with subsequent Gradle 5.0 releases. Please use version 2.0.2 or later instead. 2.0 - 17th October 2018 This version was released for compatibility with Gradle 5.0-milestone-1, but is not compatible with subsequent Gradle 5.0 releases. Please use version 2.0.2 or later instead. 1.16 - 21st August 2018 Capture repositories and source repository for a resolved module component Capture individual lifecycle listeners and attribute to code unit application Capture Gradle build script compilation details Capture deprecated usage notifications Capture source of included build 1.15.2 - 10th August 2018 Fix for Kotlin script build caching 1.15.1 - 5th July 2018 Fix for potential classloader leak when using buildScan.background() 1.15 - 3rd July 2018 Support capturing expensive custom values/tags/links in the background Task buildScanPublishPrevious is created lazily Fixed error when using included build as plugin and in main build 1.14 - 12th June 2018 Further performance improvements Removal of unnecessary implicit continuous build scan suppression Capture information on lifecycle hook execution 1.13.4 - 18th May 2018 Improved performance of build scan plugin, particularly during configuration time 1.13.3 - 14th May 2018 Fix incompatibility with new continuous build features in Gradle 4.7 1.13.2 - 8th May 2018 Do not show build scan publishing information when --quiet or -q argument is present Retry likely temporary network errors while publishing a build scan 1.13.1 - 10th Apr 2018 Improve performance of plugin data capture. 1.13 - 28th Mar 2018 Capture console log from beginning of the build. 1.12.1 - 13th Feb 2018 Fix message when terms of service are declined. 1.12 - 12th Feb 2018 Capture build scans for composite builds. Capture original task execution time. 1.11 - 5th Dec 2017 Capture test execution, dependency resolution, and project structure data from the beginning of the build. Improve performance of plugin data capture. Enhance Gradle version compatibility check. 1.10.3 - 23th Nov 2017 Fix incompatibility with Android Plugin for Gradle 3.0.0. 1.10.2 - 7th Nov 2017 Fix incompatibility with development builds of Gradle 4.4. 1.10.1 - 27th Oct 2017 Fix incompatibility with development builds of Gradle 4.4. 1.10 - 17th Oct 2017 Detect when build was run by a single-use daemon. Capture default charset of the JVM that executed the build. Capture build path of each project. 1.9.1 - 10th Oct 2017 Prompt user for license agreement acceptance, if needed. Capture console output and network activity until closer to the end of the build. Limit the number and length of captured custom tags, custom links, and custom values. 1.9 - 15th Aug 2017 Capture task graph calculation. Capture more fine-grained project configuration. Capture build cache interactions including artifact packing and unpacking. 1.8 - 15th June 2017 - 29th May 2017 Fix incompatibility with development builds of Gradle 4.0. 1.7.3 - 19th May 2017 Fix incompatibility with development builds of Gradle 4.0. 1.7.2 - 17th May 2017 Fix incompatibility with development builds of Gradle 4.0. 1.7.1 - 3rd May 2017 Fix incompatibility with development builds of Gradle 4.0. 1.7 - 24th April 2017 Fix NPE when specifying buildScan "server" URL without schema or host. Overlapping output is captured as a non-cacheable reason for a task. 1.6 - 10th February 2017 Capture whether task outputs are cacheable and the reason if they are not. Capture network download activities. 1.5 - 11st January 2017 Capture whether tasks were skipped due to having no source. Capture whether tasks are lifecycle tasks (i.e. no actions). Add "mailto:" link as custom build scan links. 1.4 - 21st December 2016 Performance improvements when executing many tests. 1.3 - 15th November 2016 Capture tags, links and/or values via conventional system properties. Reduced payload size when publishing large dependency graphs. 1.2 - 12th October 2016 Capture tags, links and/or values at the end of the build via buildScan.buildFinished(). 1.1.1 - 20th September 2016 Fixed issues with creating build scans for some projects via Android Studio. 1.1 - 17th September 2016 - 23rd June 2016 Initial release.
https://docs.gradle.com/enterprise/gradle-plugin/
CC-MAIN-2020-05
refinedweb
2,185
50.63
I According to this Link javaFX 8u45 spinner, can be styled in numerous ways via style class. I do know how to do it by code. For example: spinner.getStyleClass().add(Spinner.STYLE_CLASS_SPLIT_ARROWS_HORIZONTAL); or, spinner.getStyleClass().add("split- If I want a scene to be 500 by 500... does that make the stage 550 by 550 or does it make the scene 450 by 450 and the stage 500 by 500? What is the width and length of the extra title bar space above the scene that include the close, restore, and mi I tried to run ninepatch jar from sdk folder using command java -jar ninepatch.jar in terminal. My bad, nothing happened. I tried various web based ninepatch editors like romannurik which won't serve my purpose. How can I run ninepatch jar in Ubuntu Here is my java model class - CustomerProperty.java package model; import java.io.InputStream; public class CustomerProperty { public CustomerProperty() { } public int propertyid; public String name; public String phone; public String occupation; pub Can any one help me to create a line graph like the image in android. --------------Solutions------------- Using AChartEngine you can add an image, after making slight modifications in the AchartEngine - XYMultipleSeriesRenderer class. Along with X A Is it possible to launch google maps activity and pass several latitude/longitude variables so several locations are mapped inside the map? I am able to show one location with this code, but how do I add more parameters? String uri = String.format(Lo building a Sudoku game. I have drawn a grid so far and programmed the selection of a field, but my chosen picture for selection does not appear. My Class for the selector is: package com.brendenbunker; import javax.swing.*; public class Selectio I tried everything but not able to find any solution. I used iText, flying-saucer for converting HTML to PDF, but not able to do so. import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import I'm new on encryption. I'm programming 2 app one for Android (JAVA) and other for Windows (C#), so I need to encrypted messages between them over TCP. I wonder if someone could tell if what I thought is OK or there is a better and easy way. So I thou I am using HP Fortify to measure code quality of my java code. HP Fortify is reporting SQL Injection error on PreparedStatement stmt = connnection.prepareStatement(queryString); so how to resolve this? --------------Solutions------------- if you don' i wanted to connect to mysql from java code where mysql is in another system. i have created a user in another machine "nilotpal". Other machine address is 192.168.92.93. I am able to ping to this machine. where am i missing?? can someone help?! I am new with this language. I have some rows in employee table and the bean class is Employee. I have fetched one record Employee employee=this.employeeDaoImpl.getEmployeeObject(employeeId); This is the CONTROLLER @Transactional @RequestMapping(valu I am developing as rest WS in whcih i want to set the system property. String AUTH_CONF = ""; System.setProperty("java.security.auth.login.config", AUTH_CONF); when i am going
http://www.dskims.com/category/java/10/
CC-MAIN-2019-13
refinedweb
534
60.21
Daisuke Oyama Faculty of Economics, University of Tokyo This notebook demonstrates the functionalities of the game_theory module. import numpy as np from quantecon.game_theory import NormalFormGame, Player An $N$-player normal form game is a triplet $g = (I, (A_i)_{i \in I}, (u_i)_{i \in I})$ where where $i+j$ is understood modulo $N$. Note that we adopt the convention that the $0$-th argument of the payoff function $u_i$ is player $i$'s own action and the $j$-th argument, $j = 1, \ldots, N-1$, is player ($i+j$)'s action (modulo $N$). In our module, a normal form game and a player are represented by the classes_0, \ldots, n_{N-1}, N)$ whose $(a_0, \ldots, a_{N-1})$-entry contains an array of the $N$ payoff values for the action profile $(a_0, \ldots, a_{N-1})$. As an example, consider the following game ("Matching Pennies"): $ \begin{bmatrix} 1, -1 & -1, 1 \\ -1, 1 & 1, -1 \end{bmatrix} $ matching_pennies_bimatrix = [[(1, -1), (-1, 1)], [(-1, 1), (1, -1)]] g_MP = NormalFormGame(matching_pennies_bimatrix) print(g_MP) 2-player NormalFormGame with payoff profile array: [[[ 1, -1], [-1, 1]], [[-1, 1], [ 1, -1]]] print(g_MP.players[0]) # Player instance for player 0 Player in a 2-player normal form game with payoff array: [[ 1, -1], [-1, 1]] print(g_MP.players[1]) # Player instance for player 1 Player in a 2-player normal form game with payoff array: [[-1, 1], [ 1, -1]] g_MP.players[0].payoff_array # Player 0's payoff array array([[ 1, -1], [-1, 1]]) g_MP.players[1].payoff_array # Player 1's payoff array array([[-1, 1], [ 1, -1]]) g_MP[0, 0] # payoff profile for action profile (0, 0) array([ 1, -1])) print(g_Coo) 2-player NormalFormGame with payoff profile array: [[[4, 4], [0, 3]], [[3, 0], [2, 2]]] g_Coo.players[0].payoff_array # Player 0's payoff array array([[4, 0], [3, 2]]) g_Coo.players[1].payoff_array # Player 1's payoff array array([) print(g_RPS) 2-player NormalFormGame with payoff profile array: [[[ 0, 0], [-1, 1], [ 1, -1]], [[ 1, -1], [ 0, 0], [-1, 1]], [[-1, 1], [ 1, -1], [ 0, 0]]][0, 0] = 1, 1 g_PD[0, 1] = -2, 3 g_PD[1, 0] = 3, -2 g_PD[1, 1] = 0, 0 print(g_PD) 2-player NormalFormGame with payoff profile array: [[[ 1., 1.], [-2., 3.]], [[ 3., -2.], [0 = Player([[3, 1], [0, 2]]) player1 = Player([[2, 0], [1, 3]]) Beware that in payoff_array[h, k], h refers to the player's own action, while k refers to the opponent player's action. player0.payoff_array array([[3, 1], [0, 2]]) player1.payoff_array array([[2, 0], [1, 3]]) Passing an array of Player instances is the third way to create a NormalFormGame instance: g_BoS = NormalFormGame((player0, player1)) print(g_BoS) 2-player NormalFormGame with payoff profile array: [[[3, 2], [1, 1]], [[0, 0], [2, 3]]] The game_theory module also supports games with more than two players._0 + \cdots + q_{N. from quantecon import cartesian def cournot(a, c, N, q_grid): """ Create a `NormalFormGame` instance for the symmetric N-player Cournot game with linear inverse demand a - Q and constant marginal cost c. Parameters ---------- a : scalar Intercept of the demand curve c : scalar Common constant marginal cost N : scalar(int) Number of firms q_grid : array_like(scalar) Array containing the set of possible quantities Returns ------- NormalFormGame NormalFormGame instance representing the Cournot game """ q_grid = np.asarray(q_grid) payoff_array = \ cartesian([q_grid]*N).sum(axis=-1).reshape([len(q_grid)]*N) * (-1) + \ (a - c) payoff_array *= q_grid.reshape([len(q_grid)] + [1]*(N-1)) payoff_array += 0 # To get rid of the minus sign of -0 player = Player(payoff_array) return NormalFormGame([player for i in range(N)])) print(g_Cou) 3-player NormalFormGame with payoff profile array: [[[[300, 300, 300], [250, 250, 375]], [[250, 375, 250], [200, 300, 300]]], [[[375, 250, 250], [300, 200, 300]], [[300, 300, 200], [225, 225, 225]]]] print(g_Cou.players[0]) Player in a 3-player normal form game with payoff array: [[[300, 250], [250, 200]], [[375, 300], [300, 225]]] g_Cou.nums_actions (2, 2, 2) A Nash equilibrium of a normal form game is a profile of actions where the action of each player is a best response to the others'. The Player object has a method best_response. Consider the Matching Pennies game g_MP defined above. For example, player 0's best response to the opponent's action 1 is: g_MP.players[0].best_response(1) 1 Player 0's best responses to the opponent's mixed action [0.5, 0.5] (we know they are 0 and 1): # By default, returns the best response action with the smallest index g_MP.players[0].best_response([0.5, 0.5]) 0 # With tie_breaking='random', returns randomly one of the best responses g_MP.players[0].best_response([0.5, 0.5], tie_breaking='random') # Try several times 0 # With tie_breaking=False, returns an array of all the best responses g_MP.players[0].best_response([0.5, 0.5], tie_breaking=False) array([0, 1]) For this game, we know that ([0.5, 0.5], [0.5, 0.5]) is a (unique) Nash equilibrium. g_MP.is_nash(([0.5, 0.5], [0.5, 0.5])) True g_MP.is_nash((0, 0)) False g_MP.is_nash((0, [0.5, 0.5])) False For small games, we can find pure action Nash equilibria by brute force. def find_pure_nash_brute(g): """ Find all pure Nash equilibria of a normal form game by brute force. Parameters ---------- g : NormalFormGame """ NEs = [] for a in np.ndindex(*g.nums_actions): if g.is_nash(a): NEs.append(a) num_NEs = len(NEs) if num_NEs == 0: msg = 'no pure Nash equilibrium' elif num_NEs == 1: msg = '1 pure Nash equilibrium:\n{0}'.format(NEs) else: msg = '{0} pure Nash equilibria:\n{1}'.format(num_NEs, NEs) print('The game has ' + msg) Matching Pennies: find_pure_nash_brute(g_MP) The game has no pure Nash equilibrium Coordination game: find_pure_nash_brute(g_Coo) The game has 2 pure Nash equilibria: [(0, 0), (1, 1)] Rock-Paper-Scissors: find_pure_nash_brute(g_RPS) The game has no pure Nash equilibrium Battle of the Sexes: find_pure_nash_brute(g_BoS) The game has 2 pure Nash equilibria: [(0, 0), (1, 1)] Prisoners' Dillema: find_pure_nash_brute(g_PD) The game has 1 pure Nash equilibrium: [(1, 1)] Cournot game: find_pure_nash_brute(g_Cou) The game has 1 pure Nash equilibrium: [(1, 1, 1)] In some games, such as "supermodular games" and "potential games", the process of sequential best responses converges to a Nash equilibrium. Here's a script to find one pure Nash equilibrium by sequential best response, if it converges. def sequential_best_response(g, init_actions=None, tie_breaking='smallest', verbose=True): """ Find a pure Nash equilibrium of a normal form game by sequential best response. Parameters ---------- g : NormalFormGame init_actions : array_like(int), optional(default=[0, ..., 0]) The initial action profile. tie_breaking : {'smallest', 'random'}, optional(default='smallest') verbose: bool, optional(default=True) If True, print the intermediate process. """ N = g.N # Number of players a = np.empty(N, dtype=int) # Action profile if init_actions is None: init_actions = [0] * N a[:] = init_actions if verbose: print('init_actions: {0}'.format(a)) new_a = np.empty(N, dtype=int) max_iter = np.prod(g.nums_actions) for t in range(max_iter): new_a[:] = a for i, player in enumerate(g.players): if N == 2: a_except_i = new_a[1-i] else: a_except_i = new_a[np.arange(i+1, i+N) % N] new_a[i] = player.best_response(a_except_i, tie_breaking=tie_breaking) if verbose: print('player {0}: {1}'.format(i, new_a)) if np.array_equal(new_a, a): return a else: a[:] = new_a print('No pure Nash equilibrium found') return None A Cournot game with linear demand is known to be a potential game, for which sequential best response converges to a Nash equilibrium. Let us try a bigger instance: a, c = 80, 20 N = 3 q_grid = np.linspace(0, a-c, 13) # [0, 5, 10, ..., 60] g_Cou = cournot(a, c, N, q_grid) a_star = sequential_best_response(g_Cou) # By default, start with (0, 0, 0) print('Nash equilibrium indices: {0}'.format(a_star)) print('Nash equilibrium quantities: {0}'.format(q_grid[a_star])) init_actions: [0 0 0] player 0: [6 0 0] player 1: [6 3 0] player 2: [6 3 1] player 0: [4 3 1] player 1: [4 3 1] player 2: [4 3 2] player 0: [3 3 2] player 1: [3 3 2] player 2: [3 3 3] player 0: [3 3 3] player 1: [3 3 3] player 2: [3 3 3] Nash equilibrium indices: [3 3 3] Nash equilibrium quantities: [ 15. 15. 15.] # Start with the largest actions (12, 12, 12) sequential_best_response(g_Cou, init_actions=(12, 12, 12)) init_actions: [12 12 12] player 0: [ 0 12 12] player 1: [ 0 0 12] player 2: [0 0 6] player 0: [3 0 6] player 1: [3 1 6] player 2: [3 1 4] player 0: [3 1 4] player 1: [3 2 4] player 2: [3 2 3] player 0: [3 2 3] player 1: [3 3 3] player 2: [3 3 3] player 0: [3 3 3] player 1: [3 3 3] player 2: [3 3 3] array([3, 3, 3]) The limit action profile is indeed a Nash equilibrium: g_Cou.is_nash(a_star) True In fact, the game has other Nash equilibria (because of our choice of grid points and parameter values): find_pure_nash_brute(g_Cou) The game has 7 pure Nash equilibria: [(2, 3, 4), (2, 4, 3), (3, 2, 4), (3, 3, 3), (3, 4, 2), (4, 2, 3), (4, 3, 2)] Make it bigger: N = 4 q_grid = np.linspace(0, a-c, 61) # [0, 1, 2, ..., 60] g_Cou = cournot(a, c, N, q_grid) sequential_best_response(g_Cou) init_actions: [0 0 0 0] player 0: [30 0 0 0] player 1: [30 15 0 0] player 2: [30 15 7 0] player 3: [30 15 7 4] player 0: [17 15 7 4] player 1: [17 16 7 4] player 2: [17 16 11 4] player 3: [17 16 11 8] player 0: [12 16 11 8] player 1: [12 14 11 8] player 2: [12 14 13 8] player 3: [12 14 13 10] player 0: [11 14 13 10] player 1: [11 13 13 10] player 2: [11 13 13 10] player 3: [11 13 13 11] player 0: [11 13 13 11] player 1: [11 12 13 11] player 2: [11 12 13 11] player 3: [11 12 13 12] player 0: [11 12 13 12] player 1: [11 12 13 12] player 2: [11 12 12 12] player 3: [11 12 12 12] player 0: [12 12 12 12] player 1: [12 12 12 12] player 2: [12 12 12 12] player 3: [12 12 12 12] player 0: [12 12 12 12] player 1: [12 12 12 12] player 2: [12 12 12 12] player 3: [12 12 12 12] array([12, 12, 12, 12]) sequential_best_response(g_Cou, init_actions=(0, 0, 0, 30)) init_actions: [ 0 0 0 30] player 0: [15 0 0 30] player 1: [15 7 0 30] player 2: [15 7 4 30] player 3: [15 7 4 17] player 0: [16 7 4 17] player 1: [16 11 4 17] player 2: [16 11 8 17] player 3: [16 11 8 12] player 0: [14 11 8 12] player 1: [14 13 8 12] player 2: [14 13 10 12] player 3: [14 13 10 11] player 0: [13 13 10 11] player 1: [13 13 10 11] player 2: [13 13 11 11] player 3: [13 13 11 11] player 0: [12 13 11 11] player 1: [12 13 11 11] player 2: [12 13 12 11] player 3: [12 13 12 11] player 0: [12 13 12 11] player 1: [12 12 12 11] player 2: [12 12 12 11] player 3: [12 12 12 12] player 0: [12 12 12 12] player 1: [12 12 12 12] player 2: [12 12 12 12] player 3: [12 12 12 12] array([12, 12, 12, 12]) Sequential best response does not converge in all games: print(g_MP) # Matching Pennies 2-player NormalFormGame with payoff profile array: [[[ 1, -1], [-1, 1]], [[-1, 1], [ 1, -1]]] sequential_best_response(g_MP) init_actions: [0 0] player 0: [0 0] player 1: [0 1] player 0: [1 1] player 1: [1 0] player 0: [0 0] player 1: [0 1] player 0: [1 1] player 1: [1 0] No pure Nash equilibrium found
http://nbviewer.jupyter.org/github/QuantEcon/QuantEcon.notebooks/blob/master/game_theory_py.ipynb
CC-MAIN-2017-04
refinedweb
2,012
52.53
Introdu helping me settle into my new life in Barcelona. Meetup.com provides a platform for anybody to build a community around a topic of interest, scheduling events from casual drinks in a bar, hikes in the mountains or performing in a singing group. With meetup.com, you can "Find your people" by sharing your interests with others in your local community. This platform provides an interesting opportunity to explore which world cities have the most active users for any given topic, allowing us to find our ideal cities and perhaps learn a little about different cultures around the world. Fortunately, meetup.com provides a robust API to allow us to explore this dataset for ourselves. The Final Visualization The aim of this project is to build an interface to allow the user to explore various topics of interest and visualize the best cities for that unique grouping of topics. I've used my hometown of Calgary in the below example image with data science and spanish language as topics. The final visualization can be viewed here. Feel free to go play with it, the rest of this post outlines how to retrieve the data from meetup.com using it's API. The Build Meetup.com API Meetup.com has a very well documented API, and memebers of the community have built API wrappers for many popular programming languages. Python being my language of choice, I've utilized the Python meetup-api library for this project. To use the package, we first need to obtain an API key to be used as authentication for our client object. import meetup.api import configparser import time config = configparser.ConfigParser() config.read('secrets.ini') meetup_api_key = config.get('meetup', 'api_key') client = meetup.api.Client(meetup_api_key) What we need from the API is to iterate over all groups that exist on the platform, collect the topic tags that group organizers assign their group, and collect the member count for each group. The meetup.api python package provides a GET function to obtain a list of groups having certain input filter parameters. The request returns a results object with a list of groups and their respecitive data including topic keywords. groups = client.GetGroups(lat=51.0486, lon=-114.0708,radius=50,fields=['topics']) #example meetup API call with Calgary as center #GPS coords and 50 mile radius. Optional data #request to return each groups list of topics groups.results[1] 29/30 (10 seconds remaining) {'category': {'id': 2, 'name': 'career/business', 'shortname': 'career-business'}, 'city': 'Calgary', 'country': 'CA', 'created': 1038423812000, 'description': '<p><img src=""></p>\n<p><span><i><b>PLEASE READ BEFORE JOINING OUR GROUP</b> <br></i></span></p>\n<p><span>The Calgary Business Professionals Group ("CBP") is the premier business-related Meetup in the Calgary area. We cater to Calgary entrepreneurs.</span></p>\n<p><span>The CBP is all about forging strong relationships with no strings attached. </span></p>\n<p><span>We are not trying to sell you anything! </span></p>\n<p><span>Our strength is our membership (over 2000 members) and our events (we have hosted over 300).</span></p>\n<p><span>The CBP Meetup Group is one of the largest and longest running Meetup groups in Calgary (in existence since 2002). </span> </p>\n<p><b>Our events are invitation-only, private functions and are open to CBP Meetup Group members and their guests only.</b> <br></p>\n<p>Our events are free to attend (our breakfast event does require you to spend $10 minimum to support our venue).</p>\n<p>There are great food and drink specials at our "Beer and Wings" event, but you are on the hook for what you consume (our host venue runs individual tabs for all attendees). Please tip your server!</p>\n<p><span><b>In the interests of "good networking", we require ALL new members to include:</b></span></p>\n<p><span><b> (1) A recognizable photo (headshot or similar), NO ADVERTISING OR LOGOS!</b></span></p>\n<p><span><b>(2) BOTH your first AND last name on both your Meetup AND Group profiles</b></span></p>\n<p><span><b><i>Your application for membership will be rejected without this information</i></b></span></p>\n<p><span><b>In addition:</b></span></p>\n<p><strong>(3) We do not permit members of Multi-Level Marketing ("MLM") or other "Network Marketing" organizations to join this group. </strong></p>\n<p><strong>(4) We allow members of other networking groups to join, but PLEASE, do not recruit our members or promote your events at our functions. Doing so will result in removal from CBP.</strong> <br></p>\n<p><strong>(5) Please use Meetup\'s messaging function to communicate to follow members but selling or promoting your product or service in an unsolicited fashion is not permitted. Any violations of this policy will result in removal from the group. <br></strong></p>\n<p><span>We look forward to meeting you at one of our events.</span></p>\n<p><span>Yours in business and entrepreneurship;</span> <br></p>\n<p><b>Lisa Marie Genovese</b>, Organizer</p>\n<p><b>Sean Phillips</b>, Co-Organizer and Host of the monthly breakfast event</p>\n<p><b>Brad Celmainis</b>, Co-Organizer and Host of the monthly Beer and Wings event</p>\n<p><img src=""></p>\n<p> <br></p>', 'group_photo': {'highres_link': '', 'photo_id': 228822102, 'photo_link': '', 'thumb_link': ''}, 'id': 54766, 'join_mode': 'approval', 'lat': 51.04999923706055, 'link': '', 'lon': -114.08000183105469, 'members': 2071, 'name': 'Calgary Business Professionals Group', 'organizer': {'member_id': 13068793, 'name': 'Lisa Marie Genovese', 'photo': {'highres_link': '', 'photo_id': 246782615, 'photo_link': '', 'thumb_link': ''}}, 'rating': 4.47, 'state': 'AB', 'timezone': 'Canada/Mountain', 'topics': [{'id': 389, 'name': 'Small Business', 'urlkey': 'smallbiz'}, {'id': 1238, 'name': 'Marketing', 'urlkey': 'marketing'}, {'id': 3880, 'name': 'Professional Development', 'urlkey': 'prodev'}, {'id': 4422, 'name': 'Social Networking', 'urlkey': 'socialnetwork'}, {'id': 15405, 'name': 'Business Referral Networking', 'urlkey': 'business-referral-networking'}, {'id': 15720, 'name': 'Professional Networking', 'urlkey': 'professional-networking'}, {'id': 17325, 'name': 'Small Business Marketing Strategy', 'urlkey': 'small-business-marketing-strategy'}, {'id': 17635, 'name': 'Business Strategy', 'urlkey': 'business-strategy'}, {'id': 19882, 'name': 'Entrepreneurship', 'urlkey': 'entrepreneurship'}, {'id': 20060, 'name': 'Entrepreneur Networking', 'urlkey': 'business-entrepreneur-networking'}, {'id': 20743, 'name': 'Small Business Owners', 'urlkey': 'small-business-owners'}, {'id': 45636, 'name': 'Calgary Business', 'urlkey': 'calgary-business'}, {'id': 65792, 'name': 'B2B Networking', 'urlkey': 'b2b-networking'}, {'id': 72702, 'name': 'Calgary Entrepreneurs', 'urlkey': 'calgary-entrepreneurs'}], 'urlname': 'businessincalgary', 'utc_offset': -21600000, 'visibility': 'public_limited', 'who': 'Business Professionals'} The meetup.com API does not provide a clear way to access every group on the platform, as the design of the system is such that a user selects a center location to search from in a geographic radius to ensure users are recommended groups close to their desired location. One option to obtain all availible groups is to input an impossibly high radius to encompass the entire globe. groups = client.GetGroups(lat=51.0486, lon=-114.0708,radius=10000000000,fields=['topics']) groups.meta['total_count'] 28/30 (7 seconds remaining) 257973 Although this option is technically feasible, and as of today returns a total of 257,973 unique groups, the total time to make that single request is over a minute. The meetup.com API is limited to only return 200 results at a time, which would require over 1290 of these requests. To overcome the limit of 200 results, the API provides a page offset parameter to programmatically scroll through each page containing the next 200 groups. groups_per_page = 200 groups = client.GetGroups(lat=51.0486, lon=-114.0708,radius=5)#initial request to obtain total request pages time.sleep(1) pages = int(groups.meta['total_count']/groups_per_page) print("total request groups = " + str(groups.meta['total_count'])) for i in range(0,pages + 1): #iterate over each request page print("page " + str(i) + "/" + str(pages)) #get offseted request by current request page groups = client.GetGroups(lat=51.0486, lon=-114.0708,radius=5,fields=['topics'],pages=groups_per_page,offset=i) 29/30 (10 seconds remaining) total request groups = 903 page 0/4 28/30 (8 seconds remaining) page 1/4 27/30 (6 seconds remaining) page 2/4 26/30 (5 seconds remaining) page 3/4 25/30 (3 seconds remaining) page 4/4 24/30 (2 seconds remaining) Initally I attempted to use the above method to iterate over the entire 1290 pages of groups on meetup.com, but each request required me to pass the impossibly high radius parameter with each respective offset page, which I worried was hammering meetup.com's servers and would have taken a few days of straight API requests. The alternate solution I ended up using was to obtain a list of the top 250 global cities by population and use each as the centroid GPS location with a 300 mile radius to obtain the nearby groups. The complete API requests and data structure handling done for collecting the meetup.com data can be viewed in main.py in the projects repo. To keep the data within githubs maximum 100mb file limit and ensure a performant d3.js visualization, city-topics with less then 100 members are filtered out of the dataset. The Viz The visualization is made up of 3 main components: 1. Globe with city markings indicating cities containing the user selected topics and color coded by that cities sum total ranking in each topic - the lowest total score is the highest ranking city for that unique list of topics. The base for the d3.js globe was modified from here 2. Top 10 ranking cities for user selected list of topics 3. Detailed data for user selected city indicating that cities top 5 ranked topics, plus the rank for each of the user inputted topics My Example To test out the final viz, I added a few of the topic that interest me to find my ideal city. The following image depicts the results for my list of topics. The best city for all 8 topics appears to be New York, which is usually the number one city for any list of topics. Meetup.com was started in New York, and I believe New York is a large percentage of the total meetup.com user base, so most queries will show it as being the top city for most given list of topics. The results past New York become more interesting for my example, especially Sydney. It does well in all of the topics that interest me, plus it ranks first in the category "fun fun fun". Maybe I'll have to check out Sydney once I'm done my studies here in Barcelona. Conclusions The meetup.com API is a really cool dataset that can be used to explore the world and how people are interacting in it. There's probably alot more that can be done with this dataset, and I'm looking forward to playing with it some more to find further insights and interesting anomolies. Hopefully others have fun finding their ideal city and exploring the world through this lens.
http://cole-maclean.github.io/blog/meetupcityfinder/
CC-MAIN-2017-39
refinedweb
1,838
51.78
This blog has moved to kennykerr.ca I’ve noticed that quite a few people in the community have been wondering why on earth the System.Enum type in version 2 of the .NET Framework lacks a generic Parse method. If you haven’t used the Parse method lately, an example will help to clarify the frustration many developers have experienced. I will use C# for this illustration since that is the language that causes much of the frustration. :) Here goes: FileShare share1 = FileShare.Read | FileShare.Delete; string text = share1.ToString();Debug.Assert("Read, Delete" == text); FileShare share2 = (FileShare) Enum.Parse(typeof(FileShare), text);Debug.Assert(share1 == share2); FileShare is an enum declared in the System.IO namespace. It defines the constraints placed on how a particular file can be shared. Since the CLR defines a common type system, FileShare ultimately derives from System.Object and inherits its virtual ToString method. In the example above, the share1 value is implicitly boxed and the ToString method is then dispatched against the boxed value. Since the FileShare type includes the Flags attribute, the ToString implementation provided by the abstract System.Enum value type knows to comma-separate the flags. Had the Flags attribute been omitted, the ToString override would simply have returned the string representation of the enum’s underlying type, typically a 32-bit integer. So far so good. It’s when you attempt to convert the string representation back to an enum value that the frustration begins. To convert strings into enum values, the System.Enum type provides a static Parse method with the following signature, expressed in C#: object Parse(Type enumType, string value, bool ignoreCase); Since enums can have any underlying integral type, the Parse method cannot return a value type and thus returns an object. But what about returning System.Enum? There are two challenges with that. Firstly Enum is abstract so it cannot be returned by value and it’s abstract because Enum itself doesn’t contain the enum’s value field and returning it or passing it by value would slice away the value field. Secondly, C# doesn’t support strongly-typed boxed values – all boxed values are expressed as System.Object types in C#. C++/CLI allows you to express the Parse method more accurately: Enum^ Parse(Type^ enumType, String^ value, bool ignoreCase); If you’re not familiar with C++/CLI, the ^ declarator indicates that the type declaration is a handle to a CLR reference type. Enum^ is thus a handle to an Enum-derived value type. Unfortunately C# doesn’t support strongly-typed boxed values, but it would not help much anyway since an explicit conversion would still be required to convert the abstract Enum type to a concrete enum value. So let’s give up trying to improve on the respectable Parse method provided by the BCL and focus on how we might improve the situation from within the language. Here is the Parse method usage again from the C# example: FileShare share2 = (FileShare) Enum.Parse(typeof(FileShare), text); There are fundamentally two problems with this code. The first is the need to repeatedly indicate the exact type of the enum we wish to convert to. A veteran C++ programmer might instinctively write the following (that is if the veteran C++ programmer were familiar with C++/CLI): template <typename T>T Parse(String^ value, bool ignoreCase = false){ return safe_cast<T>(Enum::Parse(T::typeid, value, ignoreCase));} This solves the first problem nicely. The template function generates the necessary code to pass the type to the Parse method as well as to convert the result to the appropriate type. The typeid keyword returns the Type object for the type T. The safe_cast keyword unboxes the Object^ returned by the Parse method, converting it to the type indicated by the template type parameter. With this template function available, the original C# example can be written more cleanly in C++ as follows: FileShare share1 = FileShare::Read | FileShare::Delete; String^ text = share1.ToString();Debug::Assert("Read, Delete" == text); FileShare share2 = Parse<FileShare>("Read, Delete");Debug::Assert(share1 == share2); This is certainly more elegant but there is still one more problem that plagues both the C# version as well as the C++ template version, although it’s less of a problem in C++. The issue is that we’re not using the compiler to perform any kind of validation to ensure that the types used with the Parse method are in fact of the correct type. In the C# example you can use two completely different types without as much as a warning from the compiler. The C++ example at least doesn’t allow that, but you can still use a non-enum type as the type parameter and the code will compile without any errors. This is less of a problem in practice since you will typically be assigning the result of the Parse method to a strongly-typed variable and the compiler will complain if the Parse template function’s calculated return type does not match the target of the assignment. Notice in this C# example that the wrong type is passed to the Parse method. FileShare share2 = (FileShare) Enum.Parse(typeof(FileMode), text); The template solution is adequate for C++, but can we do better? Why yes! There is even some hope for the C# programmer. Templates use structural constraints when they are instantiated by the compiler. This is ideal for many classes of problems. In this case however we would like something a little different. What we need is a technique that provides subtype constraints. A CLR generic will do nicely. Consider the following generic C++ functions: generic <typename T> where T : Enumstatic T Parse(String^ value){ return Parse<T>(value, false);} generic <typename T> where T : Enumstatic T Parse(String^ value, bool ignoreCase){ return safe_cast<T>(Enum::Parse(T::typeid, value, ignoreCase));} By using a generic function, we can declare a subtype constraint for T such that the compiler will ensure that all uses of the Parse generic function are used with a type parameter that derives from Enum, thus only allowing CLR enumerated types. A default argument cannot be used as with the previous template function because default arguments are not allowed on generic functions or members of managed types. Default arguments are not supported by the CLR. Finally, the question that may have popped into your head is why doesn’t the .NET Framework’s Enum class provide a generic Parse function as I have just described? The trouble is that C# doesn’t allow Enum to be used as a subtype constraint and the BCL is undoubtedly written in C#. Had the Visual C++ team been ready with C++/CLI when .NET was first being hatched, I suspect things might have turned out differently. Fortunately C++/CLI is coming soon in Visual C++ 2005 and brings all the power and flexibility of templates, generics and multi-paradigm programming to the .NET Framework. If you’re a C# programmer and aren’t ready to switch to C++ then not to work. Although C# doesn’t allow you to declare the generic function equivalent to the C++ example above, the good news is that Visual C++ generates perfectly legal CLI metadata and IL. Simply expose the generic Parse method on a public class in a C++ library assembly and reference it from your C# project. Using it is simple and natural in C#: FileShare share2 = Utility.Parse<FileShare>(text); Don’t you just love .NET! Happy coding, whatever your language(s) of choice. © 2005 Kenny Kerr Very nice trick, if the whole thing hangs together then it is a very handy tool. Nice post.
http://weblogs.asp.net/kennykerr/archive/2005/05/16/407023.aspx
crawl-003
refinedweb
1,283
62.17
For the codelabs in this pathway, you will be building a Dice Roller Android app. When the user "rolls the dice," a random result will be generated. The result takes into account the number of sides of the dice. For example, only values from 1-6 can be rolled from a 6-sided dice. This is what the final app will look like. To help you focus on the new programming concepts for this app, you will use the browser-based Kotlin programming tool to create core app functionality. The program will output your results to the console. Later you will implement the user interface in Android Studio. In this first codelab, you will create a Kotlin program that simulates rolling dice and outputs a random number, just like a dice would. Prerequisites - How to open, edit, and run code in - Create and run a Kotlin program that uses variables and functions, and prints a result to the console. - Format numbers within text using a string template with the ${variable}notation. What you'll learn - How to programmatically generate random numbers to simulate dice rolls. - How to structure your code by creating a Diceclass with a variable and a method. - How to create an object instance of a class, modify its variables, and call its methods. What you'll build - A Kotlin program in the browser-based Kotlin programming tool that can perform a random dice roll. What you need - A computer with an internet connection Games often have a random element to them. You could earn a random prize or advance a random number of steps on the game board. In your everyday life, you can use random numbers and letters to generate safer passwords! Instead of rolling actual dice, you can write a program that simulates rolling dice for you. Each time you roll the dice, the outcome can be any number within the range of possible values. Fortunately, you don't have to build your own random-number generator for such a program. Most programming languages, including Kotlin, have a built-in way for you to generate random numbers. In this task, you will use the Kotlin code to generate a random number. Set up your starter code - In your browser, open the website. - Delete all the existing code in the code editor and replace it with the code below. This is the main()function you worked with in earlier codelabs. fun main() { } Use the random function To roll a dice, you need a way to represent all the valid dice roll values. For a regular 6-sided dice, the acceptable dice rolls are: 1, 2, 3, 4, 5, and 6. Previously, you learned that there are types of data like Int for integer numbers and String for text. IntRange is another data type, and it represents a range of integer numbers from a starting point to an endpoint. IntRange is a suitable data type for representing the possible values a dice roll can produce. - Inside your main()function, define a variable as a valcalled diceRange. Assign it to an IntRangefrom 1 to 6, representing the range of integer numbers that a 6-sided dice can roll. val diceRange = 1..6 You can tell that 1..6 is a Kotlin range because it has a start number, two dots, followed by an ending number (no spaces in between). Other examples of integer ranges are 2..5 for the numbers 2 through 5, and 100..200 for the numbers 100 through 200. Similar to how calling println() tells the system to print the given text, you can use a function called random() to generate and return a random number for you for a given range. As before, you can store the result in a variable. - Inside main(), define a variable as a valcalled randomNumber. - Make randomNumberhave the value of the result of calling random()on the diceRangerange, as shown below. val randomNumber = diceRange.random() Notice that you are calling random() on diceRange using a period, or dot, between the variable and the function call. You can read this as "generating a random number from diceRange". The result is then stored in the randomNumber variable. - To see your randomly generated number, use the string formatting notation (also called a "string template") ${randomNumber}to print it, as shown below. println("Random number: ${randomNumber}") Your finished code should look like this. fun main() { val diceRange = 1..6 val randomNumber = diceRange.random() println("Random number: ${randomNumber}") } - Run your code several times. Each time, you should see output as below, with different random numbers. Random number: 4 When you roll dice, they are real objects in your hands. While the code you just wrote works perfectly fine, it's hard to imagine that it's about actual dice. Organizing a program to be more like the things it represents makes it easier to understand. So, it would be cool to have programmatic dice that you can roll! All dice work essentially the same. They have the same properties, such as sides, and they have the same behavior, such as that they can be rolled. In Kotlin, you can create a programmatic blueprint of a dice that says that dice have sides and can roll a random number. This blueprint is called a class. From that class, you can then create actual dice objects, called object instances. For example, you can create a 12-sided dice, or a 4-sided dice. Define a Dice class In the following steps, you will define a new class called Dice to represent a rollable dice. - To start afresh, clear out the code in the main()function so that you end up with the code as shown below. fun main() { } - Below this main()function, add a blank line, and then add code to create the Diceclass. As shown below, start with the keyword class, followed by the name of the class, followed by an opening and closing curly brace. Leave space in between the curly braces to put your code for the class. class Dice { } Inside a class definition, you can specify one or more properties for the class using variables. Real dice can have a number of sides, a color, or a weight. In this task, you'll focus on the property of number of sides of the dice. - Inside the Diceclass, add a varcalled sidesfor the number of sides your dice will have. Set sidesto 6. class Dice { var sides = 6 } That's it. You now have a very simple class representing dice. Create an instance of the Dice class With this Dice class, you have a blueprint of what a dice is. To have an actual dice in your program, you need to create a Dice object instance. (And if you needed to have three dice, you would create three object instances.) - To create an object instance of Dice, in the main()function, create a valcalled myFirstDiceand initialize it as an instance of the Diceclass. Notice the parentheses after the class name, which denote that you are creating a new object instance from the class. fun main() { val myFirstDice = Dice() } Now that you have a myFirstDice object, a thing made from the blueprint, you can access its properties. The only property of Dice is its sides. You access a property using the "dot notation". So, to access the sides property of myFirstDice, you call myFirstDice.sides which is pronounced " myFirstDice dot sides". - Below the declaration of myFirstDice, add a println()statement to output the number of sidesof myFirstDice. println(myFirstDice.sides) Your code should look like this. fun main() { val myFirstDice = Dice() println(myFirstDice.sides) } class Dice { var sides = 6 } - Run your program and it should output the number of sidesdefined in the Diceclass. 6 You now have a Dice class and an actual dice myFirstDice with 6 sides. Let's make the dice roll! Make the Dice Roll You previously used a function to perform the action of printing cake layers. Rolling dice is also an action that can be implemented as a function. And since all dice can be rolled, you can add a function for it inside the Dice class. A function that is defined inside a class is also called a method. - In the Diceclass, below the sidesvariable, insert a blank line and then create a new function for rolling the dice. Start with the Kotlin keyword fun, followed by the name of the method, followed by parentheses (), followed by opening and closing curly braces {}. You can leave a blank line in between the curly braces to make room for more code, as shown below. Your class should look like this. class Dice { var sides = 6 fun roll() { } } When you roll a six-sided dice, it produces a random number between 1 and 6. - Inside the roll()method, create a val randomNumber. Assign it a random number in the 1..6range. Use the dot notation to call random()on the range. val randomNumber = (1..6).random() - After generating the random number, print it to the console. Your finished roll()method should look like the code below. fun roll() { val randomNumber = (1..6).random() println(randomNumber) } - To actually roll myFirstDice, in main(), call the roll()method on myFirstDice. You call a method using the "dot notation". So, to call the roll()method of myFirstDice, you type myFirstDice.roll()which is pronounced " myFirstDicedot roll()". myFirstDice.roll() Your completed code should look like this. fun main() { val myFirstDice = Dice() println(myFirstDice.sides) myFirstDice.roll() } class Dice { var sides = 6 fun roll() { val randomNumber = (1..6).random() println(randomNumber) } } - Run your code! You should see the result of a random dice roll below the number of sides. Run your code several times, and notice that the number of sides stays the same, and the dice roll value changes. 6 4 Congratulations! You have defined a Dice class with a sides variable and a roll() function. In the main() function, you created a new Dice object instance and then you called the roll() method on it to produce a random number. Currently you are printing out the value of the randomNumber in your roll() function and that works great! But sometimes it's more useful to return the result of a function to whatever called the function. For example, you could assign the result of the roll() method to a variable, and then move a player by that amount! Let's see how that's done. - In main()modify the line that says myFirstDice.roll(). Create a valcalled diceRoll. Set it equal to the value returned by the roll()method. val diceRoll = myFirstDice.roll() This doesn't do anything yet, because roll() doesn't return anything yet. In order for this code to work as intended, roll() has to return something. In previous codelabs you learned that you need to specify a data type for input arguments to functions. In the same way, you have to specify a data type for data that a function returns. - Change the roll()function to specify what type of data will be returned. In this case, the random number is an Int, so the return type is Int. The syntax for specifying the return type is: After the name of the function, after the parentheses, add a colon, space, and then the Intkeyword for the return type of the function. The function definition should look like the code below. fun roll(): Int { - Run this code. You will see an error in the Problems View. It says: A ‘return' expression is required in a function with a block body. You changed the function definition to return an Int, but the system is complaining that your code doesn't actually return an Int. "Block body" or "function body" refers to the code between the curly braces of a function. You can fix this error by returning a value from a function using a return statement at the end of the function body. - In roll(), remove the println()statement and replace it with a returnstatement for randomNumber. Your roll()function should look like the code below. fun roll(): Int { val randomNumber = (1..6).random() return randomNumber } - In main()remove the print statement for the sides of the dice. - Add a statement to print out the value of sidesand diceRollin an informative sentence. Your finished main()function should look similar to the code below. fun main() { val myFirstDice = Dice() val diceRoll = myFirstDice.roll() println("Your ${myFirstDice.sides} sided dice rolled ${diceRoll}!") } - Run your code and your output should be like this. Your 6 sided dice rolled 4! Here is all your code so far. fun main() { val myFirstDice = Dice() val diceRoll = myFirstDice.roll() println("Your ${myFirstDice.sides} sided dice rolled ${diceRoll}!") } class Dice { var sides = 6 fun roll(): Int { val randomNumber = (1..6).random() return randomNumber } } Not all dice have 6 sides! Dice come in all shapes and sizes: 4 sides, 8 sides, up to 120 sides! - In your Diceclass, in your roll()method, change the hard-coded 1..6to use sidesinstead, so that the range, and thus the random number rolled, will always be right for the number of sides. val randomNumber = (1..sides).random() - In the main()function, below and after printing the dice roll, change sidesof my FirstDiceto be set to 20. myFirstDice.sides = 20 - Copy and paste the existing print statement below after where you changed the number of sides. - Replace the printing of diceRollwith printing the result of calling the roll()method on myFirstDice. println("Your ${myFirstDice.sides} sided dice has rolled a ${myFirstDice.roll()}!") Your program should look like this. fun main() { val myFirstDice = Dice() val diceRoll = myFirstDice.roll() println("Your ${myFirstDice.sides} sided dice rolled ${diceRoll}!") myFirstDice.sides = 20 println("Your ${myFirstDice.sides} sided dice rolled ${myFirstDice.roll()}!") } class Dice { var sides = 6 fun roll(): Int { val randomNumber = (1..sides).random() return randomNumber } } - Run your program and you should see a message for the 6-sided dice, and a second message for the 20-sided dice. Your 6 sided dice rolled 3! Your 20 sided dice rolled 15! The idea of a class is to represent a thing, often something physical in the real world. In this case, a Dice class does represent a physical dice. In the real world, dice cannot change their number of sides. If you want a different number of sides, you need to get a different dice. Programmatically, this means that instead of changing the sides property of an existing Dice object instance, you should create a new dice object instance with the number of sides you need. In this task, you are going to modify the Dice class so that you can specify the number of sides when you create a new instance. Change the Dice class definition so you can supply the number of sides. This is similar to how a function can accept arguments for input. - Modify the Diceclass definition to accept an integer called numSides. The code inside your class does not change. class Dice(val numSides: Int) { // Code inside does not change. } - Inside the Diceclass, delete the sidesvariable, as you can now use numSides. - Also, fix the range to use numSides. Your Dice class should look like this. class Dice (val numSides: Int) { fun roll(): Int { val randomNumber = (1..numSides).random() return randomNumber } } If you run this code, you will see a lot of errors, because you need to update main() to work with the changes to the Dice class. - In main(), to create myFirstDicewith 6 sides, you must now supply in the number of sides as an argument to the Diceclass, as shown below. val myFirstDice = Dice(6) - In the print statement, change sidesto numSides. - Below that, delete the code that changes sidesto 20, because that variable does not exist anymore. - Delete the printlnstatement underneath it as well. Your main() function should look like the code below, and if you run it, there should be no errors. fun main() { val myFirstDice = Dice(6) val diceRoll = myFirstDice.roll() println("Your ${myFirstDice.numSides} sided dice rolled ${diceRoll}!") } - After printing the first dice roll, add code to create and print a second Diceobject called mySecondDicewith 20 sides. val mySecondDice = Dice(20) - Add a print statement that rolls and prints the returned value. println("Your ${mySecondDice.numSides} sided dice rolled ${mySecondDice.roll()}!") - Your finished main()function should look like this. { val randomNumber = (1..numSides).random() return randomNumber } } - Run your finished program, and your output should look like this. Your 6 sided dice rolled 5! Your 20 sided dice rolled 7! When writing code, concise is better. You can get rid of the randomNumber variable and return the random number directly. - Change the returnstatement to return the random number directly. fun roll(): Int { return (1..numSides).random() } In the second print statement, you put the call to get the random number into the string template. You can get rid of the diceRoll variable by doing the same thing in the first print statement. - Call myFirstDice.roll()in the string template and delete the diceRollvariable. The first two lines of your main()code now look like this. val myFirstDice = Dice(6) println("Your ${myFirstDice.numSides} sided dice rolled ${myFirstDice.roll()}!") - Run your code and there should be no difference in the output. This is your final code after refactoring it . fun main() { val myFirstDice = Dice(6) println("Your ${myFirstDice.numSides} sided dice rolled ${myFirstDice.roll()}!") val mySecondDice = Dice(20) println("Your ${mySecondDice.numSides} sided dice rolled ${mySecondDice.roll()}!") } class Dice (val numSides: Int) { fun roll(): Int { return (1..numSides).random() } } { return (1..numSides).random() } } - Call the random()function on an IntRangeto generate a random number: (1..6).random() - Classes are like a blueprint of an object. They can have properties and behaviors, implemented as variables and functions. - An instance of a class represents an object, often a physical object, such as a dice. You can call the actions on the object and change its attributes. - You can supply values to a class when you create an instance. For example: class Dice(val numSides: Int)and then create an instance with Dice(6). - Functions can return something. Specify the data type to be returned in the function definition, and use a returnstatement in the function body to return something. For example: fun example(): Int { return 5 } Do the following: - Give your Diceclass another attribute of color and create multiple instances of dice with different numbers of sides and colors! - Create a Coinclass, give it the ability to flip, create an instance of the class and flip some coins! How would you use the random()function with a range to accomplish the coin flip?
https://developer.android.com/codelabs/basic-android-kotlin-training-create-dice-roller-in-kotlin
CC-MAIN-2021-21
refinedweb
3,100
75.91
This notebook constructs generalizations of Barro's classic 1979 model of tax smoothing. Our generalizations are adaptations of extensions of his 1979 model suggested by Barro (1999, 2003). Barro's original 1979 model is about a government that borrows and lends in order to help it minimize an intertemporal measure of distortions caused by taxes. Technical tractability induced Barro to assume that the government trades only one-period risk-free debt, and the one-period risk-free interest rate is constant. By using a secret weapon -- model along lines he suggested in Barro (1999, 2003). Barro (1979) disortions Barro's model can be mapped into a discounted linear quadratic dynamic programming problem. Our generalizations of Barro's (1979) model, partly inspired by Barro (1999) and Barro (2003), defining pin down $N$ value functions and $N$ linear decision rules, applying to the $N$ Markov states. Barro's 1979 and 2003 notebook describes: Markov jump linear quadratic (LQ) dynamic programming An application of Markov jump LQ dynamic programming to a model in which a government faces exogenous time-varying interest rates for issuing one-period risk-free debt A sequel to this notebook describes applies Markov LQ control to settings in which a government issues risk-free debt of different maturities Markov jump linear quadratic dynamic programming combines advantages of the computational simplicity of linear quadratic dynamic programming, and the ability of finite state Markov chains to represent interesting patterns of random variation determine $N$ optimal value functions and $N$ linear decision rules. These value functions and decision rules apply in the $N$ Markov states: i.e., when the Markov state is in state $j$, the value function and decision rule for state $j$ prevails. It is handy to have the following reminder in mind. A linear quadratic dynamic programming problem consists of a scalar discount factor $\beta \in (0,1)$, an $n\times 1$ state vector $x_t$, an initial condition for $x_0$, a $k \times 1$ control vector $u_t$, a $p \times 1$ random shock vector $w_{t+1}$ and the following two triples of matrices: A triple of matrices $(R, Q, W)$ defining a loss function $$ r(x_t, u_t) = x_t' R x_t + u_t' Q u_t + 2 u_t' W x_t $$ a triple of matrices $(A, B, C)$ defining a state-transition law $$ x_{t+1} = A x_t + B u_t + C w_{t+1} $$ The problem is$$ - x_0' P x_0 - \rho = \min_{\{u_t\}_{t=0}^\infty} E \sum_{t=0}^{\infty} \beta^t r(x_t, u_t) $$ subject to the transition law for the state. The optimal decision rule for this problem have the form$$ u_t = - F x_t $$ and the optimal value function is of the form$$ -\left( x_t' P x_t + \rho \right) $$ where $P$ solves the algebraic matrix Riccati equation$$ P = R+ \beta A' P A_i - (\beta B' P A + W)' (Q + \beta B P B )^{-1} (\beta B P A + W)]$$ and the constant $\rho$ satisfies$$\rho = \beta \left( \rho + {\rm trace}(P C C') \right)$$ and the matrix $F$ in the decision rule for $u_t$ satisfies$$ F = (Q + \beta B' P B)^{-1} (\beta (B' P A )+ W)$$ The idea is to make the matrices $A, B, C, R, Q, W$ fixed functions of a finite state $s$ that is governed by an $N$ state Markov chain. This makes decision rules depend on the Markov state, and so fluctuate through time restricted ways. In particular, we use the following extension of a discrete time linear quadratic dynamic programming problem. We let $ s(t) \equiv s_t \in [1, 2, \ldots, N]$ be a time t realization of an $N$ state Markov chain with transition matrix $\Pi$ having typical element $\Pi_{ij}$. Here $i$ denotes today and $j$ denotes tomorrow and$$ \Pi_{ij} = {\rm Prob}(s_{t+1} = j |s_t = i) $$ We'll switch between labeling today's state as $s(t)$ and $i$ and between labeling tomorrow's state as $s(t+1)$ or $j$. The decision maker solves the minimization problem:$$ \min_{\{u_t\}_{t=0}^\infty} E \sum_{t=0}^{\infty} \beta^t r(x_t, s(t), u_t) $$ with $$ r(x_t, s(t), u_t) = -( x_t' R(s_t) x_t + u_t' Q(s_t) u_t + 2 u_t' W(s_t) x_t) $$ subject to linear laws of motion with matrices $(A,B,C)$ each possibly dependent on the Markov-state-$s_t$:$$ x_{t+1} = A(s_t) x_t + B(s_t) u_t + C(s_t) w_{t+1} $$ where $\{w_{t+1}\}$ is an i.i.d. stochatic process with $w_{t+1} \sim {\cal N}(0,I)$. The optimal decision rule for this problem have the form$$ u_t = - F(s_t) x_t $$ and the optimal value functions are of the form$$ -\left( x_t' P(s_t) x_t + \rho(s_t) \right) $$ or equivalently$$ - x_t' P_i x_t - \rho_i $$ The optimal value functions $- x' P_i x - \rho_i$ for $i = 1, \ldots, n$ satisfy the $N$ interrelated Bellman equations\begin{align*} - x' P_i x - \rho_i & = \max_u - \biggl[ x'R_i x + u' Q_i u + 2 u' W_i x \cr & \beta \sum_j \Pi_{ij}E ((A_i x + B_i u + C_i w)' P_j (A_i x + B_i u + C_i w) x + \rho_j) \biggr] \end{align*} The matrices $P(s(t)) = P_i$ and the scalars $ \rho(s_t) = \rho_i, i = 1, \ldots, n $ satisfy the following stacked system of algebraic matrix Riccati equations:$$ P_i = R_i + \beta \sum_j A_i' P_j A_i \Pi_{ij} - \sum_j \Pi_{ij}[ (\beta B_i' P_j A_i + W_i)' (Q + \beta B_i' P_j B_i)^{-1} (\beta B_i' P_j A_i + W_i)]$$$$\rho_i = \beta \sum_j \Pi_{ij} ( \rho_j + {\rm trace}(P_j C_i C_i') )$$ and the $F_i$ in the optimal decision rules are$$ F_i = (Q_i + \beta \sum_j \Pi_{ij} B_i' P_j B_i)^{-1} (\beta \sum_j \Pi_{ij}(B_i' P_j A_i )+ W_i)$$ We begin by solving a version of the Barro (1979)), the stochastic process of government expenditures is exogenous. The government's problem is to choose a plan for taxation and borrowing $\$. To begin with, we will assume that $p_{t,t+1}$ is constant (and equal to $\beta$), but we will also extend the model to allow this variable to evolve over time. To map into the LQ framework, we that $G_t$ follows an AR(1) process: $$ G_{t+1} = \bar G + \rho G_t + \sigma w_{t+1} $$ To do this, we set $z_t = \begin{bmatrix} 1 \\ G_t \end{bmatrix}$, and consequently: $$ A_{22} = \begin{bmatrix} 1 & 0 \\ \bar G & \rho \end{bmatrix} \hspace{2mm} , \hspace{2mm} C_2 = \begin{bmatrix} 0 \\ \sigma \end{bmatrix} $$ import quantecon as qe import numpy as np import matplotlib.pyplot as plt %matplotlib inline # M = np.array([[-beta]]) R = np.dot(S.T,S) Q = np.dot(M.T,M) W = np.dot(M.T,S) # Small penalty on debt required to implement no-ponzi scheme R[0,0] = R[0,0] + 1e-9 We can now create an instance of an LQ model: LQBarro = qe.LQ(Q, R, A, B, C=C, N=W, beta=beta). As conditional expectation of $T_{t+1}$ at time $t$ is:$$ E_t T_{t+1} = (S-MF)(A-BF)x_t $$ Consequently, taxation is a martingale ($E_t T_{t+1} = T_t$) if:$$(S-MF)(A-BF) = (S-MF)$$ which holds in this case: S - M.dot(F), (S-M.dot(F)).dot(A-B.dot(F)) (array([[ 0.05000002, 19.79166502, 0.2083334 ]]), array([[ 0.05000002, 19.79166504, 0.2083334 ]])) This explains the gradual fanning out of taxation if we simulate the Barro model a large number of times: T = 500 fig, ax = plt.subplots() ax.set_xlabel(r'Time') ax.set_ylabel(r'Taxation') for i in range(250): x,u,w = LQBarro.compute_sequence(x0,ts_length=T) ax.plot(list(range(T+1)), ((S-M.dot(F)).dot(x))[0,:]) plt.show() We can see a similar, but smoother pattern, if we plot government debt over time. Debt is smoother due to the persistence of the government spending process. T = 500 fig, ax = plt.subplots() ax.set_xlabel(r'Time') ax.set_ylabel(r'Taxation') for i in range(250): x,u,w = LQBarro.compute_sequence(x0,ts_length=T) ax.plot(list(range(T+1)), x[0,:]) plt.show() To implement the extension to the Barro model in which $p_{t,t+1}$ varies over time, we must allow the M matrix to be time-varying. From the mapping of the Barro model into the LQ framework, this means that our Q and W matrices will now also vary over time. We can solve such a model using the LQ_Markov class, which solves Markov jump linear quandratic control problems as described above. The code for the class can be viewed here. The class takes a variable number of arguments, to allow for there to be an arbitrary $N$ states of the world. To accomodate this, the matrices for each state of the world must be held in a "namedtuple". The value and policy functions are then found by iterating on the system of algebraic matrix Riccati equations. The solutions for $P,F,\rho$ are stored in Python "dictionaries". The class also contains a "method", for simulating the model. This is an extension of a similar method in the LQ class, adapted to take into account the fact that the model's matrices depend on the state of the world. Below we import all functionality from this code. (You should download the file and put it in the same directory as this notebook before you execute the next line.) from lq_markov import * state of the world has a low interest rate, and the second state of the world has a high interest rate. We also need to specify a transition matrix for the state of the world, we use:$$ \Pi = \begin{bmatrix} 0.8 & 0.2 \\ 0.2 & 0.8 \end{bmatrix} $$ (so each state of the world is persisent, and there is an equal chance of moving from one namedtuple to keep the R,Q,A,B,C,W matrices for each state of the world world = namedtuple('world', ['A', 'B', 'C', 'R', 'Q', 'W']) Pi = np.array([[0.8,0.2],[0.2,0.8]]) M1 = np.array([[-beta - 0.02]]) M2 = np.array([[-beta + 0.017]]) Q1 = np.dot(M1.T,M1) Q2 = np.dot(M2.T,M2) W1 = np.dot(M1.T,S) W2 = np.dot(M2.T,S) #Sets up the two states of the world v1 = world(A=A,B=B,C=C,R=R,Q=Q1,W=W1) v2 = world(A=A,B=B,C=C,R=R,Q=Q2,W=W2) MJLQBarro = LQ_Markov(beta,Pi,v1,v2) The decision rules are now dependent on the state of the world: MJLQBarro.F[1] array([[ -0.98437712, 19.20516427, -0.8314215 ]]) MJLQBarro.F[2] array([[ -1.01434301, 21.5847983 , -0.83851116]]) Simulating a large number of such economies over time reveals interesting dynamics. Debt tends to stay low and stable, but periodically spikes up to high levels. T = 2000 x0 = np.array([[1000,1,25]]) fig, ax = plt.subplots() ax.set_xlabel(r'Time') ax.set_ylabel(r'Debt') for i in range(250): x,u,w,s = MJLQBarro.compute_sequence(x0,ts_length=T) ax.plot(list(range(T+1)), x[0,:]) plt.show()
http://nbviewer.jupyter.org/github/QuantEcon/TaxSmoothing/blob/master/Tax_Smoothing_1.ipynb
CC-MAIN-2017-04
refinedweb
1,845
57.81
How do I localize strings? How do I localize strings? Hi all; When designing with Architect, how do I put all strings in a separate resource file that we can change based on the language of the user? Or is another approach recommended? thanks - dave SA does not have any turn-key solution to this. I have done the following: - Put your strings in a separate namespace in a separate JS-file. - Load that file before you include your Ext JS file in the HTML-page - In you SA project, add processconfigs to all things you need to localize and set the text/html/title/fieldLabel properties /Mattias OW! I was afraid it was something like that. thanks - dave At SenchaCon I discussed this with a couple of people and Sencha engineers and came up with an alternative approach that I can share with you. This may or may not fit your project, especially as it involves overriding components on a high level that may cause performance issues. The basic idea is to override Ext.Component along the lines below. The namespace VPCalcDesktop is the app's namespace and VPCalcLang is a file containing the following code and that is required in the SA project: Code: Ext.define('VPCalcDesktop.Locale',{ override: 'Ext.Component', constructor: function(cfg) { if (cfg) { this.parser(cfg, 'title'); this.parser(cfg, 'text'); this.parser(cfg, 'labelFieldSet'); this.parser(cfg, 'boxLabel'); this.parser(cfg, 'fieldLabel'); this.parser(cfg, 'label'); } this.callParent(arguments); }, parser: function(config, property) { if (config[property]) { var text = config[property]; if (text.substr(0, 1) == '#') { var result = VPCalcLang[text.substr(1)]; } config[property] = result||text; } } }); Code: var VPCalcLang=VPCalcLang || {}; VPCalcLang=eval('({"indata_tab1":"Projektinformation","indata_tab3":"Installation","indata_tab4":"Driftparametrar"})'); (I am developing a Desktop and Touch version of the same application, with different names but the strings are the same hence the different namespace for the strings). I think this would kill us as we have around 4,000 strings. I'm hoping they can add something where there is a resource.js that is just a ton of variables that have strings assigned to them. And then also a resource_en.js, resource_de.js, etc. and it loads the appropiate one. thanks - dave
http://www.sencha.com/forum/showthread.php?270522-How-do-I-localize-strings
CC-MAIN-2015-14
refinedweb
367
60.41
What follows is a set of rules, guidelines, and tips that we have found to be useful in making C++ code portable across many machines and compilers. None of these rules is absolute. We update the rules from time to time as C++ language features become widely implemented. C++ portability rules When these rules were first written down, we didn't use templates, namespaces, or inline functions of any complexity. There was also a lot of concern over interoperability between C and C++. How times change! These days, templates and inlines are some of our favorite C++ footguns. Feetgun. Whatever. C++ namespaces are now standard practice. And there's not much C code left in the codebase. Then again, some things apparently never change. Don't use static constructors Gecko is a large existing codebase that uses manual error handling. We can't switch on exceptions and start throwing them because the existing code isn't exception-safe. If you do use exceptions in some platform-specific library code or something, you must catch all exceptions there, because you can't throw the exception across XP (cross platform) code. Don't use Run-time Type Information This is another feature we once avoided because of uneven implementations across compilers. But we compile with RTTI disabled to this day, I guess to avoid the memory overhead.. Don't use the C++ standard library (including iostream, locale, and the STL) There are one million reasons for this. Just for starters, the C++ standard library uses exceptions and we compile with exceptions disabled. But generally it's just literally proven better to write our own, as nutty as that sounds -- our library code is smaller, it behaves the same across platforms, and it wins on correctness, efficiency, Unicode support, features, etc. Look in /mfbt. There is one exception to this rule: it is acceptable to use placement new. You'll have to #include <new> first. Use C++ lambdas, but with care C++ lambdas are supported across all our compilers now. Rejoice! We recommend explicitly listing out the variables that you capture in the lambda, both for documentation purposes, and to double-check that you're only capturing what you expect to capture. Use namespaces Namespaces may be used according to the style guidelines in Mozilla Coding Style Guide. Don't mix varargs and inlines What? Why are you using varargs to begin with?! Stop that at once! Don't use initializer lists with objects Non-portable example (at least, this used to be nonportable, because HP-UX!): SubtlePoint myPoint = {300, 400}; This is more of a style thing at this point, but why not splurge and get yourself a nice constructor? Make header files compatible with C and C++ ... Use override on subclass virtual member functions The override keyword is supported in C++11 and in all our supported compilers, and it catches bugs. Always declare a copy constructor and assignment operator Non-portable code: class FooClass { // having such similar signatures // is a bad idea in the first place. { // having such similar signatures // is a bad idea in the first place. void doit(long); void doit(short); }; void B::foo(FooClass* xyz) { xyz->doit(45L); } Use nsCOMPtr in XPCOM code See the nsCOMPtr User Manual for usage details. Don't use identifiers that start with an underscore This rule occasionally surprises people who've been hacking C++ for decades. But it comes directly from the C++ standard!. Stuff that is good to do for C or C++ Avoid conditional #includes when possible Every object file linked into libxul needs to have a unique name. Avoid generic names like nsModule.cpp and instead use nsPlacesModule.cpp. Turn on warnings for your compiler, and then write warning free code Some compilers (even recent ones like MSVC 2013) do not pack the bits when different bitfields are given different types. For example, the following struct might have a size of 8 bytes, even though it would fit in 1: struct { char ch : 1; int i : 1; }; Don't use an enum type for a bitfield. Last updated April 2015
https://developer.mozilla.org/en-US/docs/Mozilla/C++_Portability_Guide
CC-MAIN-2016-50
refinedweb
683
64.2
Shared libraries diamond problem? Disclaimer I thought I’d dive into this problem as a weekend project. Don’t rely on this article as a source of truth, but please correct me where I’m wrong. I’m not an expert in creating shared libraries, and it’s much harder that it would first appear. The existence of libtool proves that. Example project described can be found here. Multiple versions of the same library The lovely land of modern Unix will allow you to have multiple versions of the same library installed at the same time. That’s not the problem. The problem is that when you load the libraries all the symbols are resolved inside the same namespace. There can’t be two versions in use of the same function with the same name, even if they are in different libraries (well, it won’t work the way you want it to). You can’t choose which one to see from different code. (see breadth first search description this article about ld.so GNU linker/loader for details). The scenario In this scenario there are three separate libraries: libd1- Calls functions in libd2and libbaseversion 1. File name is simply libd1.so. libd2- Calls functions in libd1and libbaseversion 2. File name is simply libd2.so. (cross dependency between libd1and libd2) libbase- This is the library that made non backwards compatible changes between version 1 and 2. Files are libbase.so.1.0and libbase.so.2.0, with traditional symlinks from libbase.so.[12]. The important bit here is that the two versions are to be considered incompatible and must both be usable in the same process at the same time. And the executable p which links to libd1 and libd2. What we want to achieve is to have libd1 and libd2 be able to call functions in libbase, but to have them call different versions. Both libbase.so.1 and libbase.so.2 should be loaded and active (have their functions callable). What normally happens When you link an executable with -lfoo the linker finds libfoo.so and verifies that it (along with default libraries) contain all the symbols that are currently unresolved. Linking shared objects (DSO, .so files) is similar, except there’s no requirement that all symbols are resolved. If an unresolved symbol exists in more than one library then only one is actually used. You can’t therefore link two overlapping ABIs, even indirectly via an intermediate dependency. Well, you can, but are you comfortable with one of them being “hidden”? (which one is not important for this article) Both versions of the library can therefore be loaded, but if they overlap then one will hide the other (in the overlap). How to solve it The hiding of one of the symbols in a name clash is done by the dynamic linker ( ld.so) at load time (run time). Since symbols are referenced by name the only way to differentiate the two names is to force them to have different names. This can be done in different ways; manually, or automatically. Both append some text to every symbol you want to differentiate. Automatic (with --default-symver) $ gcc -fPIC -Wall -pedantic -c -o base1.o base1.c $ gcc -shared \ -Wl,--default-symver \ -Wl,-soname,libbase.so.1 \ -o libbase.so.1.0 base1.o $ nm libbase.so.1.0 [...] 00000000000006f0 T base_print <--- same name as without the special args [...] 0000000000000000 A libbase.so.1 <--- this is new with --default-symver [...] A small change. Certainly doesn’t appear to refer to a new name. You can also inspect with objdump -T, but the magic happens when you link something to it. Let’s compile and link one of the libraries that uses libbase.so: $ ldconfig -N -f ld.so.conf $ ln -fs libbase.so.1 libbase.so # library to link with $ gcc -fPIC -Wall -pedantic -c -o d1.o d1.c $ gcc -Wl,-rpath=. -L. \ -Wl,--default-symver \ -Wl,-soname,libd1.so \ -shared -o libd1.so d1.o -lbase $ nm d1.o [...] U base_print [...] U d2_print [...] $ nm libd1.so [...] U base_print@@libbase.so.1 [...] U d2_print [...] $ ldd libd1.so [...] libbase.so.1 => ./libbase.so.1 [...] Interesting. The unresolved symbol base_print was changed in the linking step, but d2_print was not. This is because the version info was put into libbase.so (symlinked to libbase.so.1.0). libd2.so didn’t yet exist, so it can’t have version info attached. If you want version info for libd1 and libd2 referencing each other then you’ll first have to create versions of the libraries that don’t depend on each other but do have version info. It’s probably possible to bootstrap this manually, but I haven’t looked into it. Also note that libd1.so knows that it’s depending on libbase.so.1 (not plain libbase.so). This is the name given with the -soname option when linking libbase.so. So there’s even more magic going on than I led on. And it’s a good reason for having that option. libd2.so is compiled similarly, except against version 2 of libbase.so. The program p is then linked to both libd1.so and libd2.so, which in turn pulls in both versions of libbase.so: $ cc -Wl,-rpath=. -o p p.o -L. -Wl,-rpath=. -ld1 -ld2 $ ldd p linux-vdso.so.1 => (0x00007ffff41f8000) libd1.so => ./libd1.so (0x00007fe08b788000) libd2.so => ./libd2.so (0x00007fe08b586000) libc.so.6 => /lib/libc.so.6 (0x00007fe08b1e5000) libbase.so.1 => ./libbase.so.1 (0x00007fe08afe3000) libbase.so.2 => ./libbase.so.2 (0x00007fe08ade1000) /lib64/ld-linux-x86-64.so.2 (0x00007fe08b98c000) $ nm p | grep libd U d1@@libd1.so U d2@@libd2.so $ ./p base version 2> init base version 1> init d1> init d2> init d1() d2_print() base version 2> d1 <--- libd1 -> libd2 -> libbase version 2 d2() d1_print() base version 1> d2 <--- libd2 -> libd1 -> libbase version 1 d2> fini d1> fini base version 1> fini base version 2> fini Note that both base versions are loaded, and that d1() calls d<b>2</b>_print() and vice versa. Diamond problem solved. Yay! Manual with --version-script Instead of --default-syms one can use --version-script=base1.map and create the map file. BASE1 { global: base_print; local: *; }; ### Manual from within the code asm(“.symver base_print_foo,base_print@@BASE1”); ``` to create base_print@@BASE1 from base_print_foo. This may still need a map file, but it will override it. Notes Summary … yet Unix still has much less DLL hell than Windows. I aimed to provide an accessible view into shared libraries by solving a specific problem. For more in-depth information from people who know more about it than me see the links below. I’ve barely scratched the surface. The compile time linker ( ld) and the dynamic linker ( ld.so) do a lot of magic. More than you’d expect if you haven’t thought about it before. Links - Example project - How To Write Shared Libraries, by Ulrich Drepper - Program Library HOWTO - 3. Shared Libraries - ld.so GNU linker/loader - Gold readiness obstacle #1: Berkeley DB. Also see other linker related posts on that blog. - It’s not all gold that shines — Why underlinking is a bad thing. Nice illustrations of the problem. - Autotools Mythbuster - Chapter 3. Building All Kinds of Libraries — libtool - Why there are shared object files and a bunch of symlinks - Binutils ld manual - 3.9 VERSION Command
https://blog.habets.se/2012/05/Shared-libraries-diamond-problem.html
CC-MAIN-2022-21
refinedweb
1,236
69.48
Rendering to physical sizes, how to let it work on all platforms? I'm creating an application that should render things to physical sizes, i.e. an intermediate goal would be to render a square that is 4x3 cm on all displays (using both iOS & windows). (I understand that its not really possible to do this always correct as the real world size of screens varies) the problem I ran into today is that on iOS there is a 2x factor which I can't identify by using generic calls. QGuiApplication::primaryScreen()->devicePixelRatio() returns 1 on a iPad (incorrect? - iOS 9.3) and 2 on a iPhone (correct? - also iOS 9.3) or am i missing something? using a QQuickPaintedItem derived class in the paint(QPainter *painter) function: auto physicalpixelsperinch = painter->device->physicalDpiX() * QGuiApplication::primaryScreen()->devicePixelRatio(); is (more or less) correct for windows and a iPhone, but not for an iPad. what I am I missing here? Hi On Desktop and Android, something like this should work: import QtQuick.Window 2.2 Rectangle { property real mm: Screen.pixelDensity width: 40*mm height: 30*mm } The problem is that, on Android, depending on the devices, the hardware vendors dont supply reliable firmware, and usually Screen.pixelDensity doesnt give acurate values. On desktop, I usualy get correct values. Not sure abou t IOS, but please check it and let me know :) You could check out the pixelToInches function that is included in the V-Play SDK. @johngod Thank you so much, you're right Screen.pixelDensity would be the complete solution if it was in qml, sifting trough the qt source i was able that it was derived from: double pixelpermm = QGuiApplication::primaryScreen()->physicalDotsPerInch() / 25.4 //physicalDotsPerInchX() & physicalDotsPerInchY() also exist and it seems to be correct on both my iPhone & iPad quite wel (better than all other ways I found so far) @Lorenz thanks, but for the time being I want to stick to Qt as it is a paid sdk as soon as you go commercial
https://forum.qt.io/topic/79078/rendering-to-physical-sizes-how-to-let-it-work-on-all-platforms
CC-MAIN-2018-30
refinedweb
335
54.83
ReQL is the RethinkDB query language. It offers a very powerful and convenient way to manipulate JSON documents. This document is a gentle introduction to ReQL concepts. You don’t have to read it to be productive with RethinkDB, but it helps to understand some basics. Want to write useful queries right away? Check out the ten-minute guide. ReQL is different from other NoSQL query languages. It’s built on three key principles: .operator. runcommand and pass it an active database connection. Let’s look at these concepts in more detail. Note: the following examples use the Python driver, but most of them also apply to RethinkDB drivers for other languages. You start using ReQL in your program similarly to how you’d use other databases: import rethinkdb as r # import the RethinkDB package conn = r.connect() # connect to the server on localhost and default port But this is where the similarity ends. Instead of constructing strings and passing them to the database server, you access ReQL by using methods from the rethinkdb package: r.table_create('users').run(conn) # create a table `users` r.table('users').run(conn) # get an iterable cursor to the `users` table Every ReQL query, from filters, to updates, to table joins is done by calling appropriate methods. This design has the following advantages: - You can use the same programming environment and tools you’re already used to. - Learning the language is no different from learning any other library. - There is little to no chance of security issues that arise from string injection attacks. In ReQL, you can chain commands at the end of other commands using the . operator: # Get an iterable cursor to the `users` table (we've seen this above) r.table('users').run(conn) # Return only the `last_name` field of the documents r.table('users').pluck('last_name').run(conn) # Get all the distinct last names (remove duplicates) r.table('users').pluck('last_name').distinct().run(conn) # Count the number of distinct last names r.table('users').pluck('last_name').distinct().count().run(conn) Almost all ReQL operations are chainable. You can think of the . operator similarly to how you’d think of a Unix pipe. You select the data from the table and pipe it into a command that transforms it. You can continue chaining transformers until your query is done. In ReQL, data flows from left to right. Even if you have a cluster of RethinkDB nodes, you can send your queries to any node and the cluster will create and execute distributed programs that get the data from relevant nodes, perform the necessary computations, and present you with final results without you ever worrying about it. This design has the following advantages: - The language is easy to learn, read, and modify. - It’s a natural and convenient way to express queries. - You can construct queries incrementally by chaining transformations and examining intermediary results. While queries are built up on the client, they’re only sent to the server once you call the run command. All processing happens on the server—the queries don’t run on the client, and don’t require intermediary network round trips between the client and the server. For example, you can store queries in variables, and send them to the server later: # Create the query to get distinct last names distinct_lastnames_query = r.table('users').pluck('last_name').distinct() # Send it to the server and execute distinct_lastnames_query.run(conn) Read about how this technology is implemented for more details. ReQL queries are executed lazily: # Get up to five user documents that have the `age` field defined r.table('users').has_fields('age').limit(5).run(conn) For this query RethinkDB will perform enough work to get the five documents, and stop when the query is satisfied. Even if you don’t have a limit on the number of queries but use a cursor, RethinkDB will do just enough work to allow you to read the data you request. This allows queries to execute quickly without wasting CPU cycles, network bandwidth, and disk IO. Like most database systems, ReQL supports primary and secondary indexes to allow efficient data access. You can also create compound indexes and indexes based on arbitrary ReQL expressions to speed up complex queries. Learn how to use primary and secondary indexes in RethinkDB. All ReQL queries are automatically parallelized on the RethinkDB server as much as possible. Whenever possible, query execution is split across CPU cores, servers in the cluster, and even multiple datacenters. If you have large, complicated queries that require multiple stages of processing, RethinkDB will automatically break them up into stages, execute each stage in parallel, and combine data to return a complete result. While RethinkDB doesn’t currently have a fully-featured query optimizer, ReQL is designed with one in mind. For example, the server has enough information to reorder the chain for efficiency, or to use alternative implementation plans to improve performance. This feature will be introduced into future versions of RethinkDB. So far we’ve seen only simple queries without conditions. ReQL supports a familiar syntax for building more advanced queries: # Get all users older than 30 r.table('users').filter(lambda user: user['age'] > 30).run(conn) # If you'd like to avoid writing lambdas, RethinkDB supports an # alternative syntax: r.table('users').filter(r.row['age'] > 30).run(conn) This query looks just like any other Python code you would normally write. Note that RethinkDB will execute this query on the server, and it doesn’t execute native Python code. The client drivers do a lot of work to inspect the code and convert it to an efficient ReQL query that will be executed on the server: user['age'] > 30. lambdaexpression is executed only once on the client. Internally, the driver passes a special object to the lambdafunction which allows constructing a representation of the query. This representation is then sent to the server over the network and evaluated on the cluster. Read about how this technology is implemented for more details. This technology has limitations. While most operations allow you to write familiar code, you can’t use native language’s operations that have side effects (such as if and for). Instead, you have to use alternative ReQL commands: #) This design has the following advantages: - For most queries, you can write familiar, easy to learn code without learning special commands. - The queries are efficiently transported to the server (via protocol buffers), and evaluated in the cluster. - RethinkDB has access to the query structure, which allows for optimization techniques similar to those available in SQL. This feature will be added to RethinkDB in the future. This technology has the following limitation: - Native language’s operations that have side effects or control blocks cannot be used within a lambda. Learn more about how this design is implemented for details. You can combine multiple ReQL queries to build more complex ones. Let’s start with a simple example. RethinkDB supports server-side JavaScript evaluation using the embedded V8 engine (sandboxed within outside processes, of course): # Evaluate a JavaScript expression on the server and get the result r.js('1 + 1').run(conn) Because ReQL is composable you can combine the r.js command with any other query. For example, let’s use it as an alternative to get all users older than 30: # Get all users older than 30 (we've seen this above) r.table('users').filter(lambda user: user['age'] > 30).run(conn) # Get all users older than 30 using server-side JavaScript r.table('users').filter(r.js('(function (user) { return user.age > 30; })')).run(conn) RethinkDB will seamlessly evaluate the js command by calling into the V8 engine during the evaluation of the filter query. You can combine most queries this way into progressively more complex ones. Let’s say we have another table authors, and we’d like to get a list of authors whose last names are also in the users table we’ve seen before. We can do it by combining two queries: # Find all authors whose last names are also in the `users` table r.table('authors').filter(lambda author: r.table('users').pluck('last_name').contains(author.pluck('last_name'))). run(conn) Here, we use the r.table('users').pluck('last_name') query as the inner query in filter, combining the two queries to build a more sophisticated one. Even if you have a cluster of servers and both the authors table and the users table are sharded, RethinkDB will do the right thing and evaluate relevant parts of the query above on the appropriate shards, combine bits of data as necessary, and return the complete result. A few things to note about this query: - We compose the query on the client and call runonly once. Remember to call runonly once on the complex query when you’re ready for it to be executed. - You can also perform this query using the inner_join command. Composing queries isn’t limited to simple commands and inner queries. You can also use expressions to perform complex operations. For example, suppose we’d like to find all users whose salary and bonus don’t exceed $90,000, and increase their salary by 10%: r.table('users').filter(lambda user: user['salary'] + user['bonus'] < 90000) .update(lambda user: {'salary': user['salary'] + user['salary'] * 0.1}) In addition to commands described here, ReQL supports a number of sophisticated commands that are composable similarly to the commands described here. See the following documentation for more details: This design has the following advantages: - Unlike most NoSQL languages, you can use ReQL to build queries of arbitrary complexity. - There is no new syntax or new commands for complex queries. Once you understand the composition principle you can write new queries without learning anything else. - Subqueries can be abstracted in variables, which allows for modular programming in the same way as done by most other modern programming languages. Just in case you needed another calculator, ReQL can do that too! # Add two plus two (r.expr(2) + r.expr(2)).run(conn) # You only need to specify `r.expr` once for the driver to work (r.expr(2) + 2).run(conn) # More algebra (r.expr(2) + 2 / 2).run(conn) # Logic (r.expr(2) > 3).run(conn) # Branches r.branch(r.expr(2) > 3, 1, # if True, return 1 2 # otherwise, return 2 ).run(conn) # Compute the Fibonacci sequence r.table_create('fib').run(conn) r.table('fib').insert([{'id': 0, 'value': 0}, {'id': 1, 'value': 1}]).run(conn) r.expr([2, 3, 4, 5, 6, 7, 8, 9, 10, 11]).for_each(lambda x: r.table('fib').insert({'id': x, 'value': (r.table('fib').order_by('id').nth(x - 1)['value'] + r.table('fib').order_by('id').nth(x - 2)['value']) })).run(conn) r.table('fib').order_by('id')['value'].run(conn) Browse the following resources to learn more about ReQL: © RethinkDB contributors Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License.
https://docs.w3cub.com/rethinkdb~java/docs/introduction-to-reql/
CC-MAIN-2019-18
refinedweb
1,825
57.57
If you're thinking that you should try changing a readonly property.. well, in short, you almost certainly shouldn't try. For example, the following class has a property that should only be set in its constructor and then never mutated again - public sealed class Example { public Example(int id) { Id = id; } public int Id { get; } } And it is a good thing that we are able to write code so easily that communicates precisely when a property may (and may not) change. However.. You might have some very particular scenario in mind where you really do want to try to write to a readonly auto-property's value for an instance that has already been created. It's possible that you are writing some interesting deserialisation code, I suppose. For something that I was looking at, I was curious to look into how feasible it is (or isn't) and I came up with the following three basic approaches. I think that each approach demonstrates something a little off the beaten track of .NET - granted, there's absolutely nothing here that's never been done before.. but sometimes it's fun to be reminded of how flexible .NET can be, if only to appreciate how hard it works to keep everything reliable and consistent. I'll show three approaches, in decreasing order of ease of writing. They all depend upon a particular naming conventions in .NET's internals that is not documented and should not be considered reliable (ie. a future version of C# and/or the compiler could break it). Even if you ignore this potential time bomb, only the first of the three methods will actually work. Like I said at the start, this is something that you almost certainly shouldn't be attempting anyway! C# 6 introduced read-only auto-properties. Before thoses were available, you had two options to do something similar. You could use a private setter - public sealed class Example { public Example(int id) { Id = id; } public int Id { get; private set; } } .. or you could manually create a private readonly backing field for the property - public sealed class Example { private readonly int _id; public Example(int id) { _id = id; } public int Id { get { return _id; } } } The first approach requires less code but the guarantees that it claims to make are less strict. When a field is readonly then it may only be set within a constructor but when it has a private setter then it could feasibly change at any point in the lifetime of the instance. In the class above, it's clear to see that it is only set in the constructor but there are no compiler assurances that someone won't come along and add a method to the Example class that mutates the private-setter "Id" property. If you have a readonly "_id" backing field then it would not be possible to write a method to mutate the value*. * (Without resorting to the sort of shenanigans that we are going to look at here) So the second class is more reliable and more accurately conveys the author's intentions for the code (that the "Id" property of an Example instance will never change during its lifetime). The disadvantage is that there is more code to write. The C# 6 syntax is the best of both worlds - as short (shorter, in fact, since there is no setter defined) as the first version but with the stronger guarantees of the second version. Interestingly, the compiler generates IL that is essentially identical to that which result from the C# 5 syntax where you manually define a property that backs onto a readonly field. The only real difference relates to the fact that it wants to be sure that it can inject a readonly backing field whose name won't clash with any other field that the human code writer may have added to the class. To do this, it uses characters in the generated field names that are not valid to appear in C#, such as "<Id>k__BackingField". The triangle brackets may not be used in C# code but they may be used in the IL code that the compiler generates. And, just to make things extra clear, it adds a [CompilerGenerated] attribute to the backing field. This is sufficient information for us to try to identify the compiler-generated backing field using reflection. Going back to this version of the class: public sealed class Example { public Example(int id) { Id = id; } public int Id { get; } } .. we can identify the backing field for the "Id" property with the following code: var type = typeof(Example); var property = type.GetProperty("Id"); var backingField = type .GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static) .FirstOrDefault(field => field.Attributes.HasFlag(FieldAttributes.Private) && field.Attributes.HasFlag(FieldAttributes.InitOnly) && field.CustomAttributes.Any(attr => attr.AttributeType == typeof(CompilerGeneratedAttribute)) && (field.DeclaringType == property.DeclaringType) && field.FieldType.IsAssignableFrom(property.PropertyType) && field.Name.StartsWith("<" + property.Name + ">") ); With this backingField reference, we can start doing devious things. Like this: // Create an instance with a readonly auto-property var x = new Example(123); Console.WriteLine(x.Id); // Prints "123" // Now change the value of that readonly auto-property! backingField.SetValue(x, 456); Console.WriteLine(x.Id); // Prints "456" We took an instance of a class that has a readonly property (meaning that it should never change after the instance has been constructed) and we changed that property. Evil. One more time, though: this relies upon the current convention that the compiler-generated backing fields follow a particular naming convention. If that changes one day then this code will fail. Enough with the boring warnings, though - let's get to the real nub of the matter; reflection is slooooooooow, isn't it? Surely we should never resort to such a clunky technology?? If Example had a regular private field that we wanted to set - eg. public sealed class Example { private int _somethingElse; public Example(int id, int somethingElse) { Id = id; _somethingElse = somethingElse; } public int Id { get; } public int GetSomethingElse() { return _somethingElse; } } Then we could use reflection to get a reference to that field once and build a delegate using LINQ Expressions that would allow us to update that field value using something like this: var field = typeof(Example).GetField("_somethingElse", BindingFlags.Instance | BindingFlags.NonPublic); var sourceParameter = Expression.Parameter(typeof(Example), "source"); var valueParameter = Expression.Parameter(field.FieldType, "value"); var fieldSetter = Expression.Lambda<Action<Example, int>>( Expression.Assign( Expression.MakeMemberAccess(sourceParameter, field), valueParameter ), sourceParameter, valueParameter ) .Compile(); We could then cache that "fieldSetter" delegate and call it any time that we wanted to update the private "_somethingElse" field on an Example instance. There would be a one-off cost to the reflection that identifies the field and a one-off cost to generating that delegate initially but any subsequent call should be comparably quick to hand-written field-updating code (obviously it's not possible to hand-write code to update a private field from outside the class.. but you get the point). There's one big problem with this approach, though; it doesn't work for readonly fields. The "Expression.Assign" call will throw an ArgumentException if the specified member is readonly: Expression must be writeable SAD FACE. This is quite unfortunate. It had been a little while since I'd played around with LINQ Expressions and I was feeling quite proud of myself getting the code to work.. only to fall at the last hurdle. Never mind. One bright side is that I also tried out this code in a .NET Core application and it worked to the same extent as the "full fat" .NET Framework - ie. I was able to generate a delegate using LINQ Expressions that would set a non-readonly private field on an instance. Considering that reflection capabilities were limited in the early days of .NET Standard, I found it a nice surprise that support seems so mature now. Time to bring out the big guns! If the friendlier way of writing code that dynamically compiles other .NET code (ie. LINQ Expressions) wouldn't cut it, surely the old fashioned (and frankly intimidating) route of writing code to directly emit IL would do the job? It's been a long time since I've written any IL-generating code, so let's take it slow. If we're starting with the case that worked with LINQ Expressions then we want to create a method that will take an Example instance and an int value in order to set the "_somethingElse" field on the Example instance to that new number. The first thing to do is to create some scaffolding. The following code is almost enough to create a new method of type Action<Example, int> - // Set restrictedSkipVisibility to true to avoid any pesky "visibility" checks being made (in other // words, let the IL in the generated method access any private types or members that it tries to) var method = new DynamicMethod( name: "SetSomethingElseField", returnType: null, parameterTypes: new[] { typeof(Example), typeof(int) }, restrictedSkipVisibility: true ); var gen = method.GetILGenerator(); // TODO: Emit require IL op codes here.. var fieldSetter = (Action<Example, int>)method.CreateDelegate(typeof(Action<Example, int>)); The only problem is that "TODO" section.. the bit where we have to know what IL to generate. There are basically two ways you can go about working out what to write here. You can learn enough about IL (and remember it again years after you learn some!) that you can just start hammering away at the keyboard.. or you can write some C# that basically does what you want, compile that using Visual Studio and then use a disassembler to see what IL is produced. I'm going for plan b. Handily, if you use Visual Studio then you probably already have a disassembler installed! It's called ildasm.exe and I found it on my computer in "C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools" after reading this: "Where are the SDK tools? Where is ildasm?". To make things as simple as possible, I created a new class in a C# project - class SomethingWithPublicField { public int Id; } and then created a static method that I would want to look at the disassembly of: static void MethodToCopy(SomethingWithPublicField source, int value) { source.Id = value; } I compiled the console app, opened the exe in ildasm and located the method. Double-clicking it revealed this: .method private hidebysig static void MethodToCopy(class Test.Program/SomethingWithPublicField source, int32 'value') cil managed { // Code size 9 (0x9) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: stfld int32 Test.Program/SomethingWithPublicField::Id IL_0008: ret } // end of method Program::MethodToCopyTyped Ok. That actually couldn't be much simpler. The "ldarg.0" code means "load argument 0 onto the stack", "ldarg.1" means "load argument 1 onto the stack" and "stfld" means take the instance of the first object on the stack and set the specified field to be the second object on the stack. "ret" just means exit method (returning any value, if there is one - which there isn't in this case). This means that the "TODO" comment in my scaffolding code may be replaced with real content, resulting in the following: var field = typeof(Example).GetField("_somethingElse", BindingFlags.Instance | BindingFlags.NonPublic); var method = new DynamicMethod( name: "SetSomethingElseField", returnType: null, parameterTypes: new[] { typeof(Example), typeof(int) }, restrictedSkipVisibility: true ); var gen = method.GetILGenerator(); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldarg_1); gen.Emit(OpCodes.Stfld, field); gen.Emit(OpCodes.Ret); var fieldSetter = (Action<Example, int>)method.CreateDelegate(typeof(Action<Example, int>)); That's it! We now have a delegate that is a compiled method for writing a new int into the private field "_somethingElse" for any given instance of Example. Unfortunately, things go wrong at exactly the same point as they did with LINQ Expressions. The above code works fine for setting a regular private field but if we tried to set a readonly field using the same approach then we'd be rewarded with an error: System.Security.VerificationException: 'Operation could destabilize the runtime.' Another disappointment!* * (Though hopefully not a surprise if you're reading this article since I said right at the top that only the first of these three approaches would work!) But, again, to try to find a silver lining, I also tried the non-readonly-private-field-setting-via-emitted-IL code in a .NET Core application and I was pleasantly surprised to find that it worked. It required the packages "System.Reflection.Emit.ILGeneration" and "System.Reflection.Emit.Lightweight" to be added through NuGet but nothing more difficult than that. Although I decided last month that I'm still not convinced that .NET Core is ready for me to use in work, I am impressed by how much does work with it. Update (9th March 2021): I realised some time after writing this post that it is possible to make this work with emitted IL, the only difference required is to take this code: var method = new DynamicMethod( name: "SetSomethingElseField", returnType: null, parameterTypes: new[] { typeof(Example), typeof(int) }, restrictedSkipVisibility: true ); .. and add an additional argument like this: var method = new DynamicMethod( name: "SetSomethingElseField", returnType: null, parameterTypes: new[] { typeof(Example), typeof(int) }, m: field.DeclaringType.Module, restrictedSkipVisibility: true ); I haven't recreated the benchmarks to try this code, I'm hoping that the performance difference will be minimal between setting a private readonly field via emitted IL and setting a private non-readonly field via emitted IL (which is benchmarked below). I'm using this approach in my DanSerialiser project. So we've ascertained that there is only one way* to set a readonly field on an existing instance and, regrettably, it's also the slowest. I guess that a pertinent question to ask, though, is just how much slower is the slowest? * (As further evidence that there isn't another way around this, I've found an issue from EntityFramework's GitHub repo: "Support readonly fields" which says that it's possible to set a readonly property with reflection but that the issue-raiser encountered the same two failures that I've demonstrated above when he tried alternatives and no-one has proposed any other ways to tackle it) Obviously we can't compare the readonly-field-setting performance of the three approaches above because only one of them is actually capable of doing that. But we can compare the performance of something similar; setting a private (but not readonly) field, since all three are able to achieve that. Ordinarily at this point, I would write some test methods and run them in a loop and time the loop and divide by the number of runs and then maybe repeat a few times for good measure and come up with a conclusion. Today, though, I thought that I might try something a bit different because I recently heard again about something called "BenchmarkDotNet". It claims. This sounds ideal for my purposes! What I'm most interesting in is how reflection compares to compiled LINQ expressions and to emitted IL when it comes to setting a private field. If this is of any importance whatsoever then presumably the code will be run over and over again and so it should be the execution time of the compiled property-setting code that is of interest - the time taken to actually compile the LINQ expressions / emitted IL can probably be ignored as it should disappear into insignificance when the delegates are called enough times. But, for a sense of thoroughness (and because BenchmarkDotNet makes it so easy), I'll also measure the time that it takes to do the delegate compilation as well. To do this, I created a .NET Core Console application in VS2017, added the BenchmarkDotNet NuGet package and changed the .csproj file by hand to build for both .NET Core and .NET Framework 4.6.1 by changing <TargetFramework>netcoreapp1.1</TargetFramework> to <TargetFrameworks>netcoreapp1.1;net461</TargetFrameworks> <PlatformTarget>AnyCPU</PlatformTarget> (as described in the BenchmarkDotNet FAQ). Then I put the following together. There are six benchmarks in total; three to measure the creation of the different types of property-setting delegates and three to then measure the execution time of those delegates - class Program { static void Main(string[] args) { BenchmarkRunner.Run<TimedSetter>(); Console.ReadLine(); } } [CoreJob, ClrJob] public class TimedSetter { private SomethingWithPrivateField _target; private FieldInfo _field; private Action<SomethingWithPrivateField, int> _reflectionSetter, _linqExpressionSetter, _emittedILSetter; [GlobalSetup] public void GlobalSetup() { _target = new SomethingWithPrivateField(); _field = typeof(SomethingWithPrivateField) .GetFields(BindingFlags.NonPublic | BindingFlags.Instance) .FirstOrDefault(f => f.Name == "_id"); _reflectionSetter = ConstructReflectionSetter(); _linqExpressionSetter = ConstructLinqExpressionSetter(); _emittedILSetter = ConstructEmittedILSetter(); } [Benchmark] public Action<SomethingWithPrivateField, int> ConstructReflectionSetter() { return (source, value) => _field.SetValue(source, value); } [Benchmark] public Action<SomethingWithPrivateField, int> ConstructLinqExpressionSetter() { var sourceParameter = Expression.Parameter(typeof(SomethingWithPrivateField), "source"); var valueParameter = Expression.Parameter(_field.FieldType, "value"); var fail = Expression.Assign( Expression.MakeMemberAccess(sourceParameter, _field), valueParameter ); return Expression.Lambda<Action<SomethingWithPrivateField, int>>( Expression.Assign( Expression.MakeMemberAccess(sourceParameter, _field), valueParameter ), sourceParameter, valueParameter ) .Compile(); } [Benchmark] public Action<SomethingWithPrivateField, int> ConstructEmittedILSetter() { var method = new DynamicMethod( name: "SetField", returnType: null, parameterTypes: new[] { typeof(SomethingWithPrivateField), typeof(int) }, restrictedSkipVisibility: true ); var gen = method.GetILGenerator(); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldarg_1); gen.Emit(OpCodes.Stfld, _field); gen.Emit(OpCodes.Ret); return (Action<SomethingWithPrivateField, int>)method.CreateDelegate( typeof(Action<SomethingWithPrivateField, int>) ); } [Benchmark] public void SetUsingReflection() { _reflectionSetter(_target, 1); } [Benchmark] public void SetUsingLinqExpressions() { _linqExpressionSetter(_target, 1); } [Benchmark] public void SetUsingEmittedIL() { _emittedILSetter(_target, 1); } } public class SomethingWithPrivateField { private int _id; } The "GlobalSetup" method will be run once and will construct the delegates for delegate-executing benchmark methods ("SetUsingReflection", "SetUsingLinqExpressions" and "SetUsingEmittedIL"). The time that it takes to execute the [GlobalSetup] method does not contribute to any of the benchmark method times - the benchmark methods will record only their own execution time. However, having delegate-creation benchmark methods ("ConstructReflectionSetter", "ConstructLinqExpressionSetter" and "ConstructEmittedILSetter") means that I'll have an idea how large the initial cost to construct each delegate is (or isn't), separate to the cost of executing each type of delegate. BenchmarkDotNet has capabilities beyond what I've taken advantage of. For example, it can also build for Mono (though I don't have Mono installed on my computer, so I didn't try this) and it can test 32-bit vs 64-bit builds. Aside from testing .NET Core 1.1 and .NET Framework 4.6.1, I've kept things fairly simple. After it has run, it emits the following summary about my computer: BenchmarkDotNet=v0.10.8, OS=Windows 8.1 (6.3.9600) Processor=AMD FX(tm)-8350 Eight-Core Processor, ProcessorCount=8 Frequency=14318180 Hz, Resolution=69.8413 ns, Timer=HPET dotnet cli version=1.0.4 [Host] : .NET Core 4.6.25211.01, 64bit RyuJIT [AttachedDebugger] Clr : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1087.0 Core : .NET Core 4.6.25211.01, 64bit RyuJIT And produces the following table: The easiest thing to interpret is the "Mean" - BenchmarkDotNet did a few "pilot runs" to try to see how long the benchmark methods would take and then tries to decide what is an appropriate number of runs to do for real in order to get reliable results. The short version is that when delegates are compiled using LINQ Expressions and emitted-IL that they both execute a lot faster than reflection; over 85x faster for .NET Framework 4.6.1 and 1,500x faster for .NET Core 1.1! The huge difference between reflection and the other two approaches, though, may slightly overshadow the fact that the LINQ Expression delegates are actually about 1.6x faster than the emitted-IL delegates. I hadn't expected this at all, I would have thought that they would be almost identical - in fact, I'm still surprised and don't currently have any explanation for it. The mean value doesn't usually tell the whole story, though. When looking at the mean, it's also useful to look at the Standard Deviation ("StdDev" in the table above). The mean might be within a small spread of values or a very large spread of values. A small spread is better because it suggests that the single mean value that we're looking at is representative of behaviour in the real world and that values aren't likely to vary too wildly - a large standard deviation means that there was much more variation in the recorded values and so the times could be all over the place in the real world. (Along similar lines, the "Error" value is described as being "Half of 99.9% confidence interval" - again, the gist is that smaller values suggest that the mean is a more useful indicator of what we would see in the real world for any given request). What I've ignored until this point are the "ConstructReflectionSetter" / "ConstructLinqExpressionSetter" / "ConstructEmittedILSetter" methods. If we first look at the generation of the LINQ Expression delegate on .NET 4.6.1, we can see that the mean time to generate that delegate was around 150ms - compared to approx 10ms for the reflection delegate. Each time the LINQ Expressions delegate is used to set the field instead of the reflection delegate we save around 0.16ms. That means that we need to call the delegate around 950 times in order to pay of the cost of constructing it! As I suggested earlier, it would only make sense to investigate these sort of optimisations if you expect to execute the code over and over and over again (otherwise, why not just keep it simple and stick to using plain old reflection).. but it's still useful to have the information about just how much "upfront cost" there is to things like this, compared to how much you hope to save in the long run. It's also interesting to see the discrepancies between .NET Framework 4.6.1 and .NET Core 1.1 - the times to compile LINQ Expressions and emitted-IL delegates are noticeably shorter and the time to set the private field by reflection noticeably longer. In fact, these differences mean that you only need to set the field 25 times before you start to offset the cost of creating the LINQ Expressions delegate (when you compare it to updating the field using reflection) and only 14 times to offset the cost of creating the emitted-IL delegate! I'm really happy with how easy BenchmarkDotNet makes it to measure these sorts of very short operations. Whenever I've tried to do something similar in the past, I've felt niggling doubts that maybe I'm not running it enough times or maybe there are some factors that I should try to average out. Even when I get a result, I've sometimes just looked at the single average (ie. the mean) time taken, which is a bit sloppy since the spread of results can be of vital importance as well. That BenchmarkDotNet presents the final data in such a useful way and with so few decisions on my part is fantastic. I forget each time that I start a new project how the running-benchmarks-against-multiple-frameworks functionality works, so I'll add a note here for anyone else that gets confused (and, likely, for me in the future!) - the first thing to do is to manually edit the .csproj file of the benchmark project so that it includes the following: <TargetFrameworks>netcoreapp2.0;net461</TargetFrameworks> It's not currently possible to specify multiple projects using the VS GUI, so your .csproj file will normally have a line like this: <TargetFramework>netcoreapp2.0</TargetFramework> (Not only is there only a single framework specified but the node is called "TargetFramework" - without an "s" - as opposed to "TargetFrameworks" with an "s") After you've done this, you need to run the benchmark project from the command line (if you try to run it from within VS, even in Release configuation, you will get a warning that the results may be inaccurate as a debugger is attached). You do that with a command like this (it may vary if you're using a different version of .NET Core) - dotnet run --framework netcoreapp2.0 --configuration release You have to specify a framework to run the project as but (and this is the important part) that does not mean that the benchmarks will only be run against the framework. What happens when you run this command is that multiple executables are built and then executed, which run the tests in each of the frameworks that you specified in the benchmark attributes and in the "TargetFrameworks" node in the .csproj file. The results of these multiple executables are aggregated to give you the final benchmark output. On the other hand, unfortunately .NET Core has been hard work for me again when it came to BenchmarkDotNet. I made it sound very easy earlier to get everything up and running because I didn't want dilute my enthusiasm for the benchmarking. However, I did have a myriad of problems before everything started working properly. When I was hand-editing the .csproj file to target multiple frameworks (I still don't know why this isn't possible within VS when editing project properties), Visual Studio would only seem to intermittently acknowledge that I'd changed it and offer to reload. This wasn't super-critical but it also didn't fill me with confidence. When it was ready to build and target both .NET Framework 4.6.1 and .NET Core 1.1, I got a cryptic warning: Detected package downgrade: Microsoft.NETCore.App from 1.1.2 to 1.1.1 CoreExeTest (>= 1.0.0) -> BenchmarkDotNet (>= 0.10.8) -> Microsoft.NETCore.App (>= 1.1.2) CoreExeTest (>= 1.0.0) -> Microsoft.NETCore.App (>= 1.1.1) Everything seemed to build alright but I didn't know if this was something to worry about or not (I like my projects to be zero-warning). It suggested to me that I was targeting .NET Core 1.1 and BenchmarkDotNet was expecting .NET Core 1.1.2 - sounds simple enough, surely I can upgrade? I first tried changing the .csproj to target "netcoreapp1.1.2" but that didn't work. In fact, it "didnt work" in a very unhelpful way; when I ran the project it would open in a window and immediately close, with no way to break and catch the exception in the debugger. I used "dotnet run"* on the command line to try to see more information and was then able to see the error message: The specified framework 'Microsoft.NETCore.App', version '1.1.2' was not found. - Check application dependencies and target a framework version installed at: C:\Program Files\dotnet\shared\Microsoft.NETCore.App - The following versions are installed: 1.0.1 1.0.4 1.1.1 - Alternatively, install the framework version '1.1.2'. * (Before being able to use "dotnet run" I had to manually edit the .csproj file to only target .NET Core - if you target multiple frameworks and try to use "dotnet run" then you get an error "Unable to run your project. Please ensure you have a runnable project type and ensure 'dotnet run' supports this project") I changed the .csproj file back from "netcoreapp1.1.2" to "netcoreapp1.1" and went to the NuGet UI to see if I could upgrade the "Microsoft.NETCore.App" package.. but the version dropdown wouldn't let me change it (stating that the other versions that it was aware of were "Blocked by project"). I tried searching online for a way to download and install 1.1.2 but got nowhere. Finally, I saw that VS 2017 had an update pending entitled "Visual Studio 15.2 (26430.16)". The "15.2" caught me out for a minute because I initially presumed it was an update for VS 2015. The update includes .NET Core 1.1.2 (see this dotnet GitHub issue) and, when I loaded my solution again, the warning above had gone. Looking at the installed packages for my project, I saw that "Microsoft.NETCore.App" was now on version 1.1.2 and that all other versions were "Blocked by project". This does not feel friendly and makes me worry about sharing code with others - if they don't have the latest version of Visual Studio then the code may cause them warnings like the above that don't happen on my PC. Yuck. After all this, I got the project compiling (without warnings) and running, only for it to intermittently fail as soon as it started: Access to the path 'BDN.Generated.dll' is defined This relates to an output folder created by BenchmarkDotNet. Sometimes this folder would be locked and it would not be possible to overwrite the files on the next run. Windows wouldn't let me delete the folder directly but I could trick it by renaming the folder and then deleting it. I didn't encounter this problem if I created an old-style .NET Framework project and used BenchmarkDotNet there - this would prevent me from running tests against multiple frameworks but it might have also prevented me from teetering over the brink of insanity. This is not how I would expect mature tooling to behave. For now, I continue to consider .NET Core as the Top Gear boys (when they still were the Top Gear boys) described old Alfa Romeos; "you want to believe that it can be something wonderful but you couldn't, in all good conscience, recommend it to a friend". I suspect that, to some, this may seem like one of my more pointless blog posts. I tried to do something that .NET really doesn't want you to do (and that whoever wrote the code containing the readonly auto-properties really doesn't expect you to do) and then tried to optimise that naughty behaviour - then spent a lot more time explaining how it wasn't posible to do so! However, along the way I discovered BenchmarkDotNet and I'm counting that as a win - I'll be keeping that in my arsenal for future endeavours. And I also enjoyed revisiting what is and isn't possible with reflection and reminding myself of the ways that .NET allows you to write code that could make my code appear to work in surprising ways. Finally, it was interesting to see how the .NET Framework compared to .NET Core in terms of performance for these benchmarks and to see take another look at the question of how mature .NET Core and its tooling is (or isn't). And when you learn a few things, can it ever really count as a waste of time? A comment on this post by "ai_enabled" asked about the use of the reflection method "SetValueDirect" instead of "SetValue". I must admit that I was unaware of this method but it was an interesting question posed about its performance in comparison to "SetValue" and there was a very important point made about the code that I'd presented so far when it comes to structs; in particular, because structs are copied when they're passed around, the property-update mechanisms that I've shown wouldn't have worked. I'll try to demonstrate this with some code: public static void Main() { var field = typeof(SomeStructWithPrivateField) .GetFields(BindingFlags.NonPublic | BindingFlags.Instance) .FirstOrDefault(f => f.Name == "_id"); // FAIL! "target" will still have an "_id" value of zero :( var target = new SomeStructWithPrivateField(); field.SetValue(target, 123); } public struct SomeStructWithPrivateField { private int _id; } Because the "SetValue" method's first parameter is of type object, the "target" struct will get boxed - any time that a non-reference type is passed as an argument where a reference type is expected, it effectively gets "wrapped up" into an object. I won't go into all of the details of boxing / unboxing here (if you're interested, though, then "Boxing and Unboxing (C# Programming Guide)" is a good starting point) but one important thing to note is that structs are copied as part of the boxing process. This means "SetValue" will be working on a copy of "target" and so the "_id" property of the "target" value will not be changed by the "SetValue" call! The way around this is to use "SetValueDirect", which takes a special TypedReference argument. The way in which this is done is via the little-known "__makeref" keyword (I wasn't aware of it before looking into "SetValueDirect") - public static void Main() { var field = typeof(SomeStructWithPrivateField) .GetFields(BindingFlags.NonPublic | BindingFlags.Instance) .FirstOrDefault(f => f.Name == "_id"); // SUCCESS! "target" will have its "_id" value updated! var target = new SomeStructWithPrivateField(); field.SetValueDirect(__makeref(target), 123); } If we wanted to wrap this up into a delegate then we need to ensure that the target parameter is marked as being "ref", otherwise we'll end up creating another place that the struct gets copied and the update lost. That means that we can no longer use something like: Action<SomeStructWithPrivateField, int> In fact, we can't use the generic Action class at all because it doesn't allow for "ref" parameters to be specified. Instead, we'll need to define a new delegate - public delegate void Updater(ref SomeStructWithPrivateField target, int value); Instances of this may be created like this: var field = typeof(SomeStructWithPrivateField) .GetFields(BindingFlags.NonPublic | BindingFlags.Instance) .FirstOrDefault(f => f.Name == "_id"); Updater updater = (ref SomeStructWithPrivateField target, int value) => field.SetValueDirect(__makeref(target), id); If we want to do the same with the LINQ Expressions or generated IL approaches then we need only make some minor code tweaks to what we saw earlier. The first argument of the generated delegates must be changed to be a "ref" type and we need to generate a delegate of type Updater instead of Action<SomeStructWithPrivateField, int> - // Construct an "Updater" delegate using LINQ Expressions var sourceParameter = Expression.Parameter( typeof(SomeStructWithPrivateField).MakeByRefType(), "source" ); var valueParameter = Expression.Parameter(field.FieldType, "value"); var fail = Expression.Assign( Expression.MakeMemberAccess(sourceParameter, field), valueParameter ); var linqExpressionUpdater = Expression.Lambda<Updater>( Expression.Assign( Expression.MakeMemberAccess(sourceParameter, field), valueParameter ), sourceParameter, valueParameter ) .Compile(); // Construct an "Updater" delegate by generating IL var method = new DynamicMethod( name: "SetField", returnType: null, parameterTypes: new[] { typeof(SomeStructWithPrivateField).MakeByRefType(), typeof(int) }, restrictedSkipVisibility: true ); var gen = method.GetILGenerator(); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldind_Ref); gen.Emit(OpCodes.Ldarg_1); gen.Emit(OpCodes.Stfld, field); gen.Emit(OpCodes.Ret); var emittedIlUpdater = (Updater)method.CreateDelegate(typeof(Updater)); (Note: There is an additional "Ldind_Ref" instruction required for the IL to "unwrap" the ref argument but it's otherwise the same) I used BenchmarkDotNet again to compare the performance of the two reflection methods ("SetValue" and "SetValueDirect") against LINQ Expressions and emitted IL when setting a private field on an instance and found that having to call "__makeRef" and "SetValueDirect" was much slower on .NET 4.6.1 than just calling "SetValue" (about 17x slower) but actually marginally faster on .NET Core. It's worth noting that the LINQ Expressions and emitted-IL approaches are slightly slower when working with a "ref" parameter than they were in the original version of the code. I suppose that this makes sense because there is an extra instruction explicitly required in the emitted-IL code and the LINQ-Expression-constructed delegate will have to deal with the added indirection under the hood (though this happens "by magic" and the way that LINQ Expressions code doesn't need to be changed to account for it). I guess that it's possible that "SetValueDirect" could be faster if you already have a TypedReference (which is what "__makeRef" gives you) and you want to set multiple properties on it.. but that wasn't the use case that I had in mind when I looked into all of this and so I haven't tried to measured that. All in all, this was another fun diversion. It's curious that the performance between using "SetValue" and "__makeRef" / "SetValueDirect" is so pronounced in the "classic" .NET Framework but much less so in Core. On the other hand, if the target reference is a struct then the performance discrepancies are moot since trying to use "SetValue" won't work! If you want to try to reproduce this for yourself in .NET Core then (accurate as of 8th August 2017) you need to install Visual Studio 2017 15.3 Preview 2 so that you can build .NET Core 2.0 projects and you'll then need to install the NuGet package "System.Runtime.CompilerServices.Unsafe"*. Without both of these, you won't be able to use "__makeRef", you'll get a slightly cryptic error: Predefined type 'System.TypedReference' is not defined or imported * (I found this out via Ben Bowen's post "Fun With __makeref") Once you have these bleeding edge bits, though, you can build a project with BenchmarkDotNet tests configured to run in both .NET Framework and .NET Core with a .csproj like this: <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFrameworks>netcoreapp2.0;net461</TargetFrameworks> <PlatformTarget>AnyCPU</PlatformTarget> </PropertyGroup> <ItemGroup> <PackageReference Include="BenchmarkDotNet" Version="0.10.8" /> </ItemGroup> </Project> and you can run the tests in both frameworks using this: dotnet run --framework netcoreapp2.0 --configuration release Don't be fooled by the fact that you have to specify a single framework - through BenchmarkDotNet magic, the tests will be run for both frameworks (so long as you annotate the benchmark class with "[CoreJob, ClrJob]") and the results will be displayed in one convenient combined table at the end. Posted at 20:31 Dan is a big geek who likes making stuff with computers! He can be quite outspoken so clearly needs a blog :) In the last few minutes he seems to have taken to referring to himself in the third person. He's quite enjoying it.
https://www.productiverage.com/trying-to-set-a-readonly-autoproperty-value-externally-plus-a-little-benchmarkdotnet
CC-MAIN-2022-05
refinedweb
6,289
54.32